Date: 2021-03-03T22:27:17+00:00

Actual source code: bddcprivate.c
petsc-3.14.5 2021-03-03
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:   PetscInt               *emarks;
    175:   PetscBool              print,eerr,done,lrc[2],conforming,global,singular,setprimal;
    176:   PetscErrorCode         ierr;

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

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

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

    217:   /* Get Nedelec field */
    218:   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);
    219:   if (pcbddc->n_ISForDofsLocal && field >= 0) {
    220:     PetscObjectReference((PetscObject)pcbddc->ISForDofsLocal[field]);
    221:     nedfieldlocal = pcbddc->ISForDofsLocal[field];
    222:     ISGetLocalSize(nedfieldlocal,&ne);
    223:   } else if (!pcbddc->n_ISForDofsLocal && field != PETSC_DECIDE) {
    224:     ne            = n;
    225:     nedfieldlocal = NULL;
    226:     global        = PETSC_TRUE;
    227:   } else if (field == PETSC_DECIDE) {
    228:     PetscInt rst,ren,*idx;

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

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

    249:   /* Sanity checks */
    250:   if (!order && !conforming) SETERRQ(comm,PETSC_ERR_SUP,"Variable order and non-conforming spaces are not supported at the same time");
    251:   if (pcbddc->user_ChangeOfBasisMatrix) SETERRQ(comm,PETSC_ERR_SUP,"Cannot generate Nedelec support with user defined change of basis");
    252:   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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    612:   /* Get the local G^T explicitly */
    613:   MatDestroy(&lGt);
    614:   MatTranspose(lG,MAT_INITIAL_MATRIX,&lGt);
    615:   MatSetOption(lGt,MAT_KEEP_NONZERO_PATTERN,PETSC_FALSE);

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

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

    633:   if (print) {
    634:     IS tbz;

    636:     cum = 0;
    637:     for (i=0;i<nv;i++)
    638:       if (sfvleaves[i])
    639:         vmarks[cum++] = i;

    641:     ISCreateGeneral(PETSC_COMM_SELF,cum,vmarks,PETSC_COPY_VALUES,&tbz);
    642:     PetscObjectSetName((PetscObject)tbz,"corners_to_be_zeroed_local");
    643:     ISView(tbz,NULL);
    644:     ISDestroy(&tbz);
    645:   }

    647:   PetscSFReduceBegin(sfv,MPIU_INT,sfvleaves,sfvroots,MPI_SUM);
    648:   PetscSFReduceEnd(sfv,MPIU_INT,sfvleaves,sfvroots,MPI_SUM);
    649:   PetscSFBcastBegin(sfv,MPIU_INT,sfvroots,sfvleaves);
    650:   PetscSFBcastEnd(sfv,MPIU_INT,sfvroots,sfvleaves);

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

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

    676:   /* Recompute G */
    677:   MatDestroy(&lG);
    678:   MatTranspose(lGt,MAT_INITIAL_MATRIX,&lG);
    679:   if (print) {
    680:     PetscObjectSetName((PetscObject)lG,"used_lG");
    681:     MatView(lG,NULL);
    682:     PetscObjectSetName((PetscObject)lGt,"used_lGt");
    683:     MatView(lGt,NULL);
    684:   }

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

    704:   /* Compute edge connectivity */
    705:   PetscObjectSetOptionsPrefix((PetscObject)lG,"econn_");

    707:   /* Symbolic conn = lG*lGt */
    708:   MatProductCreate(lG,lGt,NULL,&conn);
    709:   MatProductSetType(conn,MATPRODUCT_AB);
    710:   MatProductSetAlgorithm(conn,"default");
    711:   MatProductSetFill(conn,PETSC_DEFAULT);
    712:   PetscObjectSetOptionsPrefix((PetscObject)conn,"econn_");
    713:   MatProductSetFromOptions(conn);
    714:   MatProductSymbolic(conn);

    716:   MatGetRowIJ(conn,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    717:   if (fl2g) {
    718:     PetscBT   btf;
    719:     PetscInt  *iia,*jja,*iiu,*jju;
    720:     PetscBool rest = PETSC_FALSE,free = PETSC_FALSE;

    722:     /* create CSR for all local dofs */
    723:     PetscMalloc1(n+1,&iia);
    724:     if (pcbddc->mat_graph->nvtxs_csr) { /* the user has passed in a CSR graph */
    725:       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);
    726:       iiu = pcbddc->mat_graph->xadj;
    727:       jju = pcbddc->mat_graph->adjncy;
    728:     } else if (pcbddc->use_local_adj) {
    729:       rest = PETSC_TRUE;
    730:       MatGetRowIJ(matis->A,0,PETSC_TRUE,PETSC_FALSE,&i,(const PetscInt**)&iiu,(const PetscInt**)&jju,&done);
    731:     } else {
    732:       free   = PETSC_TRUE;
    733:       PetscMalloc2(n+1,&iiu,n,&jju);
    734:       iiu[0] = 0;
    735:       for (i=0;i<n;i++) {
    736:         iiu[i+1] = i+1;
    737:         jju[i]   = -1;
    738:       }
    739:     }

    741:     /* import sizes of CSR */
    742:     iia[0] = 0;
    743:     for (i=0;i<n;i++) iia[i+1] = iiu[i+1]-iiu[i];

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

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

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

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

    784:   /* Analyze interface for edge dofs */
    785:   PCBDDCAnalyzeInterface(pc);
    786:   pcbddc->mat_graph->twodim = PETSC_FALSE;

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

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

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

    814:   maxsize = 0;
    815:   for (i=0;i<nee;i++) {
    816:     PetscInt size,mark = i+1;

    818:     ISGetLocalSize(eedges[i],&size);
    819:     ISGetIndices(eedges[i],&idxs);
    820:     for (j=0;j<size;j++) marks[idxs[j]] = mark;
    821:     ISRestoreIndices(eedges[i],&idxs);
    822:     maxsize = PetscMax(maxsize,size);
    823:   }

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

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

    873:   /* Reset marked primal dofs */
    874:   ISGetLocalSize(primals,&cum);
    875:   ISGetIndices(primals,&idxs);
    876:   for (i=0;i<cum;i++) marks[idxs[i]] = 0;
    877:   ISRestoreIndices(primals,&idxs);

    879:   /* Now use the initial lG */
    880:   MatDestroy(&lG);
    881:   MatDestroy(&lGt);
    882:   lG   = lGinit;
    883:   MatTranspose(lG,MAT_INITIAL_MATRIX,&lGt);

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

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

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

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

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

    1031:     /* Mark again */
    1032:     PetscArrayzero(marks,ne);
    1033:     for (i=0;i<nee;i++) {
    1034:       PetscInt size,mark = i+1;

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

    1046:     /* Recompute extended cols */
    1047:     eerr = PETSC_FALSE;
    1048:     for (i=0;i<nee;i++) {
    1049:       PetscInt size;

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

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

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

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

    1131:   if (PetscDefined(USE_DEBUG)) {
    1132:     /* Inspects columns of lG (rows of lGt) and make sure the change of basis will
    1133:      not interfere with neighbouring coarse edges */
    1134:     PetscMalloc1(nee+1,&emarks);
    1135:     MatGetRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1136:     for (i=0;i<nv;i++) {
    1137:       PetscInt emax = 0,eemax = 0;

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

    1151:       for (j=ii[i];j<ii[i+1];j++) {
    1152:         if (marks[jj[j]] && marks[jj[j]] != eemax) {
    1153:           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]);
    1154:         }
    1155:       }
    1156:     }
    1157:     PetscFree(emarks);
    1158:     MatRestoreRowIJ(lGt,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&done);
    1159:   }

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

    1171:     if (ii[i+1]==ii[i] || PetscBTLookup(btv,i)) continue;
    1172:     for (j=ii[i];j<ii[i+1];j++)
    1173:       if (marks[jj[j]] && !mark)
    1174:         mark = marks[jj[j]];

    1176:     /* not relevant */
    1177:     if (!mark) continue;

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

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

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

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

    1218:   /* Defaults to identity */
    1219:   MatCreateVecs(pc->pmat,&tvec,NULL);
    1220:   VecSet(tvec,1.0);
    1221:   MatDiagonalSet(T,tvec,INSERT_VALUES);
    1222:   VecDestroy(&tvec);

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

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

    1246:     ISCreateGeneral(comm,2*nee,corners,PETSC_USE_POINTER,&wis);
    1247:     ISLocalToGlobalMappingApplyIS(vl2g,wis,&gwis);
    1248:     ISDestroy(&wis);
    1249:     ISRenumber(gwis,NULL,&cnv,&wis);
    1250:     ISLocalToGlobalMappingCreateIS(wis,&cvl2g);
    1251:     ISDestroy(&wis);
    1252:     ISDestroy(&gwis);

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

    1265: #if defined(PRINT_GDET)
    1266:   inc = 0;
    1267:   lev = pcbddc->current_level;
    1268: #endif

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

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

    1285:       ISGetIndices(eedges[i],&cols);
    1286:       /* H1 */
    1287:       ISGetIndices(extrows[i],&rows);
    1288:       MatGetSize(Gins,&nrh,&nch);
    1289:       MatDenseGetArrayRead(Gins,&data);
    1290:       MatSetValuesLocal(T,nrh,rows,nch,cols,data,INSERT_VALUES);
    1291:       MatDenseRestoreArrayRead(Gins,&data);
    1292:       ISRestoreIndices(extrows[i],&rows);
    1293:       /* complement */
    1294:       MatGetSize(GKins,&nrc,&ncc);
    1295:       if (!ncc) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Constant function has not been generated for coarse edge %D",i);
    1296:       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);
    1297:       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);
    1298:       MatDenseGetArrayRead(GKins,&data);
    1299:       MatSetValuesLocal(T,nrc,cols,ncc,cols+nch,data,INSERT_VALUES);
    1300:       MatDenseRestoreArrayRead(GKins,&data);

    1302:       /* coarse discrete gradient */
    1303:       if (pcbddc->nedcG) {
    1304:         PetscInt cols[2];

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

    1320:   /* Start assembling */
    1321:   MatAssemblyBegin(T,MAT_FINAL_ASSEMBLY);
    1322:   if (pcbddc->nedcG) {
    1323:     MatAssemblyBegin(pcbddc->nedcG,MAT_FINAL_ASSEMBLY);
    1324:   }

    1326:   /* Free */
    1327:   if (fl2g) {
    1328:     ISDestroy(&primals);
    1329:     for (i=0;i<nee;i++) {
    1330:       ISDestroy(&eedges[i]);
    1331:     }
    1332:     PetscFree(eedges);
    1333:   }

    1335:   /* hack mat_graph with primal dofs on the coarse edges */
    1336:   {
    1337:     PCBDDCGraph graph   = pcbddc->mat_graph;
    1338:     PetscInt    *oqueue = graph->queue;
    1339:     PetscInt    *ocptr  = graph->cptr;
    1340:     PetscInt    ncc,*idxs;

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

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

    1382:   ISDestroy(&nedfieldlocal);
    1383:   PetscFree(extrow);
    1384:   PetscFree2(work,rwork);
    1385:   PetscFree(corners);
    1386:   PetscFree(cedges);
    1387:   PetscFree(extrows);
    1388:   PetscFree(extcols);
    1389:   MatDestroy(&lG);

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

    1401:   /* set change of basis */
    1402:   PCBDDCSetChangeOfBasisMat(pc,T,singular);
    1403:   MatDestroy(&T);

    1405:   return(0);
    1406: }

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

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

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

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

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

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

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

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

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

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

    1560: PetscErrorCode PCBDDCAddPrimalVerticesLocalIS(PC pc, IS primalv)
    1561: {
    1562:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;

    1566:   if (primalv) {
    1567:     if (pcbddc->user_primal_vertices_local) {
    1568:       IS list[2], newp;

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

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

    1588:   for (f=0;f<Nf;f++) out[f] = X[*comp];
    1589:   return(0);
    1590: }

    1592: PetscErrorCode PCBDDCComputeLocalTopologyInfo(PC pc)
    1593: {
    1595:   Vec            local,global;
    1596:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    1597:   Mat_IS         *matis = (Mat_IS*)pc->pmat->data;
    1598:   PetscBool      monolithic = PETSC_FALSE;

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

    1616:   if (pcbddc->user_provided_isfordofs) {
    1617:     if (pcbddc->n_ISForDofs) {
    1618:       PetscInt i;

    1620:       PetscMalloc1(pcbddc->n_ISForDofs,&pcbddc->ISForDofsLocal);
    1621:       for (i=0;i<pcbddc->n_ISForDofs;i++) {
    1622:         PetscInt bs;

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

    1637:       MatGetDM(pc->pmat, &dm);
    1638:       if (!dm) {
    1639:         PCGetDM(pc, &dm);
    1640:       }
    1641:       if (dm) {
    1642:         IS      *fields;
    1643:         PetscInt nf,i;

    1645:         DMCreateFieldDecomposition(dm,&nf,NULL,&fields,NULL);
    1646:         PetscMalloc1(nf,&pcbddc->ISForDofsLocal);
    1647:         for (i=0;i<nf;i++) {
    1648:           PetscInt bs;

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

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

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

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

    1719:     MatGetDM(pc->pmat,&dm);
    1720:     if (!dm) {
    1721:       PCGetDM(pc,&dm);
    1722:     }
    1723:     if (dm) {
    1724:       PetscBool isda;

    1726:       PetscObjectTypeCompare((PetscObject)dm,DMDA,&isda);
    1727:       if (isda) {
    1728:         ISLocalToGlobalMapping l2l;
    1729:         IS                     corners;
    1730:         Mat                    lA;
    1731:         PetscBool              gl,lo;

    1733:         {
    1734:           Vec               cvec;
    1735:           const PetscScalar *coords;
    1736:           PetscInt          dof,n,cdim;
    1737:           PetscBool         memc = PETSC_TRUE;

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

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

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

    1790:             PetscMalloc1(dof*n,&idxout);
    1791:             for (i=0;i<n;i++) for (d=0;d<dof;d++) idxout[dof*i+d] = dof*idx[i]+d;
    1792:             ISLocalToGlobalMappingApply(l2l,dof*n,idxout,idxout);

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

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

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

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

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

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

    1899: PetscErrorCode PCBDDCBenignRemoveInterior(PC pc,Vec r,Vec z)
    1900: {
    1901:   PC_IS             *pcis = (PC_IS*)(pc->data);
    1902:   PC_BDDC           *pcbddc = (PC_BDDC*)(pc->data);
    1903:   PetscErrorCode    ierr;

    1906:   if (!pcbddc->benign_have_null) {
    1907:     return(0);
    1908:   }
    1909:   if (pcbddc->ChangeOfBasisMatrix) {
    1910:     Vec swap;

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

    1932: PetscErrorCode PCBDDCBenignMatMult_Private_Private(Mat A, Vec x, Vec y, PetscBool transpose)
    1933: {
    1934:   PCBDDCBenignMatMult_ctx ctx;
    1935:   PetscErrorCode          ierr;
    1936:   PetscBool               apply_right,apply_left,reset_x;

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

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

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

    2020: PetscErrorCode PCBDDCBenignMatMultTranspose_Private(Mat A, Vec x, Vec y)
    2021: {

    2025:   PCBDDCBenignMatMult_Private_Private(A,x,y,PETSC_TRUE);
    2026:   return(0);
    2027: }

    2029: PetscErrorCode PCBDDCBenignMatMult_Private(Mat A, Vec x, Vec y)
    2030: {

    2034:   PCBDDCBenignMatMult_Private_Private(A,x,y,PETSC_FALSE);
    2035:   return(0);
    2036: }

    2038: PetscErrorCode PCBDDCBenignShellMat(PC pc, PetscBool restore)
    2039: {
    2040:   PC_IS                   *pcis = (PC_IS*)pc->data;
    2041:   PC_BDDC                 *pcbddc = (PC_BDDC*)pc->data;
    2042:   PCBDDCBenignMatMult_ctx ctx;
    2043:   PetscErrorCode          ierr;

    2046:   if (!restore) {
    2047:     Mat                A_IB,A_BI;
    2048:     PetscScalar        *work;
    2049:     PCBDDCReuseSolvers reuse = pcbddc->sub_schurs ? pcbddc->sub_schurs->reuse_solver : NULL;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2309:     /* if filter is true, then removes entries lower than PETSC_SMALL in magnitude */
    2310:     if (filter) {
    2311:       PetscScalar *data;
    2312:       PetscInt    j,cum;

    2314:       PetscCalloc2(n+1,&xadj_filtered,xadj[n],&adjncy_filtered);
    2315:       MatSeqAIJGetArray(B,&data);
    2316:       cum = 0;
    2317:       for (i=0;i<n;i++) {
    2318:         PetscInt t;

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

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

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

    2368:       DMPlexGetSubdomainSection(dm,&subSection);
    2369:       MatISGetLocalMat(pc->pmat,&A);
    2370:       PetscMalloc3(A->rmap->n,&ids,graph->ncc+1,&cids,A->rmap->n,&pids);
    2371:       PetscBTCreate(A->rmap->n,&btv);
    2372:       PetscBTCreate(A->rmap->n,&btvt);

    2374:       cids[0] = 0;
    2375:       for (i = 0, cump = 0, cum = 0; i < graph->ncc; i++) {
    2376:         PetscInt j;

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

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

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

    2451: PetscErrorCode PCBDDCBenignCheck(PC pc, IS zerodiag)
    2452: {
    2453:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    2454:   PC_IS*         pcis = (PC_IS*)(pc->data);
    2455:   IS             dirIS = NULL;
    2456:   PetscInt       i;

    2460:   PCBDDCGraphGetDirichletDofs(pcbddc->mat_graph,&dirIS);
    2461:   if (zerodiag) {
    2462:     Mat            A;
    2463:     Vec            vec3_N;
    2464:     PetscScalar    *vals;
    2465:     const PetscInt *idxs;
    2466:     PetscInt       nz,*count;

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

    2489:       ISGetLocalSize(dirIS,&n);
    2490:       ISGetIndices(dirIS,&idxs);
    2491:       for (i=0;i<n;i++) vals[i] = 0.;
    2492:       VecSetValues(pcis->vec2_N,n,idxs,vals,INSERT_VALUES);
    2493:       ISRestoreIndices(dirIS,&idxs);
    2494:     }
    2495:     VecAssemblyBegin(pcis->vec2_N);
    2496:     VecAssemblyEnd(pcis->vec2_N);
    2497:     VecDuplicate(pcis->vec1_N,&vec3_N);
    2498:     VecSet(vec3_N,0.);
    2499:     MatISGetLocalMat(pc->pmat,&A);
    2500:     MatMult(A,pcis->vec1_N,vec3_N);
    2501:     VecDot(vec3_N,pcis->vec2_N,&vals[0]);
    2502:     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]));
    2503:     PetscFree(vals);
    2504:     VecDestroy(&vec3_N);

    2506:     /* there should not be any pressure dofs lying on the interface */
    2507:     PetscCalloc1(pcis->n,&count);
    2508:     ISGetIndices(pcis->is_B_local,&idxs);
    2509:     for (i=0;i<pcis->n_B;i++) count[idxs[i]]++;
    2510:     ISRestoreIndices(pcis->is_B_local,&idxs);
    2511:     ISGetIndices(zerodiag,&idxs);
    2512:     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]);
    2513:     ISRestoreIndices(zerodiag,&idxs);
    2514:     PetscFree(count);
    2515:   }
    2516:   ISDestroy(&dirIS);

    2518:   /* check PCBDDCBenignGetOrSetP0 */
    2519:   VecSetRandom(pcis->vec1_global,NULL);
    2520:   for (i=0;i<pcbddc->benign_n;i++) pcbddc->benign_p0[i] = -PetscGlobalRank-i;
    2521:   PCBDDCBenignGetOrSetP0(pc,pcis->vec1_global,PETSC_FALSE);
    2522:   for (i=0;i<pcbddc->benign_n;i++) pcbddc->benign_p0[i] = 1;
    2523:   PCBDDCBenignGetOrSetP0(pc,pcis->vec1_global,PETSC_TRUE);
    2524:   for (i=0;i<pcbddc->benign_n;i++) {
    2525:     PetscInt val = PetscRealPart(pcbddc->benign_p0[i]);
    2526:     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);
    2527:   }
    2528:   return(0);
    2529: }

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

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

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

    2571:     bsp = 0;
    2572:     for (p=0;p<n;p++) {
    2573:       PetscInt bs;

    2575:       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]);
    2576:       ISGetBlockSize(pcbddc->ISForDofsLocal[pp[p]],&bs);
    2577:       bsp += bs;
    2578:     }
    2579:     PetscMalloc1(bsp,&bzerodiag);
    2580:     bsp  = 0;
    2581:     for (p=0;p<n;p++) {
    2582:       const PetscInt *idxs;
    2583:       PetscInt       b,bs,npl,*bidxs;

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

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

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

    2606:       ISDifference(pressures,iP,&newpressures);
    2607:       ISDestroy(&pressures);
    2608:       pressures = newpressures;
    2609:     }
    2610:     ISSorted(pressures,&sorted);
    2611:     if (!sorted) {
    2612:       ISSort(pressures);
    2613:     }
    2614:     PetscFree(pp);
    2615:   }

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

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

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

    2671:     subs  = pcbddc->local_subs;
    2672:     nsubs = pcbddc->n_local_subs;
    2673:     /* 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) */
    2674:     if (checkb) {
    2675:       VecDuplicateVecs(matis->y,2,&work);
    2676:       ISGetLocalSize(zerodiag,&nl);
    2677:       ISGetIndices(zerodiag,&idxs);
    2678:       /* work[0] = 1_p */
    2679:       VecSet(work[0],0.);
    2680:       VecGetArray(work[0],&array);
    2681:       for (j=0;j<nl;j++) array[idxs[j]] = 1.;
    2682:       VecRestoreArray(work[0],&array);
    2683:       /* work[0] = 1_v */
    2684:       VecSet(work[1],1.);
    2685:       VecGetArray(work[1],&array);
    2686:       for (j=0;j<nl;j++) array[idxs[j]] = 0.;
    2687:       VecRestoreArray(work[1],&array);
    2688:       ISRestoreIndices(zerodiag,&idxs);
    2689:     }

    2691:     if (nsubs > 1 || bsp > 1) {
    2692:       IS       *is;
    2693:       PetscInt b,totb;

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

    2705:           if (subs) {
    2706:             ISLocalToGlobalMappingCreateIS(subs[i],&l2g);
    2707:           } else {
    2708:             IS tis;

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

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

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

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

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

    2802:   if (!benign_n) {
    2803:     PetscInt n;

    2805:     ISDestroy(&zerodiag);
    2806:     recompute_zerodiag = PETSC_FALSE;
    2807:     MatGetLocalSize(pcbddc->local_mat,&n,NULL);
    2808:     if (n) have_null = PETSC_FALSE;
    2809:   }

    2811:   /* final check for null pressures */
    2812:   if (zerodiag && pressures) {
    2813:     ISEqual(pressures,zerodiag,&have_null);
    2814:   }

    2816:   if (recompute_zerodiag) {
    2817:     ISDestroy(&zerodiag);
    2818:     if (benign_n == 1) {
    2819:       PetscObjectReference((PetscObject)zerodiag_subs[0]);
    2820:       zerodiag = zerodiag_subs[0];
    2821:     } else {
    2822:       PetscInt i,nzn,*new_idxs;

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

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

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

    2856:     if (pressures) {
    2857:       isused = pressures;
    2858:     } else {
    2859:       isused = zerodiag_save;
    2860:     }
    2861:     MatGetLocalToGlobalMapping(pc->pmat,&l2gmap,NULL);
    2862:     MatISGetLocalMat(pc->pmat,&A);
    2863:     MatGetLocalSize(A,&n,NULL);
    2864:     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");
    2865:     n_isused = 0;
    2866:     if (isused) {
    2867:       ISGetLocalSize(isused,&n_isused);
    2868:     }
    2869:     MPI_Scan(&n_isused,&st,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)pc));
    2870:     st = st-n_isused;
    2871:     if (n) {
    2872:       const PetscInt *gidxs;

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

    2907:     for (i=0;i<bsp;i++) {
    2908:       ISDestroy(&bzerodiag[i]);
    2909:     }
    2910:     PetscFree(bzerodiag);
    2911:   }
    2912:   pcbddc->benign_n = benign_n;
    2913:   pcbddc->benign_zerodiag_subs = zerodiag_subs;

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

    2919: project_b0:
    2920:   MatGetLocalSize(pcbddc->local_mat,&n,NULL);
    2921:   /* change of basis and p0 dofs */
    2922:   if (pcbddc->benign_n) {
    2923:     PetscInt i,s,*nnz;

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

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

    2957:       ISGetLocalSize(pcbddc->benign_zerodiag_subs[s],&nzs);
    2958:       ISGetIndices(pcbddc->benign_zerodiag_subs[s],&idxs);
    2959:       for (i=0;i<nzs-1;i++) {
    2960:         PetscScalar vals[2];
    2961:         PetscInt    cols[2];

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

    2981:     /* project if needed */
    2982:     if (pcbddc->benign_change_explicit) {
    2983:       Mat M;

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

    2997: PetscErrorCode PCBDDCBenignGetOrSetP0(PC pc, Vec v, PetscBool get)
    2998: {
    2999:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    3000:   PetscScalar    *array;

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

    3022: PetscErrorCode PCBDDCBenignPopOrPushB0(PC pc, PetscBool pop)
    3023: {
    3024:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;

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

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

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

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

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

    3109:       for (i=0;i<pcbddc->benign_n;i++) {
    3110:         PetscScalar *B0_vals;
    3111:         PetscInt    *B0_cols,B0_ncol;

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

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

    3144:   if (!sub_schurs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Adaptive selection of constraints requires SubSchurs data");
    3145:   if (!sub_schurs->schur_explicit) SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_SUP,"Adaptive selection of constraints requires MUMPS and/or MKL_CPARDISO");
    3146:   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);
    3147:   PetscLogEventBegin(PC_BDDC_AdaptiveSetUp[pcbddc->current_level],pc,0,0,0);

    3149:   if (pcbddc->dbg_flag) {
    3150:     PetscViewerFlush(pcbddc->dbg_viewer);
    3151:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    3152:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Check adaptive selection of constraints\n");
    3153:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    3154:   }

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

    3160:   /* max size of subsets */
    3161:   mss = 0;
    3162:   for (i=0;i<sub_schurs->n_subs;i++) {
    3163:     PetscInt subset_size;

    3165:     ISGetLocalSize(sub_schurs->is_subs[i],&subset_size);
    3166:     mss = PetscMax(mss,subset_size);
    3167:   }

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

    3178:   /* allocate lapack workspace */
    3179:   cum = cum2 = 0;
    3180:   maxneigs = 0;
    3181:   for (i=0;i<sub_schurs->n_subs;i++) {
    3182:     PetscInt n,subset_size;

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

    3199:       B_lwork = -1;
    3200:       /* some implementations may complain about NULL pointers, even if we are querying */
    3201:       S = &sdummy;
    3202:       St = &sdummy;
    3203:       eigs = &rdummy;
    3204:       eigv = &sdummy;
    3205:       B_iwork = &idummy;
    3206:       B_ifail = &idummy;
    3207: #if defined(PETSC_USE_COMPLEX)
    3208:       rwork = &rdummy;
    3209: #endif
    3210:       thresh = 1.0;
    3211:       PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    3212: #if defined(PETSC_USE_COMPLEX)
    3213:       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));
    3214: #else
    3215:       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));
    3216: #endif
    3217:       if (B_ierr != 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in query to SYGVX Lapack routine %d",(int)B_ierr);
    3218:       PetscFPTrapPop();
    3219:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet implemented");
    3220:   }

    3222:   nv = 0;
    3223:   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) */
    3224:     ISGetLocalSize(sub_schurs->is_vertices,&nv);
    3225:   }
    3226:   PetscBLASIntCast((PetscInt)PetscRealPart(lwork),&B_lwork);
    3227:   if (allocated_S_St) {
    3228:     PetscMalloc2(mss*mss,&S,mss*mss,&St);
    3229:   }
    3230:   PetscMalloc5(mss*mss,&eigv,mss,&eigs,B_lwork,&work,5*mss,&B_iwork,mss,&B_ifail);
    3231: #if defined(PETSC_USE_COMPLEX)
    3232:   PetscMalloc1(7*mss,&rwork);
    3233: #endif
    3234:   PetscMalloc5(nv+sub_schurs->n_subs,&pcbddc->adaptive_constraints_n,
    3235:                       nv+sub_schurs->n_subs+1,&pcbddc->adaptive_constraints_idxs_ptr,
    3236:                       nv+sub_schurs->n_subs+1,&pcbddc->adaptive_constraints_data_ptr,
    3237:                       nv+cum,&pcbddc->adaptive_constraints_idxs,
    3238:                       nv+cum2,&pcbddc->adaptive_constraints_data);
    3239:   PetscArrayzero(pcbddc->adaptive_constraints_n,nv+sub_schurs->n_subs);

    3241:   maxneigs = 0;
    3242:   cum = cumarray = 0;
    3243:   pcbddc->adaptive_constraints_idxs_ptr[0] = 0;
    3244:   pcbddc->adaptive_constraints_data_ptr[0] = 0;
    3245:   if (sub_schurs->is_vertices && pcbddc->use_vertices) {
    3246:     const PetscInt *idxs;

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

    3259:   if (mss) { /* multilevel */
    3260:     MatSeqAIJGetArray(sub_schurs->sum_S_Ej_inv_all,&Sarray);
    3261:     MatSeqAIJGetArray(sub_schurs->sum_S_Ej_tilda_all,&Starray);
    3262:   }

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

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

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

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

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

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

    3352:         B_neigs = 0;
    3353:         compute_range = (PetscBool)!same_data;
    3354:         if (nmin >= subset_size) compute_range = PETSC_FALSE;

    3356:         if (pcbddc->dbg_flag) {
    3357:           PetscInt nc = 0;

    3359:           if (sub_schurs->change_primal_sub) {
    3360:             ISGetLocalSize(sub_schurs->change_primal_sub[i],&nc);
    3361:           }
    3362:           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);
    3363:         }

    3365:         PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    3366:         if (compute_range) {

    3368:           /* ask for eigenvalues larger than thresh */
    3369:           if (sub_schurs->is_posdef) {
    3370: #if defined(PETSC_USE_COMPLEX)
    3371:             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));
    3372: #else
    3373:             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));
    3374: #endif
    3375:             PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3376:           } else { /* no theory so far, but it works nicely */
    3377:             PetscInt  recipe = 0,recipe_m = 1;
    3378:             PetscReal bb[2];

    3380:             PetscOptionsGetInt(NULL,((PetscObject)pc)->prefix,"-pc_bddc_adaptive_recipe",&recipe,NULL);
    3381:             switch (recipe) {
    3382:             case 0:
    3383:               if (scal) { bb[0] = PETSC_MIN_REAL; bb[1] = lthresh; }
    3384:               else { bb[0] = uthresh; bb[1] = PETSC_MAX_REAL; }
    3385: #if defined(PETSC_USE_COMPLEX)
    3386:               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));
    3387: #else
    3388:               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));
    3389: #endif
    3390:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3391:               break;
    3392:             case 1:
    3393:               bb[0] = PETSC_MIN_REAL; bb[1] = lthresh*lthresh;
    3394: #if defined(PETSC_USE_COMPLEX)
    3395:               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));
    3396: #else
    3397:               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));
    3398: #endif
    3399:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3400:               if (!scal) {
    3401:                 PetscBLASInt B_neigs2 = 0;

    3403:                 bb[0] = PetscMax(lthresh*lthresh,uthresh); bb[1] = PETSC_MAX_REAL;
    3404:                 PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3405:                 PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3406: #if defined(PETSC_USE_COMPLEX)
    3407:                 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));
    3408: #else
    3409:                 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));
    3410: #endif
    3411:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3412:                 B_neigs += B_neigs2;
    3413:               }
    3414:               break;
    3415:             case 2:
    3416:               if (scal) {
    3417:                 bb[0] = PETSC_MIN_REAL;
    3418:                 bb[1] = 0;
    3419: #if defined(PETSC_USE_COMPLEX)
    3420:                 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));
    3421: #else
    3422:                 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));
    3423: #endif
    3424:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3425:               } else {
    3426:                 PetscBLASInt B_neigs2 = 0;
    3427:                 PetscBool    import = PETSC_FALSE;

    3429:                 lthresh = PetscMax(lthresh,0.0);
    3430:                 if (lthresh > 0.0) {
    3431:                   bb[0] = PETSC_MIN_REAL;
    3432:                   bb[1] = lthresh*lthresh;

    3434:                   import = PETSC_TRUE;
    3435: #if defined(PETSC_USE_COMPLEX)
    3436:                   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));
    3437: #else
    3438:                   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));
    3439: #endif
    3440:                   PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3441:                 }
    3442:                 bb[0] = PetscMax(lthresh*lthresh,uthresh);
    3443:                 bb[1] = PETSC_MAX_REAL;
    3444:                 if (import) {
    3445:                   PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3446:                   PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3447:                 }
    3448: #if defined(PETSC_USE_COMPLEX)
    3449:                 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));
    3450: #else
    3451:                 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));
    3452: #endif
    3453:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3454:                 B_neigs += B_neigs2;
    3455:               }
    3456:               break;
    3457:             case 3:
    3458:               if (scal) {
    3459:                 PetscOptionsGetInt(NULL,((PetscObject)pc)->prefix,"-pc_bddc_adaptive_recipe3_min_scal",&recipe_m,NULL);
    3460:               } else {
    3461:                 PetscOptionsGetInt(NULL,((PetscObject)pc)->prefix,"-pc_bddc_adaptive_recipe3_min",&recipe_m,NULL);
    3462:               }
    3463:               if (!scal) {
    3464:                 bb[0] = uthresh;
    3465:                 bb[1] = PETSC_MAX_REAL;
    3466: #if defined(PETSC_USE_COMPLEX)
    3467:                 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));
    3468: #else
    3469:                 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));
    3470: #endif
    3471:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3472:               }
    3473:               if (recipe_m > 0 && B_N - B_neigs > 0) {
    3474:                 PetscBLASInt B_neigs2 = 0;

    3476:                 B_IL = 1;
    3477:                 PetscBLASIntCast(PetscMin(recipe_m,B_N - B_neigs),&B_IU);
    3478:                 PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3479:                 PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3480: #if defined(PETSC_USE_COMPLEX)
    3481:                 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));
    3482: #else
    3483:                 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));
    3484: #endif
    3485:                 PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3486:                 B_neigs += B_neigs2;
    3487:               }
    3488:               break;
    3489:             case 4:
    3490:               bb[0] = PETSC_MIN_REAL; bb[1] = lthresh;
    3491: #if defined(PETSC_USE_COMPLEX)
    3492:               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));
    3493: #else
    3494:               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));
    3495: #endif
    3496:               PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3497:               {
    3498:                 PetscBLASInt B_neigs2 = 0;

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

    3564:         if (B_neigs > nmax) {
    3565:           if (pcbddc->dbg_flag) {
    3566:             PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   found %d eigs, more than maximum required %D.\n",B_neigs,nmax);
    3567:           }
    3568:           if (pcbddc->use_deluxe_scaling) eigs_start = scal ? 0 : B_neigs-nmax;
    3569:           B_neigs = nmax;
    3570:         }

    3572:         nmin_s = PetscMin(nmin,B_N);
    3573:         if (B_neigs < nmin_s) {
    3574:           PetscBLASInt B_neigs2 = 0;

    3576:           if (pcbddc->use_deluxe_scaling) {
    3577:             if (scal) {
    3578:               B_IU = nmin_s;
    3579:               B_IL = B_neigs + 1;
    3580:             } else {
    3581:               B_IL = B_N - nmin_s + 1;
    3582:               B_IU = B_N - B_neigs;
    3583:             }
    3584:           } else {
    3585:             B_IL = B_neigs + 1;
    3586:             B_IU = nmin_s;
    3587:           }
    3588:           if (pcbddc->dbg_flag) {
    3589:             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);
    3590:           }
    3591:           if (sub_schurs->is_symmetric) {
    3592:             PetscInt j,k;
    3593:             for (j=0;j<subset_size;j++) {
    3594:               for (k=j;k<subset_size;k++) {
    3595:                 S [j*subset_size+k] = Sarray [cumarray+j*subset_size+k];
    3596:                 St[j*subset_size+k] = Starray[cumarray+j*subset_size+k];
    3597:               }
    3598:             }
    3599:           } else {
    3600:             PetscArraycpy(S,Sarray+cumarray,subset_size*subset_size);
    3601:             PetscArraycpy(St,Starray+cumarray,subset_size*subset_size);
    3602:           }
    3603:           PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    3604: #if defined(PETSC_USE_COMPLEX)
    3605:           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));
    3606: #else
    3607:           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));
    3608: #endif
    3609:           PetscLogFlops((4.0*subset_size*subset_size*subset_size)/3.0);
    3610:           PetscFPTrapPop();
    3611:           B_neigs += B_neigs2;
    3612:         }
    3613:         if (B_ierr) {
    3614:           if (B_ierr < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in SYGVX Lapack routine: illegal value for argument %d",-(int)B_ierr);
    3615:           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);
    3616:           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);
    3617:         }
    3618:         if (pcbddc->dbg_flag) {
    3619:           PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"   -> Got %d eigs\n",B_neigs);
    3620:           for (j=0;j<B_neigs;j++) {
    3621:             if (eigs[j] == 0.0) {
    3622:               PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"     Inf\n");
    3623:             } else {
    3624:               if (pcbddc->use_deluxe_scaling) {
    3625:                 PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"     %1.6e\n",eigs[j+eigs_start]);
    3626:               } else {
    3627:                 PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"     %1.6e\n",1./eigs[j+eigs_start]);
    3628:               }
    3629:             }
    3630:           }
    3631:         }
    3632:       } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet implemented");
    3633:     }
    3634:     /* change the basis back to the original one */
    3635:     if (sub_schurs->change) {
    3636:       Mat change,phi,phit;

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

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

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

    3716: PetscErrorCode PCBDDCSetUpSolvers(PC pc)
    3717: {
    3718:   PetscScalar    *coarse_submat_vals;

    3722:   /* Setup local scatters R_to_B and (optionally) R_to_D */
    3723:   /* PCBDDCSetUpLocalWorkVectors should be called first! */
    3724:   PCBDDCSetUpLocalScatters(pc);

    3726:   /* Setup local neumann solver ksp_R */
    3727:   /* PCBDDCSetUpLocalScatters should be called first! */
    3728:   PCBDDCSetUpLocalSolvers(pc,PETSC_FALSE,PETSC_TRUE);

    3730:   /*
    3731:      Setup local correction and local part of coarse basis.
    3732:      Gives back the dense local part of the coarse matrix in column major ordering
    3733:   */
    3734:   PCBDDCSetUpCorrection(pc,&coarse_submat_vals);

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

    3739:   /* free */
    3740:   PetscFree(coarse_submat_vals);
    3741:   return(0);
    3742: }

    3744: PetscErrorCode PCBDDCResetCustomization(PC pc)
    3745: {
    3746:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;

    3750:   ISDestroy(&pcbddc->user_primal_vertices);
    3751:   ISDestroy(&pcbddc->user_primal_vertices_local);
    3752:   ISDestroy(&pcbddc->NeumannBoundaries);
    3753:   ISDestroy(&pcbddc->NeumannBoundariesLocal);
    3754:   ISDestroy(&pcbddc->DirichletBoundaries);
    3755:   MatNullSpaceDestroy(&pcbddc->onearnullspace);
    3756:   PetscFree(pcbddc->onearnullvecs_state);
    3757:   ISDestroy(&pcbddc->DirichletBoundariesLocal);
    3758:   PCBDDCSetDofsSplitting(pc,0,NULL);
    3759:   PCBDDCSetDofsSplittingLocal(pc,0,NULL);
    3760:   return(0);
    3761: }

    3763: PetscErrorCode PCBDDCResetTopography(PC pc)
    3764: {
    3765:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    3766:   PetscInt       i;

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

    3793: PetscErrorCode PCBDDCResetSolvers(PC pc)
    3794: {
    3795:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;

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

    3843: PetscErrorCode PCBDDCSetUpLocalWorkVectors(PC pc)
    3844: {
    3845:   PC_BDDC        *pcbddc = (PC_BDDC*)pc->data;
    3846:   PC_IS          *pcis = (PC_IS*)pc->data;
    3847:   VecType        impVecType;
    3848:   PetscInt       n_constraints,n_R,old_size;

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

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

    3920:   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");
    3921:   PetscLogEventBegin(PC_BDDC_CorrectionSetUp[pcbddc->current_level],pc,0,0,0);

    3923:   /* Set Non-overlapping dimensions */
    3924:   n_vertices = pcbddc->n_vertices;
    3925:   n_constraints = pcbddc->local_primal_size - pcbddc->benign_n - n_vertices;
    3926:   n_B = pcis->n_B;
    3927:   n_D = pcis->n - n_B;
    3928:   n_R = pcis->n - n_vertices;

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

    3935:   /* Subdomain contribution (Non-overlapping) to coarse matrix  */
    3936:   PetscCalloc1(pcbddc->local_primal_size*pcbddc->local_primal_size,&coarse_submat_vals);
    3937:   MatCreateSeqDense(PETSC_COMM_SELF,n_vertices,n_vertices,coarse_submat_vals,&S_VV);
    3938:   MatDenseSetLDA(S_VV,pcbddc->local_primal_size);
    3939:   MatCreateSeqDense(PETSC_COMM_SELF,n_constraints,n_vertices,coarse_submat_vals+n_vertices,&S_CV);
    3940:   MatDenseSetLDA(S_CV,pcbddc->local_primal_size);
    3941:   MatCreateSeqDense(PETSC_COMM_SELF,n_vertices,n_constraints,coarse_submat_vals+pcbddc->local_primal_size*n_vertices,&S_VC);
    3942:   MatDenseSetLDA(S_VC,pcbddc->local_primal_size);
    3943:   MatCreateSeqDense(PETSC_COMM_SELF,n_constraints,n_constraints,coarse_submat_vals+(pcbddc->local_primal_size+1)*n_vertices,&S_CC);
    3944:   MatDenseSetLDA(S_CC,pcbddc->local_primal_size);

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

    3959:     F = reuse_solver->F;
    3960:     MatGetFactorType(F,&type);
    3961:     if (type == MAT_FACTOR_CHOLESKY) isCHOL = PETSC_TRUE;
    3962:     if (type == MAT_FACTOR_LU) isLU = PETSC_TRUE;
    3963:     MatGetSize(F,&lda_rhs,NULL);
    3964:     need_benign_correction = (PetscBool)(!!reuse_solver->benign_n);
    3965:   } else F = NULL;

    3967:   /* determine if we can use a sparse right-hand side */
    3968:   sparserhs = PETSC_FALSE;
    3969:   if (F) {
    3970:     MatSolverType solver;

    3972:     MatFactorGetSolverType(F,&solver);
    3973:     PetscStrcmp(solver,MATSOLVERMUMPS,&sparserhs);
    3974:   }

    3976:   /* allocate workspace */
    3977:   n = 0;
    3978:   if (n_constraints) {
    3979:     n += lda_rhs*n_constraints;
    3980:   }
    3981:   if (n_vertices) {
    3982:     n = PetscMax(2*lda_rhs*n_vertices,n);
    3983:     n = PetscMax((lda_rhs+n_B)*n_vertices,n);
    3984:   }
    3985:   if (!pcbddc->symmetric_primal) {
    3986:     n = PetscMax(2*lda_rhs*pcbddc->local_primal_size,n);
    3987:   }
    3988:   PetscMalloc1(n,&work);

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

    3998:   MatDestroy(&pcbddc->local_auxmat1);
    3999:   MatDestroy(&pcbddc->local_auxmat2);

    4001:   /* Precompute stuffs needed for preprocessing and application of BDDC*/
    4002:   if (n_constraints) {
    4003:     Mat         M3,C_B;
    4004:     IS          is_aux;
    4005:     PetscScalar *array,*array2;

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

    4012:     /* Assemble         local_auxmat2_R =        (- A_{RR}^{-1} C^T_{CR}) needed by BDDC setup */
    4013:     /* Assemble pcbddc->local_auxmat2   = R_to_B (- A_{RR}^{-1} C^T_{CR}) needed by BDDC application */
    4014:     if (!sparserhs) {
    4015:       PetscArrayzero(work,lda_rhs*n_constraints);
    4016:       for (i=0;i<n_constraints;i++) {
    4017:         const PetscScalar *row_cmat_values;
    4018:         const PetscInt    *row_cmat_indices;
    4019:         PetscInt          size_of_constraint,j;

    4021:         MatGetRow(C_CR,i,&size_of_constraint,&row_cmat_indices,&row_cmat_values);
    4022:         for (j=0;j<size_of_constraint;j++) {
    4023:           work[row_cmat_indices[j]+i*lda_rhs] = -row_cmat_values[j];
    4024:         }
    4025:         MatRestoreRow(C_CR,i,&size_of_constraint,&row_cmat_indices,&row_cmat_values);
    4026:       }
    4027:       MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_constraints,work,&Brhs);
    4028:     } else {
    4029:       Mat tC_CR;

    4031:       MatScale(C_CR,-1.0);
    4032:       if (lda_rhs != n_R) {
    4033:         PetscScalar *aa;
    4034:         PetscInt    r,*ii,*jj;
    4035:         PetscBool   done;

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

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

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

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

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

    4141:   /* Get submatrices from subdomain matrix */
    4142:   if (n_vertices) {
    4143: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
    4144:     PetscBool oldpin;
    4145: #endif
    4146:     PetscBool isaij;
    4147:     IS        is_aux;

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

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

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

    4186:       MatDenseGetArray(pcbddc->coarse_phi_B,&marray);
    4187:       PetscFree(marray);
    4188:       MatDestroy(&pcbddc->coarse_phi_B);
    4189:       MatDestroy(&pcbddc->coarse_psi_B);
    4190:       MatDestroy(&pcbddc->coarse_phi_D);
    4191:       MatDestroy(&pcbddc->coarse_psi_D);
    4192:     }
    4193:   }

    4195:   if (!pcbddc->coarse_phi_B) {
    4196:     PetscScalar *marr;

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

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

    4230:     ISGetIndices(pcis->is_I_local,&idxs);
    4231:     PetscMalloc1(pcbddc->benign_n,&p0_lidx_I);
    4232:     for (i=0;i<pcbddc->benign_n;i++) {
    4233:       PetscFindInt(pcbddc->benign_p0_lidx[i],pcis->n-pcis->n_B,idxs,&p0_lidx_I[i]);
    4234:     }
    4235:     ISRestoreIndices(pcis->is_I_local,&idxs);
    4236:   }

    4238:   /* vertices */
    4239:   if (n_vertices) {
    4240:     PetscBool restoreavr = PETSC_FALSE;

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

    4244:     if (n_R) {
    4245:       Mat               A_RRmA_RV,A_RV_bcorr=NULL,S_VVt; /* S_VVt with LDA=N */
    4246:       PetscBLASInt      B_N,B_one = 1;
    4247:       const PetscScalar *x;
    4248:       PetscScalar       *y;

    4250:       MatScale(A_RV,m_one);
    4251:       if (need_benign_correction) {
    4252:         ISLocalToGlobalMapping RtoN;
    4253:         IS                     is_p0;
    4254:         PetscInt               *idxs_p0,n;

    4256:         PetscMalloc1(pcbddc->benign_n,&idxs_p0);
    4257:         ISLocalToGlobalMappingCreateIS(pcbddc->is_R_local,&RtoN);
    4258:         ISGlobalToLocalMappingApply(RtoN,IS_GTOLM_DROP,pcbddc->benign_n,pcbddc->benign_p0_lidx,&n,idxs_p0);
    4259:         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);
    4260:         ISLocalToGlobalMappingDestroy(&RtoN);
    4261:         ISCreateGeneral(PETSC_COMM_SELF,n,idxs_p0,PETSC_OWN_POINTER,&is_p0);
    4262:         MatCreateSubMatrix(A_RV,is_p0,NULL,MAT_INITIAL_MATRIX,&A_RV_bcorr);
    4263:         ISDestroy(&is_p0);
    4264:       }

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

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

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

    4296:                  | 0 0  0 | (V)
    4297:              L = | 0 0 -1 | (P-p0)
    4298:                  | 0 0 -1 | (p0)

    4300:           */
    4301:           for (i=0;i<reuse_solver->benign_n;i++) {
    4302:             const PetscScalar *vals;
    4303:             const PetscInt    *idxs,*idxs_zero;
    4304:             PetscInt          n,j,nz;

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

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

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

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

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

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

    4435:         MatDestroy(&B);
    4436:         MatCreateSeqDense(PETSC_COMM_SELF,lda_rhs,n_vertices,work+lda_rhs*n_vertices,&B);
    4437:         /* Reuse B = local_auxmat2_R * S_CV */
    4438:         MatProductCreateWithMat(local_auxmat2_R,S_CV,NULL,B);
    4439:         MatProductSetType(B,MATPRODUCT_AB);
    4440:         MatProductSetFromOptions(B);
    4441:         MatProductSymbolic(B);
    4442:         MatProductNumeric(B);

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

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

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

    4503:     /* coarse basis functions */
    4504:     for (i=0;i<n_vertices;i++) {
    4505:       PetscScalar *y;

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

    4516:       if (pcbddc->switch_static || pcbddc->dbg_flag) {
    4517:         PetscInt j;

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

    4534:   if (n_constraints) {
    4535:     Mat B;

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

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

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

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

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

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

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

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

    4623:     if (n_constraints) {
    4624:       Mat S_CCT,C_CRT;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    5269:   /* print some info if requested */
    5270:   if (pcbddc->dbg_flag) {
    5271:     PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    5272:     PetscViewerFlush(pcbddc->dbg_viewer);
    5273:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    5274:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d local dimensions\n",PetscGlobalRank);
    5275:     PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"local_size = %D, dirichlet_size = %D, boundary_size = %D\n",pcis->n,n_D,n_B);
    5276:     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);
    5277:     PetscViewerFlush(pcbddc->dbg_viewer);
    5278:   }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    5547:       KSPSetPC(pcbddc->ksp_D,reuse_solver->interior_solver);
    5548:     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    5882:     if (pcbddc->benign_have_null) {
    5883:       PC        coarse_pc;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    6524:   /* map constraints_idxs in boundary numbering */
    6525:   ISGlobalToLocalMappingApply(pcis->BtoNmap,IS_GTOLM_DROP,constraints_idxs_ptr[total_counts_cc],constraints_idxs,&i,constraints_idxs_B);
    6526:   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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    6843:           /* check change of basis */
    6844:           if (pcbddc->dbg_flag) {
    6845:             PetscInt   ii,jj;
    6846:             PetscBool valid_qr=PETSC_TRUE;
    6847:             PetscBLASIntCast(primal_dofs,&Blas_M);
    6848:             PetscBLASIntCast(size_of_constraint,&Blas_N);
    6849:             PetscBLASIntCast(size_of_constraint,&Blas_K);
    6850:             PetscBLASIntCast(size_of_constraint,&Blas_LDA);
    6851:             PetscBLASIntCast(size_of_constraint,&Blas_LDB);
    6852:             PetscBLASIntCast(primal_dofs,&Blas_LDC);
    6853:             PetscFPTrapPush(PETSC_FP_TRAP_OFF);
    6854:             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));
    6855:             PetscFPTrapPop();
    6856:             for (jj=0;jj<size_of_constraint;jj++) {
    6857:               for (ii=0;ii<primal_dofs;ii++) {
    6858:                 if (ii != jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]) > 1.e-12) valid_qr = PETSC_FALSE;
    6859:                 if (ii == jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]-(PetscReal)1) > 1.e-12) valid_qr = PETSC_FALSE;
    6860:               }
    6861:             }
    6862:             if (!valid_qr) {
    6863:               PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\t-> wrong change of basis!\n");
    6864:               for (jj=0;jj<size_of_constraint;jj++) {
    6865:                 for (ii=0;ii<primal_dofs;ii++) {
    6866:                   if (ii != jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]) > 1.e-12) {
    6867:                     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]));
    6868:                   }
    6869:                   if (ii == jj && PetscAbsScalar(dbg_work[size_of_constraint*primal_dofs+jj*primal_dofs+ii]-(PetscReal)1) > 1.e-12) {
    6870:                     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]));
    6871:                   }
    6872:                 }
    6873:               }
    6874:             } else {
    6875:               PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"\t-> right change of basis!\n");
    6876:             }
    6877:           }
    6878:         } else { /* simple transformation block */
    6879:           PetscInt    row,col;
    6880:           PetscScalar val,norm;

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

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

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

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

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

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

    6982:         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");
    6983:         if (sub_schurs && sub_schurs->S_Ej_all) {
    6984:           Mat                    S_new,tmat;
    6985:           IS                     is_all_N,is_V_Sall = NULL;

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

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

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

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

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

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

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

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

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

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

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

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

    7177:     if (pcbddc->user_primal_vertices_local && !pcbddc->user_primal_vertices) {
    7178:       PCBDDCConsistencyCheckIS(pc,MPI_LOR,&pcbddc->user_primal_vertices_local);
    7179:     }
    7180:     /* Check validity of the csr graph passed in by the user */
    7181:     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);

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

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

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

    7206:       /* TODO: support for blocked */
    7207:       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);
    7208:       MatGetLocalSize(matis->A,&n,NULL);
    7209:       PetscMalloc1(pcbddc->mat_graph->cdim*n,&lcoords);
    7210:       MPI_Type_contiguous(pcbddc->mat_graph->cdim,MPIU_REAL,&dimrealtype);
    7211:       MPI_Type_commit(&dimrealtype);
    7212:       PetscSFBcastBegin(matis->sf,dimrealtype,pcbddc->mat_graph->coords,lcoords);
    7213:       PetscSFBcastEnd(matis->sf,dimrealtype,pcbddc->mat_graph->coords,lcoords);
    7214:       MPI_Type_free(&dimrealtype);
    7215:       PetscFree(pcbddc->mat_graph->coords);

    7217:       pcbddc->mat_graph->coords = lcoords;
    7218:       pcbddc->mat_graph->cloc   = PETSC_TRUE;
    7219:       pcbddc->mat_graph->cnloc  = n;
    7220:     }
    7221:     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);
    7222:     pcbddc->mat_graph->active_coords = (PetscBool)(pcbddc->corner_selection && !pcbddc->corner_selected);

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

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

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

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

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

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

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

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

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

    7324:   PetscObjectTypeCompare((PetscObject)mat,MATIS,&ismatis);
    7325:   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);
    7328:   if (*n_subdomains <=0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Invalid number of subdomains requested %D",*n_subdomains);

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

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

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

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

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

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

    7411:   PetscMalloc1(1,&ranks_send_to_idx);

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

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

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

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

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

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

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

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

    7568:   /* assemble parallel IS for sends */
    7569:   i = 1;
    7570:   if (!color) i=0;
    7571:   ISCreateGeneral(PetscObjectComm((PetscObject)mat),i,ranks_send_to_idx,PETSC_OWN_POINTER,is_sends);
    7572:   return(0);
    7573: }

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

    7577: 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[])
    7578: {
    7579:   Mat                    local_mat;
    7580:   IS                     is_sends_internal;
    7581:   PetscInt               rows,cols,new_local_rows;
    7582:   PetscInt               i,bs,buf_size_idxs,buf_size_idxs_is,buf_size_vals,buf_size_vecs;
    7583:   PetscBool              ismatis,isdense,newisdense,destroy_mat;
    7584:   ISLocalToGlobalMapping l2gmap;
    7585:   PetscInt*              l2gmap_indices;
    7586:   const PetscInt*        is_indices;
    7587:   MatType                new_local_type;
    7588:   /* buffers */
    7589:   PetscInt               *ptr_idxs,*send_buffer_idxs,*recv_buffer_idxs;
    7590:   PetscInt               *ptr_idxs_is,*send_buffer_idxs_is,*recv_buffer_idxs_is;
    7591:   PetscInt               *recv_buffer_idxs_local;
    7592:   PetscScalar            *ptr_vals,*recv_buffer_vals;
    7593:   const PetscScalar      *send_buffer_vals;
    7594:   PetscScalar            *ptr_vecs,*send_buffer_vecs,*recv_buffer_vecs;
    7595:   /* MPI */
    7596:   MPI_Comm               comm,comm_n;
    7597:   PetscSubcomm           subcomm;
    7598:   PetscMPIInt            n_sends,n_recvs,size;
    7599:   PetscMPIInt            *iflags,*ilengths_idxs,*ilengths_vals,*ilengths_idxs_is;
    7600:   PetscMPIInt            *onodes,*onodes_is,*olengths_idxs,*olengths_idxs_is,*olengths_vals;
    7601:   PetscMPIInt            len,tag_idxs,tag_idxs_is,tag_vals,tag_vecs,source_dest;
    7602:   MPI_Request            *send_req_idxs,*send_req_idxs_is,*send_req_vals,*send_req_vecs;
    7603:   MPI_Request            *recv_req_idxs,*recv_req_idxs_is,*recv_req_vals,*recv_req_vecs;
    7604:   PetscErrorCode         ierr;

    7608:   PetscObjectTypeCompare((PetscObject)mat,MATIS,&ismatis);
    7609:   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);
    7616:   if (nvecs) {
    7617:     if (nvecs > 1) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Just 1 vector supported");
    7619:   }
    7620:   /* further checks */
    7621:   MatISGetLocalMat(mat,&local_mat);
    7622:   PetscObjectTypeCompare((PetscObject)local_mat,MATSEQDENSE,&isdense);
    7623:   if (!isdense) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Currently cannot subassemble MATIS when local matrix type is not of type SEQDENSE");
    7624:   MatGetSize(local_mat,&rows,&cols);
    7625:   if (rows != cols) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Local MATIS matrices should be square");
    7626:   if (reuse && *mat_n) {
    7627:     PetscInt mrows,mcols,mnrows,mncols;
    7629:     PetscObjectTypeCompare((PetscObject)*mat_n,MATIS,&ismatis);
    7630:     if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)*mat_n),PETSC_ERR_SUP,"Cannot reuse a matrix which is not of type MATIS");
    7631:     MatGetSize(mat,&mrows,&mcols);
    7632:     MatGetSize(*mat_n,&mnrows,&mncols);
    7633:     if (mrows != mnrows) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix! Wrong number of rows %D != %D",mrows,mnrows);
    7634:     if (mcols != mncols) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix! Wrong number of cols %D != %D",mcols,mncols);
    7635:   }
    7636:   MatGetBlockSize(local_mat,&bs);

    7639:   /* prepare IS for sending if not provided */
    7640:   if (!is_sends) {
    7641:     if (!n_subdomains) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"You should specify either an IS or a target number of subdomains");
    7642:     PCBDDCMatISGetSubassemblingPattern(mat,&n_subdomains,0,&is_sends_internal,NULL);
    7643:   } else {
    7644:     PetscObjectReference((PetscObject)is_sends);
    7645:     is_sends_internal = is_sends;
    7646:   }

    7648:   /* get comm */
    7649:   PetscObjectGetComm((PetscObject)mat,&comm);

    7651:   /* compute number of sends */
    7652:   ISGetLocalSize(is_sends_internal,&i);
    7653:   PetscMPIIntCast(i,&n_sends);

    7655:   /* compute number of receives */
    7656:   MPI_Comm_size(comm,&size);
    7657:   PetscMalloc1(size,&iflags);
    7658:   PetscArrayzero(iflags,size);
    7659:   ISGetIndices(is_sends_internal,&is_indices);
    7660:   for (i=0;i<n_sends;i++) iflags[is_indices[i]] = 1;
    7661:   PetscGatherNumberOfMessages(comm,iflags,NULL,&n_recvs);
    7662:   PetscFree(iflags);

    7664:   /* restrict comm if requested */
    7665:   subcomm = NULL;
    7666:   destroy_mat = PETSC_FALSE;
    7667:   if (restrict_comm) {
    7668:     PetscMPIInt color,subcommsize;

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

    7691:       MPI_Comm_rank(comm,&rank);
    7692:       PetscSubcommCreate(comm,&subcomm);
    7693:       PetscSubcommSetNumber(subcomm,2);
    7694:       PetscSubcommSetTypeGeneral(subcomm,color,rank);
    7695:       comm_n = PetscSubcommChild(subcomm);
    7696:     }
    7697:     /* flag to destroy *mat_n if not significative */
    7698:     if (color) destroy_mat = PETSC_TRUE;
    7699:   } else {
    7700:     comm_n = comm;
    7701:   }

    7703:   /* prepare send/receive buffers */
    7704:   PetscMalloc1(size,&ilengths_idxs);
    7705:   PetscArrayzero(ilengths_idxs,size);
    7706:   PetscMalloc1(size,&ilengths_vals);
    7707:   PetscArrayzero(ilengths_vals,size);
    7708:   if (nis) {
    7709:     PetscCalloc1(size,&ilengths_idxs_is);
    7710:   }

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

    7767:   buf_size_idxs = 0;
    7768:   buf_size_vals = 0;
    7769:   buf_size_idxs_is = 0;
    7770:   buf_size_vecs = 0;
    7771:   for (i=0;i<n_recvs;i++) {
    7772:     buf_size_idxs += (PetscInt)olengths_idxs[i];
    7773:     buf_size_vals += (PetscInt)olengths_vals[i];
    7774:     if (nis) buf_size_idxs_is += (PetscInt)olengths_idxs_is[i];
    7775:     if (nvecs) buf_size_vecs += (PetscInt)olengths_idxs[i];
    7776:   }
    7777:   PetscMalloc1(buf_size_idxs,&recv_buffer_idxs);
    7778:   PetscMalloc1(buf_size_vals,&recv_buffer_vals);
    7779:   PetscMalloc1(buf_size_idxs_is,&recv_buffer_idxs_is);
    7780:   PetscMalloc1(buf_size_vecs,&recv_buffer_vecs);

    7782:   /* get new tags for clean communications */
    7783:   PetscObjectGetNewTag((PetscObject)mat,&tag_idxs);
    7784:   PetscObjectGetNewTag((PetscObject)mat,&tag_vals);
    7785:   PetscObjectGetNewTag((PetscObject)mat,&tag_idxs_is);
    7786:   PetscObjectGetNewTag((PetscObject)mat,&tag_vecs);

    7788:   /* allocate for requests */
    7789:   PetscMalloc1(n_sends,&send_req_idxs);
    7790:   PetscMalloc1(n_sends,&send_req_vals);
    7791:   PetscMalloc1(n_sends,&send_req_idxs_is);
    7792:   PetscMalloc1(n_sends,&send_req_vecs);
    7793:   PetscMalloc1(n_recvs,&recv_req_idxs);
    7794:   PetscMalloc1(n_recvs,&recv_req_vals);
    7795:   PetscMalloc1(n_recvs,&recv_req_idxs_is);
    7796:   PetscMalloc1(n_recvs,&recv_req_vecs);

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

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

    7855:   /* infer new local matrix type from received local matrices type */
    7856:   /* currently if all local matrices are of type X, then the resulting matrix will be of type X, except for the dense case */
    7857:   /* 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) */
    7858:   if (n_recvs) {
    7859:     MatTypePrivate new_local_type_private = (MatTypePrivate)send_buffer_idxs[0];
    7860:     ptr_idxs = recv_buffer_idxs;
    7861:     for (i=0;i<n_recvs;i++) {
    7862:       if ((PetscInt)new_local_type_private != *ptr_idxs) {
    7863:         new_local_type_private = MATAIJ_PRIVATE;
    7864:         break;
    7865:       }
    7866:       ptr_idxs += olengths_idxs[i];
    7867:     }
    7868:     switch (new_local_type_private) {
    7869:       case MATDENSE_PRIVATE:
    7870:         new_local_type = MATSEQAIJ;
    7871:         bs = 1;
    7872:         break;
    7873:       case MATAIJ_PRIVATE:
    7874:         new_local_type = MATSEQAIJ;
    7875:         bs = 1;
    7876:         break;
    7877:       case MATBAIJ_PRIVATE:
    7878:         new_local_type = MATSEQBAIJ;
    7879:         break;
    7880:       case MATSBAIJ_PRIVATE:
    7881:         new_local_type = MATSEQSBAIJ;
    7882:         break;
    7883:       default:
    7884:         SETERRQ2(comm,PETSC_ERR_SUP,"Unsupported private type %d in %s",new_local_type_private,PETSC_FUNCTION_NAME);
    7885:     }
    7886:   } else { /* by default, new_local_type is seqaij */
    7887:     new_local_type = MATSEQAIJ;
    7888:     bs = 1;
    7889:   }

    7891:   /* create MATIS object if needed */
    7892:   if (!reuse) {
    7893:     MatGetSize(mat,&rows,&cols);
    7894:     MatCreateIS(comm_n,bs,PETSC_DECIDE,PETSC_DECIDE,rows,cols,l2gmap,NULL,mat_n);
    7895:   } else {
    7896:     /* it also destroys the local matrices */
    7897:     if (*mat_n) {
    7898:       MatSetLocalToGlobalMapping(*mat_n,l2gmap,l2gmap);
    7899:     } else { /* this is a fake object */
    7900:       MatCreateIS(comm_n,bs,PETSC_DECIDE,PETSC_DECIDE,rows,cols,l2gmap,NULL,mat_n);
    7901:     }
    7902:   }
    7903:   MatISGetLocalMat(*mat_n,&local_mat);
    7904:   MatSetType(local_mat,new_local_type);

    7906:   MPI_Waitall(n_recvs,recv_req_vals,MPI_STATUSES_IGNORE);

    7908:   /* Global to local map of received indices */
    7909:   PetscMalloc1(buf_size_idxs,&recv_buffer_idxs_local); /* needed for values insertion */
    7910:   ISGlobalToLocalMappingApply(l2gmap,IS_GTOLM_MASK,buf_size_idxs,recv_buffer_idxs,&i,recv_buffer_idxs_local);
    7911:   ISLocalToGlobalMappingDestroy(&l2gmap);

    7913:   /* restore attributes -> type of incoming data and its size */
    7914:   buf_size_idxs = 0;
    7915:   for (i=0;i<n_recvs;i++) {
    7916:     recv_buffer_idxs_local[buf_size_idxs] = recv_buffer_idxs[buf_size_idxs];
    7917:     recv_buffer_idxs_local[buf_size_idxs+1] = recv_buffer_idxs[buf_size_idxs+1];
    7918:     buf_size_idxs += (PetscInt)olengths_idxs[i];
    7919:   }
    7920:   PetscFree(recv_buffer_idxs);

    7922:   /* set preallocation */
    7923:   PetscObjectTypeCompare((PetscObject)local_mat,MATSEQDENSE,&newisdense);
    7924:   if (!newisdense) {
    7925:     PetscInt *new_local_nnz=NULL;

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

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

    7980: #if 0
    7981:   if (!restrict_comm) { /* check */
    7982:     Vec       lvec,rvec;
    7983:     PetscReal infty_error;

    7985:     MatCreateVecs(mat,&rvec,&lvec);
    7986:     VecSetRandom(rvec,NULL);
    7987:     MatMult(mat,rvec,lvec);
    7988:     VecScale(lvec,-1.0);
    7989:     MatMultAdd(*mat_n,rvec,lvec,lvec);
    7990:     VecNorm(lvec,NORM_INFINITY,&infty_error);
    7991:     PetscPrintf(PetscObjectComm((PetscObject)mat),"Infinity error subassembling %1.6e\n",infty_error);
    7992:     VecDestroy(&rvec);
    7993:     VecDestroy(&lvec);
    7994:   }
    7995: #endif

    7997:   /* assemble new additional is (if any) */
    7998:   if (nis) {
    7999:     PetscInt **temp_idxs,*count_is,j,psum;

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

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

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

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

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

    8143:   PetscLogEventBegin(PC_BDDC_CoarseSetUp[pcbddc->current_level],pc,0,0,0);
    8144:   /* Assign global numbering to coarse dofs */
    8145:   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 */
    8146:     PetscInt ocoarse_size;
    8147:     compute_vecs = PETSC_TRUE;

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

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

    8185:   /* creates temporary MATIS object for coarse matrix */
    8186:   MatCreateSeqDense(PETSC_COMM_SELF,pcbddc->local_primal_size,pcbddc->local_primal_size,coarse_submat_vals,&coarse_submat_dense);
    8187:   MatCreateIS(PetscObjectComm((PetscObject)pc),1,PETSC_DECIDE,PETSC_DECIDE,pcbddc->coarse_size,pcbddc->coarse_size,coarse_islg,NULL,&t_coarse_mat_is);
    8188:   MatISSetLocalMat(t_coarse_mat_is,coarse_submat_dense);
    8189:   MatAssemblyBegin(t_coarse_mat_is,MAT_FINAL_ASSEMBLY);
    8190:   MatAssemblyEnd(t_coarse_mat_is,MAT_FINAL_ASSEMBLY);
    8191:   MatDestroy(&coarse_submat_dense);

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

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

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

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

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

    8334:   /* subassemble */
    8335:   if (multilevel_allowed) {
    8336:     Vec       vp[1];
    8337:     PetscInt  nvecs = 0;
    8338:     PetscBool reuse,reuser;

    8340:     if (coarse_mat) reuse = PETSC_TRUE;
    8341:     else reuse = PETSC_FALSE;
    8342:     MPIU_Allreduce(&reuse,&reuser,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    8343:     vp[0] = NULL;
    8344:     if (pcbddc->benign_have_null) { /* propagate no-net-flux quadrature to coarser level */
    8345:       VecCreate(PetscObjectComm((PetscObject)pc),&vp[0]);
    8346:       VecSetSizes(vp[0],pcbddc->local_primal_size,PETSC_DECIDE);
    8347:       VecSetType(vp[0],VECSTANDARD);
    8348:       nvecs = 1;

    8350:       if (pcbddc->divudotp) {
    8351:         Mat      B,loc_divudotp;
    8352:         Vec      v,p;
    8353:         IS       dummy;
    8354:         PetscInt np;

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

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

    8429:   /* set defaults for coarse KSP and PC */
    8430:   if (multilevel_allowed) {
    8431:     coarse_ksp_type = KSPRICHARDSON;
    8432:     coarse_pc_type  = PCBDDC;
    8433:   } else {
    8434:     coarse_ksp_type = KSPPREONLY;
    8435:     coarse_pc_type  = PCREDUNDANT;
    8436:   }

    8438:   /* print some info if requested */
    8439:   if (pcbddc->dbg_flag) {
    8440:     if (!multilevel_allowed) {
    8441:       PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"--------------------------------------------------\n");
    8442:       if (multilevel_requested) {
    8443:         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);
    8444:       } else if (pcbddc->max_levels) {
    8445:         PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Maximum number of requested levels reached (%D)\n",pcbddc->max_levels);
    8446:       }
    8447:       PetscViewerFlush(pcbddc->dbg_viewer);
    8448:     }
    8449:   }

    8451:   /* communicate coarse discrete gradient */
    8452:   coarseG = NULL;
    8453:   if (pcbddc->nedcG && multilevel_allowed) {
    8454:     MPI_Comm ccomm;
    8455:     if (coarse_mat) {
    8456:       ccomm = PetscObjectComm((PetscObject)coarse_mat);
    8457:     } else {
    8458:       ccomm = MPI_COMM_NULL;
    8459:     }
    8460:     MatMPIAIJRestrict(pcbddc->nedcG,ccomm,&coarseG);
    8461:   }

    8463:   /* create the coarse KSP object only once with defaults */
    8464:   if (coarse_mat) {
    8465:     PetscBool   isredundant,isbddc,force,valid;
    8466:     PetscViewer dbg_viewer = NULL;

    8468:     if (pcbddc->dbg_flag) {
    8469:       dbg_viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)coarse_mat));
    8470:       PetscViewerASCIIAddTab(dbg_viewer,2*pcbddc->current_level);
    8471:     }
    8472:     if (!pcbddc->coarse_ksp) {
    8473:       char   prefix[256],str_level[16];
    8474:       size_t len;

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

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

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

    8569:       PCRedundantGetKSP(pc_temp,&inner_ksp);
    8570:       KSPGetPC(inner_ksp,&inner_pc);
    8571:     }

    8573:     /* parameters which miss an API */
    8574:     PetscObjectTypeCompare((PetscObject)pc_temp,PCBDDC,&isbddc);
    8575:     if (isbddc) {
    8576:       PC_BDDC* pcbddc_coarse = (PC_BDDC*)pc_temp->data;

    8578:       pcbddc_coarse->detect_disconnected = PETSC_TRUE;
    8579:       pcbddc_coarse->coarse_eqs_per_proc = pcbddc->coarse_eqs_per_proc;
    8580:       pcbddc_coarse->coarse_eqs_limit    = pcbddc->coarse_eqs_limit;
    8581:       pcbddc_coarse->benign_saddle_point = pcbddc->benign_have_null;
    8582:       if (pcbddc_coarse->benign_saddle_point) {
    8583:         Mat                    coarsedivudotp_is;
    8584:         ISLocalToGlobalMapping l2gmap,rl2g,cl2g;
    8585:         IS                     row,col;
    8586:         const PetscInt         *gidxs;
    8587:         PetscInt               n,st,M,N;

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

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

    8656:   if (corners) {
    8657:     Vec            gv;
    8658:     IS             is;
    8659:     const PetscInt *idxs;
    8660:     PetscInt       i,d,N,n,cdim = pcbddc->mat_graph->cdim;
    8661:     PetscScalar    *coords;

    8663:     if (!pcbddc->mat_graph->cloc) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Missing local coordinates");
    8664:     VecGetSize(pcbddc->coarse_vec,&N);
    8665:     VecGetLocalSize(pcbddc->coarse_vec,&n);
    8666:     VecCreate(PetscObjectComm((PetscObject)pcbddc->coarse_vec),&gv);
    8667:     VecSetBlockSize(gv,cdim);
    8668:     VecSetSizes(gv,n*cdim,N*cdim);
    8669:     VecSetType(gv,VECSTANDARD);
    8670:     VecSetFromOptions(gv);
    8671:     VecSet(gv,PETSC_MAX_REAL); /* we only propagate coordinates from vertices constraints */

    8673:     PCBDDCGraphGetCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&is);
    8674:     ISGetLocalSize(is,&n);
    8675:     ISGetIndices(is,&idxs);
    8676:     PetscMalloc1(n*cdim,&coords);
    8677:     for (i=0;i<n;i++) {
    8678:       for (d=0;d<cdim;d++) {
    8679:         coords[cdim*i+d] = pcbddc->mat_graph->coords[cdim*idxs[i]+d];
    8680:       }
    8681:     }
    8682:     ISRestoreIndices(is,&idxs);
    8683:     PCBDDCGraphRestoreCandidatesIS(pcbddc->mat_graph,NULL,NULL,NULL,NULL,&is);

    8685:     ISGetLocalSize(corners,&n);
    8686:     ISGetIndices(corners,&idxs);
    8687:     VecSetValuesBlocked(gv,n,idxs,coords,INSERT_VALUES);
    8688:     ISRestoreIndices(corners,&idxs);
    8689:     PetscFree(coords);
    8690:     VecAssemblyBegin(gv);
    8691:     VecAssemblyEnd(gv);
    8692:     VecGetArray(gv,&coords);
    8693:     if (pcbddc->coarse_ksp) {
    8694:       PC        coarse_pc;
    8695:       PetscBool isbddc;

    8697:       KSPGetPC(pcbddc->coarse_ksp,&coarse_pc);
    8698:       PetscObjectTypeCompare((PetscObject)coarse_pc,PCBDDC,&isbddc);
    8699:       if (isbddc) { /* coarse coordinates have PETSC_MAX_REAL, specific for BDDC */
    8700:         PetscReal *realcoords;

    8702:         VecGetLocalSize(gv,&n);
    8703: #if defined(PETSC_USE_COMPLEX)
    8704:         PetscMalloc1(n,&realcoords);
    8705:         for (i=0;i<n;i++) realcoords[i] = PetscRealPart(coords[i]);
    8706: #else
    8707:         realcoords = coords;
    8708: #endif
    8709:         PCSetCoordinates(coarse_pc,cdim,n/cdim,realcoords);
    8710: #if defined(PETSC_USE_COMPLEX)
    8711:         PetscFree(realcoords);
    8712: #endif
    8713:       }
    8714:     }
    8715:     VecRestoreArray(gv,&coords);
    8716:     VecDestroy(&gv);
    8717:   }
    8718:   ISDestroy(&corners);

    8720:   if (pcbddc->coarse_ksp) {
    8721:     Vec crhs,csol;

    8723:     KSPGetSolution(pcbddc->coarse_ksp,&csol);
    8724:     KSPGetRhs(pcbddc->coarse_ksp,&crhs);
    8725:     if (!csol) {
    8726:       MatCreateVecs(coarse_mat,&((pcbddc->coarse_ksp)->vec_sol),NULL);
    8727:     }
    8728:     if (!crhs) {
    8729:       MatCreateVecs(coarse_mat,NULL,&((pcbddc->coarse_ksp)->vec_rhs));
    8730:     }
    8731:   }
    8732:   MatDestroy(&coarsedivudotp);

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

    8737:     VecSet(pcbddc->vec1_P,0.);
    8738:     for (i=0;i<pcbddc->benign_n;i++) {
    8739:       VecSetValue(pcbddc->vec1_P,pcbddc->local_primal_size-pcbddc->benign_n+i,1.0,INSERT_VALUES);
    8740:     }
    8741:     VecAssemblyBegin(pcbddc->vec1_P);
    8742:     VecAssemblyEnd(pcbddc->vec1_P);
    8743:     VecScatterBegin(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,INSERT_VALUES,SCATTER_FORWARD);
    8744:     VecScatterEnd(pcbddc->coarse_loc_to_glob,pcbddc->vec1_P,pcbddc->coarse_vec,INSERT_VALUES,SCATTER_FORWARD);
    8745:     if (coarse_mat) {
    8746:       Vec         nullv;
    8747:       PetscScalar *array,*array2;
    8748:       PetscInt    nl;

    8750:       MatCreateVecs(coarse_mat,&nullv,NULL);
    8751:       VecGetLocalSize(nullv,&nl);
    8752:       VecGetArrayRead(pcbddc->coarse_vec,(const PetscScalar**)&array);
    8753:       VecGetArray(nullv,&array2);
    8754:       PetscArraycpy(array2,array,nl);
    8755:       VecRestoreArray(nullv,&array2);
    8756:       VecRestoreArrayRead(pcbddc->coarse_vec,(const PetscScalar**)&array);
    8757:       VecNormalize(nullv,NULL);
    8758:       MatNullSpaceCreate(PetscObjectComm((PetscObject)coarse_mat),PETSC_FALSE,1,&nullv,&CoarseNullSpace);
    8759:       VecDestroy(&nullv);
    8760:     }
    8761:   }
    8762:   PetscLogEventEnd(PC_BDDC_CoarseSetUp[pcbddc->current_level],pc,0,0,0);

    8764:   PetscLogEventBegin(PC_BDDC_CoarseSolver[pcbddc->current_level],pc,0,0,0);
    8765:   if (pcbddc->coarse_ksp) {
    8766:     PetscBool ispreonly;

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

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

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

    8892:   /* free memory */
    8893:   MatDestroy(&coarse_mat);
    8894:   PetscLogEventEnd(PC_BDDC_CoarseSolver[pcbddc->current_level],pc,0,0,0);
    8895:   return(0);
    8896: }

    8898: PetscErrorCode PCBDDCComputePrimalNumbering(PC pc,PetscInt* coarse_size_n,PetscInt** local_primal_indices_n)
    8899: {
    8900:   PC_BDDC*       pcbddc = (PC_BDDC*)pc->data;
    8901:   PC_IS*         pcis = (PC_IS*)pc->data;
    8902:   Mat_IS*        matis = (Mat_IS*)pc->pmat->data;
    8903:   IS             subset,subset_mult,subset_n;
    8904:   PetscInt       local_size,coarse_size=0;
    8905:   PetscInt       *local_primal_indices=NULL;
    8906:   const PetscInt *t_local_primal_indices;

    8910:   /* Compute global number of coarse dofs */
    8911:   if (pcbddc->local_primal_size && !pcbddc->local_primal_ref_node) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"BDDC ConstraintsSetUp should be called first");
    8912:   ISCreateGeneral(PetscObjectComm((PetscObject)(pc->pmat)),pcbddc->local_primal_size_cc,pcbddc->local_primal_ref_node,PETSC_COPY_VALUES,&subset_n);
    8913:   ISLocalToGlobalMappingApplyIS(pcis->mapping,subset_n,&subset);
    8914:   ISDestroy(&subset_n);
    8915:   ISCreateGeneral(PetscObjectComm((PetscObject)(pc->pmat)),pcbddc->local_primal_size_cc,pcbddc->local_primal_ref_mult,PETSC_COPY_VALUES,&subset_mult);
    8916:   ISRenumber(subset,subset_mult,&coarse_size,&subset_n);
    8917:   ISDestroy(&subset);
    8918:   ISDestroy(&subset_mult);
    8919:   ISGetLocalSize(subset_n,&local_size);
    8920:   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);
    8921:   PetscMalloc1(local_size,&local_primal_indices);
    8922:   ISGetIndices(subset_n,&t_local_primal_indices);
    8923:   PetscArraycpy(local_primal_indices,t_local_primal_indices,local_size);
    8924:   ISRestoreIndices(subset_n,&t_local_primal_indices);
    8925:   ISDestroy(&subset_n);

    8927:   /* check numbering */
    8928:   if (pcbddc->dbg_flag) {
    8929:     PetscScalar coarsesum,*array,*array2;
    8930:     PetscInt    i;
    8931:     PetscBool   set_error = PETSC_FALSE,set_error_reduced = PETSC_FALSE;

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

    8981:       PetscMalloc1(pcbddc->local_primal_size,&gidxs);
    8982:       ISLocalToGlobalMappingApply(pcis->mapping,pcbddc->local_primal_size,pcbddc->primal_indices_local_idxs,gidxs);
    8983:       PetscViewerASCIIPrintf(pcbddc->dbg_viewer,"Distribution of local primal indices\n");
    8984:       PetscViewerFlush(pcbddc->dbg_viewer);
    8985:       PetscViewerASCIISynchronizedPrintf(pcbddc->dbg_viewer,"Subdomain %04d\n",PetscGlobalRank);
    8986:       for (i=0;i<pcbddc->local_primal_size;i++) {
    8987:         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]);
    8988:       }
    8989:       PetscViewerFlush(pcbddc->dbg_viewer);
    8990:       PetscFree(gidxs);
    8991:     }
    8992:     PetscViewerFlush(pcbddc->dbg_viewer);
    8993:     PetscViewerASCIIPushSynchronized(pcbddc->dbg_viewer);
    8994:     if (set_error_reduced) SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_PLIB,"BDDC Numbering of coarse dofs failed");
    8995:   }

    8997:   /* get back data */
    8998:   *coarse_size_n = coarse_size;
    8999:   *local_primal_indices_n = local_primal_indices;
    9000:   return(0);
    9001: }

    9003: PetscErrorCode PCBDDCGlobalToLocal(VecScatter g2l_ctx,Vec gwork, Vec lwork, IS globalis, IS* localis)
    9004: {
    9005:   IS             localis_t;
    9006:   PetscInt       i,lsize,*idxs,n;
    9007:   PetscScalar    *vals;

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

    9048: PetscErrorCode PCBDDCSetUpSubSchurs(PC pc)
    9049: {
    9050:   PC_IS               *pcis=(PC_IS*)pc->data;
    9051:   PC_BDDC             *pcbddc=(PC_BDDC*)pc->data;
    9052:   PCBDDCSubSchurs     sub_schurs=pcbddc->sub_schurs;
    9053:   Mat                 S_j;
    9054:   PetscInt            *used_xadj,*used_adjncy;
    9055:   PetscBool           free_used_adj;
    9056:   PetscErrorCode      ierr;

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

    9077:       MatGetRowIJ(pcbddc->local_mat,0,PETSC_TRUE,PETSC_FALSE,&nvtxs,&xadj,&adjncy,&flg_row);
    9078:       if (flg_row) {
    9079:         PetscMalloc2(nvtxs+1,&used_xadj,xadj[nvtxs],&used_adjncy);
    9080:         PetscArraycpy(used_xadj,xadj,nvtxs+1);
    9081:         PetscArraycpy(used_adjncy,adjncy,xadj[nvtxs]);
    9082:         free_used_adj = PETSC_TRUE;
    9083:       } else {
    9084:         pcbddc->sub_schurs_layers = -1;
    9085:         used_xadj = NULL;
    9086:         used_adjncy = NULL;
    9087:       }
    9088:       MatRestoreRowIJ(pcbddc->local_mat,0,PETSC_TRUE,PETSC_FALSE,&nvtxs,&xadj,&adjncy,&flg_row);
    9089:     }
    9090:   }

    9092:   /* setup sub_schurs data */
    9093:   MatCreateSchurComplement(pcis->A_II,pcis->pA_II,pcis->A_IB,pcis->A_BI,pcis->A_BB,&S_j);
    9094:   if (!sub_schurs->schur_explicit) {
    9095:     /* pcbddc->ksp_D up to date only if not using MatFactor with Schur complement support */
    9096:     MatSchurComplementSetKSP(S_j,pcbddc->ksp_D);
    9097:     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);
    9098:   } else {
    9099:     Mat       change = NULL;
    9100:     Vec       scaling = NULL;
    9101:     IS        change_primal = NULL, iP;
    9102:     PetscInt  benign_n;
    9103:     PetscBool reuse_solvers = (PetscBool)!pcbddc->use_change_of_basis;
    9104:     PetscBool need_change = PETSC_FALSE;
    9105:     PetscBool discrete_harmonic = PETSC_FALSE;

    9107:     if (!pcbddc->use_vertices && reuse_solvers) {
    9108:       PetscInt n_vertices;

    9110:       ISGetLocalSize(sub_schurs->is_vertices,&n_vertices);
    9111:       reuse_solvers = (PetscBool)!n_vertices;
    9112:     }
    9113:     if (!pcbddc->benign_change_explicit) {
    9114:       benign_n = pcbddc->benign_n;
    9115:     } else {
    9116:       benign_n = 0;
    9117:     }
    9118:     /* sub_schurs->change is a local object; instead, PCBDDCConstraintsSetUp and the quantities used in the test below are logically collective on pc.
    9119:        We need a global reduction to avoid possible deadlocks.
    9120:        We assume that sub_schurs->change is created once, and then reused for different solves, unless the topography has been recomputed */
    9121:     if (pcbddc->adaptive_userdefined || (pcbddc->deluxe_zerorows && !pcbddc->use_change_of_basis)) {
    9122:       PetscBool have_loc_change = (PetscBool)(!!sub_schurs->change);
    9123:       MPIU_Allreduce(&have_loc_change,&need_change,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)pc));
    9124:       need_change = (PetscBool)(!need_change);
    9125:     }
    9126:     /* If the user defines additional constraints, we import them here.
    9127:        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 */
    9128:     if (need_change) {
    9129:       PC_IS   *pcisf;
    9130:       PC_BDDC *pcbddcf;
    9131:       PC      pcf;

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

    9138:       /* hacks */
    9139:       pcisf                        = (PC_IS*)pcf->data;
    9140:       pcisf->is_B_local            = pcis->is_B_local;
    9141:       pcisf->vec1_N                = pcis->vec1_N;
    9142:       pcisf->BtoNmap               = pcis->BtoNmap;
    9143:       pcisf->n                     = pcis->n;
    9144:       pcisf->n_B                   = pcis->n_B;
    9145:       pcbddcf                      = (PC_BDDC*)pcf->data;
    9146:       PetscFree(pcbddcf->mat_graph);
    9147:       pcbddcf->mat_graph           = pcbddc->mat_graph;
    9148:       pcbddcf->use_faces           = PETSC_TRUE;
    9149:       pcbddcf->use_change_of_basis = PETSC_TRUE;
    9150:       pcbddcf->use_change_on_faces = PETSC_TRUE;
    9151:       pcbddcf->use_qr_single       = PETSC_TRUE;
    9152:       pcbddcf->fake_change         = PETSC_TRUE;

    9154:       /* setup constraints so that we can get information on primal vertices and change of basis (in local numbering) */
    9155:       PCBDDCConstraintsSetUp(pcf);
    9156:       sub_schurs->change_with_qr = pcbddcf->use_qr_single;
    9157:       ISCreateGeneral(PETSC_COMM_SELF,pcbddcf->n_vertices,pcbddcf->local_primal_ref_node,PETSC_COPY_VALUES,&change_primal);
    9158:       change = pcbddcf->ConstraintMatrix;
    9159:       pcbddcf->ConstraintMatrix = NULL;

    9161:       /* free unneeded memory allocated in PCBDDCConstraintsSetUp */
    9162:       PetscFree(pcbddcf->sub_schurs);
    9163:       MatNullSpaceDestroy(&pcbddcf->onearnullspace);
    9164:       PetscFree2(pcbddcf->local_primal_ref_node,pcbddcf->local_primal_ref_mult);
    9165:       PetscFree(pcbddcf->primal_indices_local_idxs);
    9166:       PetscFree(pcbddcf->onearnullvecs_state);
    9167:       PetscFree(pcf->data);
    9168:       pcf->ops->destroy = NULL;
    9169:       pcf->ops->reset   = NULL;
    9170:       PCDestroy(&pcf);
    9171:     }
    9172:     if (!pcbddc->use_deluxe_scaling) scaling = pcis->D;

    9174:     PetscObjectQuery((PetscObject)pc,"__KSPFETIDP_iP",(PetscObject*)&iP);
    9175:     if (iP) {
    9176:       PetscOptionsBegin(PetscObjectComm((PetscObject)iP),sub_schurs->prefix,"BDDC sub_schurs options","PC");
    9177:       PetscOptionsBool("-sub_schurs_discrete_harmonic",NULL,NULL,discrete_harmonic,&discrete_harmonic,NULL);
    9178:       PetscOptionsEnd();
    9179:     }
    9180:     if (discrete_harmonic) {
    9181:       Mat A;
    9182:       MatDuplicate(pcbddc->local_mat,MAT_COPY_VALUES,&A);
    9183:       MatZeroRowsColumnsIS(A,iP,1.0,NULL,NULL);
    9184:       PetscObjectCompose((PetscObject)A,"__KSPFETIDP_iP",(PetscObject)iP);
    9185:       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);
    9186:       MatDestroy(&A);
    9187:     } else {
    9188:       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);
    9189:     }
    9190:     MatDestroy(&change);
    9191:     ISDestroy(&change_primal);
    9192:   }
    9193:   MatDestroy(&S_j);

    9195:   /* free adjacency */
    9196:   if (free_used_adj) {
    9197:     PetscFree2(used_xadj,used_adjncy);
    9198:   }
    9199:   PetscLogEventEnd(PC_BDDC_Schurs[pcbddc->current_level],pc,0,0,0);
    9200:   return(0);
    9201: }

    9203: PetscErrorCode PCBDDCInitSubSchurs(PC pc)
    9204: {
    9205:   PC_IS               *pcis=(PC_IS*)pc->data;
    9206:   PC_BDDC             *pcbddc=(PC_BDDC*)pc->data;
    9207:   PCBDDCGraph         graph;
    9208:   PetscErrorCode      ierr;

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

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

    9247:   /* sub_schurs init */
    9248:   if (!pcbddc->sub_schurs) {
    9249:     PCBDDCSubSchursCreate(&pcbddc->sub_schurs);
    9250:   }
    9251:   PCBDDCSubSchursInit(pcbddc->sub_schurs,((PetscObject)pc)->prefix,pcis->is_I_local,pcis->is_B_local,graph,pcis->BtoNmap,pcbddc->sub_schurs_rebuild);

    9253:   /* free graph struct */
    9254:   if (pcbddc->sub_schurs_rebuild) {
    9255:     PCBDDCGraphDestroy(&graph);
    9256:   }
    9257:   return(0);
    9258: }

    9260: PetscErrorCode PCBDDCCheckOperator(PC pc)
    9261: {
    9262:   PC_IS               *pcis=(PC_IS*)pc->data;
    9263:   PC_BDDC             *pcbddc=(PC_BDDC*)pc->data;
    9264:   PetscErrorCode      ierr;

    9267:   if (pcbddc->n_vertices == pcbddc->local_primal_size) {
    9268:     IS             zerodiag = NULL;
    9269:     Mat            S_j,B0_B=NULL;
    9270:     Vec            dummy_vec=NULL,vec_check_B,vec_scale_P;
    9271:     PetscScalar    *p0_check,*array,*array2;
    9272:     PetscReal      norm;
    9273:     PetscInt       i;

    9275:     /* B0 and B0_B */
    9276:     if (zerodiag) {
    9277:       IS       dummy;

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

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

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

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

    9374: #include <../src/mat/impls/aij/mpi/mpiaij.h>
    9375: PetscErrorCode MatMPIAIJRestrict(Mat A, MPI_Comm ccomm, Mat *B)
    9376: {
    9377:   Mat            At;
    9378:   IS             rows;
    9379:   PetscInt       rst,ren;
    9381:   PetscLayout    rmap;

    9384:   rst = ren = 0;
    9385:   if (ccomm != MPI_COMM_NULL) {
    9386:     PetscLayoutCreate(ccomm,&rmap);
    9387:     PetscLayoutSetSize(rmap,A->rmap->N);
    9388:     PetscLayoutSetBlockSize(rmap,1);
    9389:     PetscLayoutSetUp(rmap);
    9390:     PetscLayoutGetRange(rmap,&rst,&ren);
    9391:   }
    9392:   ISCreateStride(PetscObjectComm((PetscObject)A),ren-rst,rst,1,&rows);
    9393:   MatCreateSubMatrix(A,rows,NULL,MAT_INITIAL_MATRIX,&At);
    9394:   ISDestroy(&rows);

    9396:   if (ccomm != MPI_COMM_NULL) {
    9397:     Mat_MPIAIJ *a,*b;
    9398:     IS         from,to;
    9399:     Vec        gvec;
    9400:     PetscInt   lsize;

    9402:     MatCreate(ccomm,B);
    9403:     MatSetSizes(*B,ren-rst,PETSC_DECIDE,PETSC_DECIDE,At->cmap->N);
    9404:     MatSetType(*B,MATAIJ);
    9405:     PetscLayoutDestroy(&((*B)->rmap));
    9406:     PetscLayoutSetUp((*B)->cmap);
    9407:     a    = (Mat_MPIAIJ*)At->data;
    9408:     b    = (Mat_MPIAIJ*)(*B)->data;
    9409:     MPI_Comm_size(ccomm,&b->size);
    9410:     MPI_Comm_rank(ccomm,&b->rank);
    9411:     PetscObjectReference((PetscObject)a->A);
    9412:     PetscObjectReference((PetscObject)a->B);
    9413:     b->A = a->A;
    9414:     b->B = a->B;

    9416:     b->donotstash      = a->donotstash;
    9417:     b->roworiented     = a->roworiented;
    9418:     b->rowindices      = NULL;
    9419:     b->rowvalues       = NULL;
    9420:     b->getrowactive    = PETSC_FALSE;

    9422:     (*B)->rmap         = rmap;
    9423:     (*B)->factortype   = A->factortype;
    9424:     (*B)->assembled    = PETSC_TRUE;
    9425:     (*B)->insertmode   = NOT_SET_VALUES;
    9426:     (*B)->preallocated = PETSC_TRUE;

    9428:     if (a->colmap) {
    9429: #if defined(PETSC_USE_CTABLE)
    9430:       PetscTableCreateCopy(a->colmap,&b->colmap);
    9431: #else
    9432:       PetscMalloc1(At->cmap->N,&b->colmap);
    9433:       PetscLogObjectMemory((PetscObject)*B,At->cmap->N*sizeof(PetscInt));
    9434:       PetscArraycpy(b->colmap,a->colmap,At->cmap->N);
    9435: #endif
    9436:     } else b->colmap = NULL;
    9437:     if (a->garray) {
    9438:       PetscInt len;
    9439:       len  = a->B->cmap->n;
    9440:       PetscMalloc1(len+1,&b->garray);
    9441:       PetscLogObjectMemory((PetscObject)(*B),len*sizeof(PetscInt));
    9442:       if (len) { PetscArraycpy(b->garray,a->garray,len); }
    9443:     } else b->garray = NULL;

    9445:     PetscObjectReference((PetscObject)a->lvec);
    9446:     b->lvec = a->lvec;
    9447:     PetscLogObjectParent((PetscObject)*B,(PetscObject)b->lvec);

    9449:     /* cannot use VecScatterCopy */
    9450:     VecGetLocalSize(b->lvec,&lsize);
    9451:     ISCreateGeneral(ccomm,lsize,b->garray,PETSC_USE_POINTER,&from);
    9452:     ISCreateStride(PETSC_COMM_SELF,lsize,0,1,&to);
    9453:     MatCreateVecs(*B,&gvec,NULL);
    9454:     VecScatterCreate(gvec,from,b->lvec,to,&b->Mvctx);
    9455:     PetscLogObjectParent((PetscObject)*B,(PetscObject)b->Mvctx);
    9456:     ISDestroy(&from);
    9457:     ISDestroy(&to);
    9458:     VecDestroy(&gvec);
    9459:   }
    9460:   MatDestroy(&At);
    9461:   return(0);
    9462: }