Actual source code: hpddm.cxx

petsc-master 2020-07-10
Report Typos and Errors
  1:  #include <petsc/private/dmimpl.h>
  2:  #include <petsc/private/matimpl.h>
  3:  #include <petsc/private/petschpddm.h>
  4:  #include <petsc/private/pcimpl.h>
  5:                                   /* otherwise, it is assumed that one is compiling libhpddm_petsc => circular dependency */
  6: #if defined(PETSC_HAVE_FORTRAN)
  7:  #include <petsc/private/fortranimpl.h>
  8: #endif

 10: static PetscErrorCode (*loadedSym)(HPDDM::Schwarz<PetscScalar>* const, IS const, IS, const Mat, Mat, std::vector<Vec>, PetscInt* const, PC_HPDDM_Level** const) = NULL;

 12: static PetscBool PCHPDDMPackageInitialized = PETSC_FALSE;
 13: static PetscBool citePC = PETSC_FALSE;
 14: static const char hpddmCitationPC[] = "@inproceedings{jolivet2013scalable,\n\tTitle = {{Scalable Domain Decomposition Preconditioners For Heterogeneous Elliptic Problems}},\n\tAuthor = {Jolivet, Pierre and Hecht, Fr\'ed\'eric and Nataf, Fr\'ed\'eric and Prud'homme, Christophe},\n\tOrganization = {ACM},\n\tYear = {2013},\n\tSeries = {SC13},\n\tBooktitle = {Proceedings of the 2013 International Conference for High Performance Computing, Networking, Storage and Analysis}\n}\n";

 16: PetscLogEvent PC_HPDDM_Strc;
 17: PetscLogEvent PC_HPDDM_PtAP;
 18: PetscLogEvent PC_HPDDM_PtBP;
 19: PetscLogEvent PC_HPDDM_Next;

 21: static const char *PCHPDDMCoarseCorrectionTypes[] = { "deflated", "additive", "balanced" };

 23: static PetscErrorCode PCReset_HPDDM(PC pc)
 24: {
 25:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;
 26:   PetscInt       i;

 30:   if (data->levels) {
 31:     for (i = 0; i < PETSC_HPDDM_MAXLEVELS && data->levels[i]; ++i) {
 32:       KSPDestroy(&data->levels[i]->ksp);
 33:       PCDestroy(&data->levels[i]->pc);
 34:       PetscFree(data->levels[i]);
 35:     }
 36:     PetscFree(data->levels);
 37:   }

 39:   ISDestroy(&data->is);
 40:   MatDestroy(&data->aux);
 41:   MatDestroy(&data->B);
 42:   data->correction = PC_HPDDM_COARSE_CORRECTION_DEFLATED;
 43:   data->Neumann    = PETSC_FALSE;
 44:   data->setup      = NULL;
 45:   data->setup_ctx  = NULL;
 46:   return(0);
 47: }

 49: static PetscErrorCode PCDestroy_HPDDM(PC pc)
 50: {
 51:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

 55:   PCReset_HPDDM(pc);
 56:   PetscFree(data);
 57:   PetscObjectChangeTypeName((PetscObject)pc, 0);
 58:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetAuxiliaryMat_C", NULL);
 59:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMHasNeumannMat_C", NULL);
 60:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetRHSMat_C", NULL);
 61:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetCoarseCorrectionType_C", NULL);
 62:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetCoarseCorrectionType_C", NULL);
 63:   return(0);
 64: }

 66: static PetscErrorCode PCHPDDMSetAuxiliaryMat_HPDDM(PC pc, IS is, Mat A, PetscErrorCode (*setup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void*), void* setup_ctx)
 67: {
 68:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

 72:   if (is) {
 73:     PetscObjectReference((PetscObject)is);
 74:     if (data->is) { /* new overlap definition resets the PC */
 75:       PCReset_HPDDM(pc);
 76:       pc->setfromoptionscalled = 0;
 77:     }
 78:     ISDestroy(&data->is);
 79:     data->is = is;
 80:   }
 81:   if (A) {
 82:     PetscObjectReference((PetscObject)A);
 83:     MatDestroy(&data->aux);
 84:     data->aux = A;
 85:   }
 86:   if (setup) {
 87:     data->setup = setup;
 88:     data->setup_ctx = setup_ctx;
 89:   }
 90:   return(0);
 91: }

 93: /*@
 94:      PCHPDDMSetAuxiliaryMat - Sets the auxiliary matrix used by PCHPDDM for the concurrent GenEO eigenproblems at the finest level. As an example, in a finite element context with nonoverlapping subdomains plus (overlapping) ghost elements, this could be the unassembled (Neumann) local overlapping operator. As opposed to the assembled (Dirichlet) local overlapping operator obtained by summing neighborhood contributions at the interface of ghost elements.

 96:    Input Parameters:
 97: +     pc - preconditioner context
 98: .     is - index set of the local auxiliary, e.g., Neumann, matrix
 99: .     A - auxiliary sequential matrix
100: .     setup - function for generating the auxiliary matrix
101: -     setup_ctx - context for setup

103:    Level: intermediate

105: .seealso:  PCCreate(), PCSetType(), PCType (for list of available types), PC, PCHPDDMSetRHSMat(), MATIS
106: @*/
107: PetscErrorCode PCHPDDMSetAuxiliaryMat(PC pc, IS is, Mat A, PetscErrorCode (*setup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void*), void* setup_ctx)
108: {

115: #if defined(PETSC_HAVE_FORTRAN)
116:   if (reinterpret_cast<void*>(setup) == reinterpret_cast<void*>(PETSC_NULL_FUNCTION_Fortran)) setup = NULL;
117:   if (setup_ctx == PETSC_NULL_INTEGER_Fortran) setup_ctx = NULL;
118: #endif
119:   PetscTryMethod(pc, "PCHPDDMSetAuxiliaryMat_C", (PC, IS, Mat, PetscErrorCode (*)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void*), void*), (pc, is, A, setup, setup_ctx));
120:   return(0);
121: }

123: static PetscErrorCode PCHPDDMHasNeumannMat_HPDDM(PC pc, PetscBool has)
124: {
125:   PC_HPDDM *data = (PC_HPDDM*)pc->data;

128:   data->Neumann = has;
129:   return(0);
130: }

132: /*@
133:      PCHPDDMHasNeumannMat - Informs PCHPDDM that the Mat passed to PCHPDDMSetAuxiliaryMat() is the local Neumann matrix. This may be used to bypass a call to MatCreateSubMatrices() and to MatConvert() for MATMPISBAIJ matrices. If a DMCreateNeumannOverlap() implementation is available in the DM attached to the Pmat, or the Amat, or the PC, the flag is internally set to PETSC_TRUE. Its default value is otherwise PETSC_FALSE.

135:    Input Parameters:
136: +     pc - preconditioner context
137: -     has - Boolean value

139:    Level: intermediate

141: .seealso:  PCHPDDM, PCHPDDMSetAuxiliaryMat()
142: @*/
143: PetscErrorCode PCHPDDMHasNeumannMat(PC pc, PetscBool has)
144: {

149:   PetscTryMethod(pc, "PCHPDDMHasNeumannMat_C", (PC, PetscBool), (pc, has));
150:   return(0);
151: }

153: static PetscErrorCode PCHPDDMSetRHSMat_HPDDM(PC pc, Mat B)
154: {
155:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

159:   PetscObjectReference((PetscObject)B);
160:   MatDestroy(&data->B);
161:   data->B = B;
162:   return(0);
163: }

165: /*@
166:      PCHPDDMSetRHSMat - Sets the right-hand side matrix used by PCHPDDM for the concurrent GenEO eigenproblems at the finest level. Must be used in conjuction with PCHPDDMSetAuxiliaryMat(N), so that Nv = lambda Bv is solved using EPSSetOperators(N, B). It is assumed that N and B are provided using the same numbering. This provides a means to try more advanced methods such as GenEO-II or H-GenEO.

168:    Input Parameters:
169: +     pc - preconditioner context
170: -     B - right-hand side sequential matrix

172:    Level: advanced

174: .seealso:  PCHPDDMSetAuxiliaryMat(), PCHPDDM
175: @*/
176: PetscErrorCode PCHPDDMSetRHSMat(PC pc, Mat B)
177: {

182:   if (B) {
184:     PetscTryMethod(pc, "PCHPDDMSetRHSMat_C", (PC, Mat), (pc, B));
185:   }
186:   return(0);
187: }

189: static PetscErrorCode PCSetFromOptions_HPDDM(PetscOptionItems *PetscOptionsObject, PC pc)
190: {
191:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;
192:   PC_HPDDM_Level **levels = data->levels;
193:   char           prefix[256];
194:   int            i = 1;
195:   PetscMPIInt    size, previous;
196:   PetscInt       n;
197:   PetscBool      flg = PETSC_TRUE;

201:   if (!data->levels) {
202:     PetscCalloc1(PETSC_HPDDM_MAXLEVELS, &levels);
203:     data->levels = levels;
204:   }
205:   PetscOptionsHead(PetscOptionsObject, "PCHPDDM options");
206:   MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size);
207:   previous = size;
208:   while (i < PETSC_HPDDM_MAXLEVELS) {
209:     PetscInt p = 1;

211:     if (!data->levels[i - 1]) {
212:       PetscNewLog(pc, data->levels + i - 1);
213:     }
214:     data->levels[i - 1]->parent = data;
215:     /* if the previous level has a single process, it is not possible to coarsen further */
216:     if (previous == 1 || !flg) break;
217:     data->levels[i - 1]->nu = 0;
218:     data->levels[i - 1]->threshold = -1.0;
219:     PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_nev", i);
220:     PetscOptionsInt(prefix, "Local number of deflation vectors computed by SLEPc", "none", data->levels[i - 1]->nu, &data->levels[i - 1]->nu, NULL);
221:     PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold", i);
222:     PetscOptionsReal(prefix, "Local threshold for selecting deflation vectors returned by SLEPc", "none", data->levels[i - 1]->threshold, &data->levels[i - 1]->threshold, NULL);
223:     /* if there is no prescribed coarsening, just break out of the loop */
224:     if (data->levels[i - 1]->threshold <= 0.0 && data->levels[i - 1]->nu <= 0) break;
225:     else {
226:       ++i;
227:       PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_nev", i);
228:       PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg);
229:       if (!flg) {
230:         PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold", i);
231:         PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg);
232:       }
233:       if (flg) {
234:         /* if there are coarsening options for the next level, then register it  */
235:         /* otherwise, don't to avoid having both options levels_N_p and coarse_p */
236:         PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_p", i);
237:         PetscOptionsRangeInt(prefix, "Number of processes used to assemble the coarse operator at this level", "none", p, &p, &flg, 1, PetscMax(1, previous / 2));
238:         previous = p;
239:       }
240:     }
241:   }
242:   data->N = i;
243:   n = 1;
244:   if (i > 1) {
245:     PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_coarse_p");
246:     PetscOptionsRangeInt(prefix, "Number of processes used to assemble the coarsest operator", "none", n, &n, NULL, 1, PetscMax(1, previous / 2));
247:     PetscOptionsEList("-pc_hpddm_coarse_correction", "Type of coarse correction applied each iteration", "PCHPDDMSetCoarseCorrectionType", PCHPDDMCoarseCorrectionTypes, 3, PCHPDDMCoarseCorrectionTypes[PC_HPDDM_COARSE_CORRECTION_DEFLATED], &n, &flg);
248:     if (flg) data->correction = PCHPDDMCoarseCorrectionType(n);
249:     PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_has_neumann");
250:     PetscOptionsBool(prefix, "Is the auxiliary Mat the local Neumann matrix?", "PCHPDDMHasNeumannMat", data->Neumann, &data->Neumann, NULL);
251:   }
252:   PetscOptionsTail();
253:   while (i < PETSC_HPDDM_MAXLEVELS && data->levels[i]) {
254:     PetscFree(data->levels[i++]);
255:   }
256:   return(0);
257: }

259: static PetscErrorCode PCApply_HPDDM(PC pc, Vec x, Vec y)
260: {
261:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

265:   PetscCitationsRegister(hpddmCitationPC, &citePC);
266:   if (data->levels[0]->ksp) {
267:     KSPSolve(data->levels[0]->ksp, x, y);
268:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "No KSP attached to PCHPDDM");
269:   return(0);
270: }

272: static PetscErrorCode PCMatApply_HPDDM(PC pc, Mat X, Mat Y)
273: {
274:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

278:   PetscCitationsRegister(hpddmCitationPC, &citePC);
279:   if (data->levels[0]->ksp) {
280:     KSPMatSolve(data->levels[0]->ksp, X, Y);
281:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "No KSP attached to PCHPDDM");
282:   return(0);
283: }

285: /*@C
286:      PCHPDDMGetComplexities - Computes the grid and operator complexities.

288:    Input Parameter:
289: .     pc - preconditioner context

291:    Output Parameters:
292: +     gc - grid complexity = sum_i(m_i) / m_1
293: -     oc - operator complexity = sum_i(nnz_i) / nnz_1

295:    Notes:
296:      PCGAMG does not follow the usual convention and names the grid complexity what is usually referred to as the operator complexity. PCHPDDM follows what is found in the literature, and in particular, what you get with PCHYPRE and -pc_hypre_boomeramg_print_statistics.

298:    Level: advanced

300: .seealso:  PCMGGetGridComplexity(), PCHPDDM
301: @*/
302: static PetscErrorCode PCHPDDMGetComplexities(PC pc, PetscReal *gc, PetscReal *oc)
303: {
304:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;
305:   MatInfo        info;
306:   PetscInt       n, m;
307:   PetscLogDouble accumulate[2] { }, nnz1 = 1.0, m1 = 1.0;

311:   for (n = 0, *gc = 0, *oc = 0; n < data->N; ++n) {
312:     if (data->levels[n]->ksp) {
313:       Mat P;
314:       KSPGetOperators(data->levels[n]->ksp, NULL, &P);
315:       MatGetSize(P, &m, NULL);
316:       accumulate[0] += m;
317:       MatGetInfo(P, MAT_GLOBAL_SUM, &info);
318:       accumulate[1] += info.nz_used;
319:       if (n == 0) {
320:         m1 = m;
321:         nnz1 = info.nz_used;
322:       }
323:     }
324:   }
325:   *gc = static_cast<PetscReal>(accumulate[0]/m1);
326:   *oc = static_cast<PetscReal>(accumulate[1]/nnz1);
327:   return(0);
328: }

330: static PetscErrorCode PCView_HPDDM(PC pc, PetscViewer viewer)
331: {
332:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;
333:   PetscViewer    subviewer;
334:   PetscSubcomm   subcomm;
335:   PetscReal      oc, gc;
336:   PetscInt       i, tabs;
337:   PetscMPIInt    size, color, rank;
338:   PetscBool      ascii;

342:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &ascii);
343:   if (ascii) {
344:     PetscViewerASCIIPrintf(viewer, "level%s: %D\n", data->N > 1 ? "s" : "", data->N);
345:     PCHPDDMGetComplexities(pc, &gc, &oc);
346:     if (data->N > 1) {
347:       PetscViewerASCIIPrintf(viewer, "Neumann matrix attached? %s\n", PetscBools[data->Neumann]);
348:       PetscViewerASCIIPrintf(viewer, "coarse correction: %s\n", PCHPDDMCoarseCorrectionTypes[data->correction]);
349:       PetscViewerASCIIPrintf(viewer, "on process #0, value%s (+ threshold%s if available) for selecting deflation vectors:", data->N > 2 ? "s" : "", data->N > 2 ? "s" : "");
350:       PetscViewerASCIIGetTab(viewer, &tabs);
351:       PetscViewerASCIISetTab(viewer, 0);
352:       for (i = 1; i < data->N; ++i) {
353:         PetscViewerASCIIPrintf(viewer, " %D", data->levels[i - 1]->nu);
354:         if (data->levels[i - 1]->threshold > -0.1) {
355:           PetscViewerASCIIPrintf(viewer, " (%g)", (double)data->levels[i - 1]->threshold);
356:         }
357:       }
358:       PetscViewerASCIIPrintf(viewer, "\n");
359:       PetscViewerASCIISetTab(viewer, tabs);
360:     }
361:     PetscViewerASCIIPrintf(viewer, "grid and operator complexities: %g %g\n", (double)gc, (double)oc);
362:     if (data->levels[0]->ksp) {
363:       KSPView(data->levels[0]->ksp, viewer);
364:       if (data->levels[0]->pc) {
365:         PCView(data->levels[0]->pc, viewer);
366:       }
367:       for (i = 1; i < data->N; ++i) {
368:         if (data->levels[i]->ksp) color = 1;
369:         else color = 0;
370:         MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size);
371:         MPI_Comm_size(PetscObjectComm((PetscObject)pc), &rank);
372:         PetscSubcommCreate(PetscObjectComm((PetscObject)pc), &subcomm);
373:         PetscSubcommSetNumber(subcomm, PetscMin(size, 2));
374:         PetscSubcommSetTypeGeneral(subcomm, color, rank);
375:         PetscViewerASCIIPushTab(viewer);
376:         PetscViewerGetSubViewer(viewer, PetscSubcommChild(subcomm), &subviewer);
377:         if (color == 1) {
378:           KSPView(data->levels[i]->ksp, subviewer);
379:           if (data->levels[i]->pc) {
380:             PCView(data->levels[i]->pc, subviewer);
381:           }
382:           PetscViewerFlush(subviewer);
383:         }
384:         PetscViewerRestoreSubViewer(viewer, PetscSubcommChild(subcomm), &subviewer);
385:         PetscViewerASCIIPopTab(viewer);
386:         PetscSubcommDestroy(&subcomm);
387:         PetscViewerFlush(viewer);
388:       }
389:     }
390:   }
391:   return(0);
392: }

394: static PetscErrorCode PCHPDDMShellSetUp(PC pc)
395: {
396:   PC_HPDDM_Level *ctx;
397:   Mat            A, P;
398:   Vec            x;
399:   const char     *pcpre;

403:   PCShellGetContext(pc, (void**)&ctx);
404:   KSPGetOptionsPrefix(ctx->ksp, &pcpre);
405:   KSPGetOperators(ctx->ksp, &A, &P);
406:   /* smoother */
407:   PCSetOptionsPrefix(ctx->pc, pcpre);
408:   PCSetOperators(ctx->pc, A, P);
409:   if (!ctx->v[0]) {
410:     VecDuplicateVecs(ctx->D, 1, &ctx->v[0]);
411:     if (!std::is_same<PetscScalar, PetscReal>::value) {
412:       VecDestroy(&ctx->D);
413:     }
414:     MatCreateVecs(A, &x, NULL);
415:     VecDuplicateVecs(x, 2, &ctx->v[1]);
416:     VecDestroy(&x);
417:   }
418:   return(0);
419: }

421: template<class Type, typename std::enable_if<std::is_same<Type, Vec>::value>::type* = nullptr>
422: PETSC_STATIC_INLINE PetscErrorCode PCHPDDMDeflate_Private(PC pc, Type x, Type y)
423: {
424:   PC_HPDDM_Level *ctx;
425:   PetscScalar    *out;

429:   PCShellGetContext(pc, (void**)&ctx);
430:   /* going from PETSc to HPDDM numbering */
431:   VecScatterBegin(ctx->scatter, x, ctx->v[0][0], INSERT_VALUES, SCATTER_FORWARD);
432:   VecScatterEnd(ctx->scatter, x, ctx->v[0][0], INSERT_VALUES, SCATTER_FORWARD);
433:   VecGetArray(ctx->v[0][0], &out);
434:   ctx->P->deflation<false>(NULL, out, 1); /* y = Q x */
435:   VecRestoreArray(ctx->v[0][0], &out);
436:   /* going from HPDDM to PETSc numbering */
437:   VecScatterBegin(ctx->scatter, ctx->v[0][0], y, INSERT_VALUES, SCATTER_REVERSE);
438:   VecScatterEnd(ctx->scatter, ctx->v[0][0], y, INSERT_VALUES, SCATTER_REVERSE);
439:   return(0);
440: }

442: template<class Type, typename std::enable_if<std::is_same<Type, Mat>::value>::type* = nullptr>
443: PETSC_STATIC_INLINE PetscErrorCode PCHPDDMDeflate_Private(PC pc, Type X, Type Y)
444: {
445:   PC_HPDDM_Level *ctx;
446:   Vec            vX, vY, vC;
447:   PetscScalar    *out;
448:   PetscInt       i, m, N, prev = 0;

452:   PCShellGetContext(pc, (void**)&ctx);
453:   VecGetLocalSize(ctx->v[0][0], &m);
454:   MatGetSize(X, NULL, &N);
455:   if (ctx->V) {
456:     MatGetSize(ctx->V, NULL, &prev);
457:   }
458:   if (N != prev) {
459:     MatDestroy(&ctx->V);
460:     MatCreateDense(PetscObjectComm((PetscObject)pc), m, PETSC_DECIDE, PETSC_DECIDE, N, NULL, &ctx->V);
461:   }
462:   /* going from PETSc to HPDDM numbering */
463:   for (i = 0; i < N; ++i) {
464:     MatDenseGetColumnVecRead(X, i, &vX);
465:     MatDenseGetColumnVecWrite(ctx->V, i, &vC);
466:     VecScatterBegin(ctx->scatter, vX, vC, INSERT_VALUES, SCATTER_FORWARD);
467:     VecScatterEnd(ctx->scatter, vX, vC, INSERT_VALUES, SCATTER_FORWARD);
468:     MatDenseRestoreColumnVecWrite(ctx->V, i, &vC);
469:     MatDenseRestoreColumnVecRead(X, i, &vX);
470:   }
471:   MatDenseGetArrayWrite(ctx->V, &out);
472:   if (N != prev) {
473:     ctx->P->start(N);
474:     prev = N;
475:   }
476:   ctx->P->deflation<false>(NULL, out, N); /* Y = Q X */
477:   MatDenseRestoreArrayWrite(ctx->V, &out);
478:   /* going from HPDDM to PETSc numbering */
479:   for (i = 0; i < N; ++i) {
480:     MatDenseGetColumnVecRead(ctx->V, i, &vC);
481:     MatDenseGetColumnVecWrite(Y, i, &vY);
482:     VecScatterBegin(ctx->scatter, vC, vY, INSERT_VALUES, SCATTER_REVERSE);
483:     VecScatterEnd(ctx->scatter, vC, vY, INSERT_VALUES, SCATTER_REVERSE);
484:     MatDenseRestoreColumnVecWrite(Y, i, &vY);
485:     MatDenseRestoreColumnVecRead(ctx->V, i, &vC);
486:   }
487:   return(0);
488: }

490: /*@C
491:      PCHPDDMShellApply - Applies a (2) deflated, (1) additive, or (3) balanced coarse correction. In what follows, E = Z Pmat Z^T and Q = Z^T E^-1 Z.

493: .vb
494:    (1) y =                Pmat^-1              x + Q x,
495:    (2) y =                Pmat^-1 (I - Amat Q) x + Q x (default),
496:    (3) y = (I - Q Amat^T) Pmat^-1 (I - Amat Q) x + Q x.
497: .ve

499:    Input Parameters:
500: +     pc - preconditioner context
501: -     x - input vector

503:    Output Parameter:
504: .     y - output vector

506:    Application Interface Routine: PCApply()

508:    Notes:
509:      The options of Pmat^1 = pc(Pmat) are prefixed by -pc_hpddm_levels_1_pc_. Z is a tall-and-skiny matrix assembled by HPDDM. The number of processes on which (Z Pmat Z^T) is aggregated is set via -pc_hpddm_coarse_p.
510:      The options of (Z Pmat Z^T)^-1 = ksp(Z Pmat Z^T) are prefixed by -pc_hpddm_coarse_ (KSPPREONLY and PCCHOLESKY by default), unless a multilevel correction is turned on, in which case, this function is called recursively at each level except the coarsest one.
511:      (1) and (2) visit the "next" level (in terms of coarsening) once per application, while (3) visits it twice, so it is asymptotically twice costlier. (2) is not symmetric even if both Amat and Pmat are symmetric.

513:    Level: advanced

515: .seealso:  PCHPDDM, PCHPDDMCoarseCorrectionType
516: @*/
517: static PetscErrorCode PCHPDDMShellApply(PC pc, Vec x, Vec y)
518: {
519:   PC_HPDDM_Level *ctx;
520:   Mat            A;

524:   PCShellGetContext(pc, (void**)&ctx);
525:   if (ctx->P) {
526:     KSPGetOperators(ctx->ksp, &A, NULL);
527:     PCHPDDMDeflate_Private(pc, x, y);                    /* y = Q x                          */
528:     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
529:       MatMult(A, y, ctx->v[1][0]);                       /* y = A Q x                        */
530:       VecWAXPY(ctx->v[1][1], -1.0, ctx->v[1][0], x);     /* y = (I - A Q) x                  */
531:       PCApply(ctx->pc, ctx->v[1][1], ctx->v[1][0]);      /* y = M^-1 (I - A Q) x             */
532:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
533:         MatMultTranspose(A, ctx->v[1][0], ctx->v[1][1]); /* z = A^T M^-1 (I - A Q) x         */
534:         PCHPDDMDeflate_Private(pc, ctx->v[1][1], ctx->v[1][1]);
535:         VecAXPY(ctx->v[1][0], -1.0, ctx->v[1][1]);       /* y = (I - Q A^T) M^-1 (I - A Q) x */
536:       }
537:       VecAXPY(y, 1.0, ctx->v[1][0]);                     /* y = y + Q x                      */
538:     } else if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE) {
539:       PCApply(ctx->pc, x, ctx->v[1][0]);
540:       VecAXPY(y, 1.0, ctx->v[1][0]);                     /* y = M^-1 x + Q x                 */
541:     } else SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
542:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
543:   return(0);
544: }

546: /*@C
547:      PCHPDDMShellMatApply - Variant of PCHPDDMShellApply() for blocks of vectors

549:    Input Parameters:
550: +     pc - preconditioner context
551: -     X - block of input vectors

553:    Output Parameter:
554: .     Y - block of output vectors

556:    Application Interface Routine: PCApply()

558:    Level: advanced

560: .seealso:  PCHPDDM, PCHPDDMShellMatApply(), PCHPDDMCoarseCorrectionType
561: @*/
562: static PetscErrorCode PCHPDDMShellMatApply(PC pc, Mat X, Mat Y)
563: {
564:   PC_HPDDM_Level *ctx;
565:   Mat            A, C, D;

569:   PCShellGetContext(pc, (void**)&ctx);
570:   if (ctx->P) {
571:     KSPGetOperators(ctx->ksp, &A, NULL);
572:     PCHPDDMDeflate_Private(pc, X, Y);
573:     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
574:       MatMatMult(A, Y, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &C);
575:       MatDuplicate(C, MAT_COPY_VALUES, &D);
576:       MatAYPX(D, -1.0, X, SAME_NONZERO_PATTERN);
577:       PCMatApply(ctx->pc, D, C);
578:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
579: #if 0 // TODO FIXME: there is a bug in MatTransposeMatMult(): results are inconsitent with a column-by-column product
580:         MatTransposeMatMult(A, C, MAT_REUSE_MATRIX, PETSC_DEFAULT, &D);
581: #else
582:         PetscInt N;
583:         MatGetSize(D, NULL, &N);
584:         for (PetscInt i = 0; i < N; ++i) {
585:           Vec cD, cC;
586:           MatDenseGetColumnVecRead(C, i, &cC);
587:           MatDenseGetColumnVecWrite(D, i, &cD);
588:           MatMultTranspose(A, cC, cD);
589:           MatDenseRestoreColumnVecWrite(D, i, &cD);
590:           MatDenseRestoreColumnVecRead(C, i, &cC);
591:         }
592: #endif
593:       }
594:       MatAXPY(Y, 1.0, C, SAME_NONZERO_PATTERN);
595:       MatDestroy(&D);
596:     } else if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE) {
597:       MatDuplicate(X, MAT_DO_NOT_COPY_VALUES, &C);
598:       PCMatApply(ctx->pc, X, C);
599:       MatAXPY(Y, 1.0, C, SAME_NONZERO_PATTERN);
600:     } else SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
601:     MatDestroy(&C);
602:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
603:   return(0);
604: }

606: static PetscErrorCode PCHPDDMShellDestroy(PC pc)
607: {
608:   PC_HPDDM_Level *ctx;

612:   PCShellGetContext(pc, (void**)&ctx);
613:   HPDDM::Schwarz<PetscScalar>::destroy(ctx, PETSC_TRUE);
614:   VecDestroyVecs(1, &ctx->v[0]);
615:   VecDestroyVecs(2, &ctx->v[1]);
616:   MatDestroy(&ctx->V);
617:   VecDestroy(&ctx->D);
618:   VecScatterDestroy(&ctx->scatter);
619:   PCDestroy(&ctx->pc);
620:   return(0);
621: }

623: static PetscErrorCode PCHPDDMSetUpNeumannOverlap_Private(PC pc)
624: {
625:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

629:   if (data->setup) {
630:     Mat       P;
631:     Vec       x, xt = NULL;
632:     PetscReal t = 0.0, s = 0.0;

634:     PCGetOperators(pc, NULL, &P);
635:     PetscObjectQuery((PetscObject)P, "__SNES_latest_X", (PetscObject*)&x);
636:     PetscStackPush("PCHPDDM Neumann callback");
637:     (*data->setup)(data->aux, t, x, xt, s, data->is, data->setup_ctx);
638:     PetscStackPop;
639:   }
640:   return(0);
641: }

643: static PetscErrorCode PCSetUp_HPDDM(PC pc)
644: {
645:   PC_HPDDM                 *data = (PC_HPDDM*)pc->data;
646:   PC                       inner;
647:   Mat                      *sub, A, P, N, C, uaux = NULL;
648:   Vec                      xin, v;
649:   std::vector<Vec>         initial;
650:   IS                       is[1], loc, uis = data->is;
651:   ISLocalToGlobalMapping   l2g;
652:   char                     prefix[256];
653:   const char               *pcpre;
654:   const PetscScalar *const *ev;
655:   PetscInt                 n, requested = data->N, reused = 0;
656:   PetscBool                subdomains = PETSC_FALSE, flag = PETSC_FALSE, ismatis;
657:   DM                       dm;
658:   PetscErrorCode           ierr;

661:   if (!data->levels[0]) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not a single level allocated");
662:   PCGetOptionsPrefix(pc, &pcpre);
663:   PCGetOperators(pc, &A, &P);
664:   if (!data->levels[0]->ksp) {
665:     KSPCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->ksp);
666:     PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_%s_", pcpre ? pcpre : "", data->N > 1 ? "levels_1" : "coarse");
667:     KSPSetOptionsPrefix(data->levels[0]->ksp, prefix);
668:     KSPSetType(data->levels[0]->ksp, KSPPREONLY);
669:   } else if(data->levels[0]->ksp->pc && data->levels[0]->ksp->pc->setupcalled == 1 && data->levels[0]->ksp->pc->reusepreconditioner) {
670:     /* if the fine level PCSHELL exists, its setup has succeeded, and one wants to reuse it, */
671:     /* then just propagate the appropriate flag to the coarser levels                        */
672:     for (n = 0; n < PETSC_HPDDM_MAXLEVELS && data->levels[n]; ++n) {
673:       /* the following KSP and PC may be NULL for some processes, hence the check            */
674:       if (data->levels[n]->ksp) {
675:         KSPSetReusePreconditioner(data->levels[n]->ksp, PETSC_TRUE);
676:       }
677:       if (data->levels[n]->pc) {
678:         PCSetReusePreconditioner(data->levels[n]->pc, PETSC_TRUE);
679:       }
680:     }
681:     /* early bail out because there is nothing to do */
682:     return(0);
683:   } else {
684:     /* reset coarser levels */
685:     for (n = 1; n < PETSC_HPDDM_MAXLEVELS && data->levels[n]; ++n) {
686:       if(data->levels[n]->ksp && data->levels[n]->ksp->pc && data->levels[n]->ksp->pc->setupcalled == 1 && data->levels[n]->ksp->pc->reusepreconditioner && n < data->N) {
687:         reused = data->N - n;
688:         break;
689:       }
690:       KSPDestroy(&data->levels[n]->ksp);
691:       PCDestroy(&data->levels[n]->pc);
692:     }
693:     /* check if some coarser levels are being reused */
694:     MPI_Allreduce(MPI_IN_PLACE, &reused, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)pc));
695:     const int *addr = data->levels[0]->P ? data->levels[0]->P->getAddrLocal() : &HPDDM::i__0;

697:     if (addr != &HPDDM::i__0 && reused != data->N - 1) {
698:       /* reuse previously computed eigenvectors */
699:       ev = data->levels[0]->P->getVectors();
700:       if (ev) {
701:         initial.reserve(*addr);
702:         VecCreateSeqWithArray(PETSC_COMM_SELF, 1, data->levels[0]->P->getDof(), ev[0], &xin);
703:         for (n = 0; n < *addr; ++n) {
704:           VecDuplicate(xin, &v);
705:           VecPlaceArray(xin, ev[n]);
706:           VecCopy(xin, v);
707:           initial.emplace_back(v);
708:           VecResetArray(xin);
709:         }
710:         VecDestroy(&xin);
711:       }
712:     }
713:   }
714:   data->N -= reused;
715:   KSPSetOperators(data->levels[0]->ksp, A, P);

717:   PetscObjectTypeCompare((PetscObject)P, MATIS, &ismatis);
718:   if (!data->is && !ismatis) {
719:     PetscErrorCode (*create)(DM, IS*, Mat*, PetscErrorCode (**)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void*), void**) = NULL;
720:     PetscErrorCode (*usetup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void*) = NULL;
721:     void           *uctx = NULL;

723:     /* first see if we can get the data from the DM */
724:     MatGetDM(P, &dm);
725:     if (!dm) {
726:       MatGetDM(A, &dm);
727:     }
728:     if (!dm) {
729:       PCGetDM(pc, &dm);
730:     }
731:     if (dm) { /* this is the hook for DMPLEX and DMDA for which the auxiliary Mat is the local Neumann matrix */
732:       PetscObjectQueryFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", &create);
733:       if (create) {
734:         (*create)(dm, &uis, &uaux, &usetup, &uctx);
735:         data->Neumann = PETSC_TRUE;
736:       }
737:     }
738:     if (!create) {
739:       if (!uis) {
740:         PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Neumann_IS", (PetscObject*)&uis);
741:         PetscObjectReference((PetscObject)uis);
742:       }
743:       if (!uaux) {
744:         PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Neumann_Mat", (PetscObject*)&uaux);
745:         PetscObjectReference((PetscObject)uaux);
746:       }
747:     }
748:     PCHPDDMSetAuxiliaryMat(pc, uis, uaux, usetup, uctx);
749:     MatDestroy(&uaux);
750:     ISDestroy(&uis);
751:   }

753:   if (!ismatis) {
754:     PCHPDDMSetUpNeumannOverlap_Private(pc);
755:   }

757:   if (data->is || (ismatis && data->N > 1)) {
758:     if (ismatis) {
759:       std::initializer_list<std::string> list = { MATSEQBAIJ, MATSEQSBAIJ };
760:       MatISGetLocalMat(P, &N);
761:       std::initializer_list<std::string>::const_iterator it = std::find(list.begin(), list.end(), ((PetscObject)N)->type_name);
762:       MatISRestoreLocalMat(P, &N);
763:       switch (std::distance(list.begin(), it)) {
764:       case 0:
765:         MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &C);
766:         break;
767:       case 1:
768:         /* MatCreateSubMatrices does not work with MATSBAIJ and unsorted ISes, so convert to MPIBAIJ */
769:         MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &C);
770:         MatSetOption(C, MAT_SYMMETRIC, PETSC_TRUE);
771:         break;
772:       default:
773:         MatConvert(P, MATMPIAIJ, MAT_INITIAL_MATRIX, &C);
774:       }
775:       MatGetLocalToGlobalMapping(P, &l2g, NULL);
776:       PetscObjectReference((PetscObject)P);
777:       KSPSetOperators(data->levels[0]->ksp, A, C);
778:       std::swap(C, P);
779:       ISLocalToGlobalMappingGetSize(l2g, &n);
780:       ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &loc);
781:       ISLocalToGlobalMappingApplyIS(l2g, loc, &is[0]);
782:       ISDestroy(&loc);
783:       /* the auxiliary Mat is _not_ the local Neumann matrix                                */
784:       /* it is the local Neumann matrix augmented (with zeros) through MatIncreaseOverlap() */
785:       data->Neumann = PETSC_FALSE;
786:     } else {
787:       is[0] = data->is;
788:       PetscOptionsGetBool(NULL, pcpre, "-pc_hpddm_define_subdomains", &subdomains, NULL);
789:       PetscOptionsGetBool(NULL, pcpre, "-pc_hpddm_has_neumann", &data->Neumann, NULL);
790:       ISCreateStride(PetscObjectComm((PetscObject)data->is), P->rmap->n, P->rmap->rstart, 1, &loc);
791:     }
792:     if (data->N > 1 && (data->aux || ismatis)) {
793:       if (!loadedSym) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "HPDDM library not loaded, cannot use more than one level");
794:       MatSetOption(P, MAT_SUBMAT_SINGLEIS, PETSC_TRUE);
795:       if (ismatis) {
796:         /* needed by HPDDM (currently) so that the partition of unity is 0 on subdomain interfaces */
797:         MatIncreaseOverlap(P, 1, is, 1);
798:         ISDestroy(&data->is);
799:         data->is = is[0];
800:       } else {
801:         if (PetscDefined(USE_DEBUG)) {
802:           PetscBool equal;
803:           IS        intersect;

805:           ISIntersect(data->is, loc, &intersect);
806:           ISEqualUnsorted(loc, intersect, &equal);
807:           ISDestroy(&intersect);
808:           if (!equal) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "IS of the auxiliary Mat does not include all local rows of A");
809:         }
810:         if (!data->Neumann) {
811:           PetscObjectTypeCompare((PetscObject)P, MATMPISBAIJ, &flag);
812:           if (flag) {
813:             /* maybe better to ISSort(is[0]), MatCreateSubMatrices, and then MatPermute */
814:             /* but there is no MatPermute_SeqSBAIJ, so as before, just use MATMPIBAIJ   */
815:             MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &uaux);
816:             flag = PETSC_FALSE;
817:           }
818:         }
819:       }
820:       if (!uaux) {
821:         if (data->Neumann) sub = &data->aux;
822:         else {
823:           MatCreateSubMatrices(P, 1, is, is, MAT_INITIAL_MATRIX, &sub);
824:         }
825:       } else {
826:         MatCreateSubMatrices(uaux, 1, is, is, MAT_INITIAL_MATRIX, &sub);
827:         MatDestroy(&uaux);
828:         MatConvert(sub[0], MATSEQSBAIJ, MAT_INPLACE_MATRIX, sub);
829:       }
830:       /* Vec holding the partition of unity */
831:       if (!data->levels[0]->D) {
832:         ISGetLocalSize(data->is, &n);
833:         VecCreateMPI(PETSC_COMM_SELF, n, PETSC_DETERMINE, &data->levels[0]->D);
834:       }
835:       if (!data->levels[0]->scatter) {
836:         MatCreateVecs(P, &xin, NULL);
837:         if (ismatis) {
838:           MatDestroy(&P);
839:         }
840:         VecScatterCreate(xin, data->is, data->levels[0]->D, NULL, &data->levels[0]->scatter);
841:         VecDestroy(&xin);
842:       }
843:       if (data->levels[0]->P) {
844:         /* if the pattern is the same and PCSetUp has previously succeeded, reuse HPDDM buffers and connectivity */
845:         HPDDM::Schwarz<PetscScalar>::destroy(data->levels[0], pc->setupcalled < 1 || pc->flag == DIFFERENT_NONZERO_PATTERN ? PETSC_TRUE : PETSC_FALSE);
846:       }
847:       if (!data->levels[0]->P) data->levels[0]->P = new HPDDM::Schwarz<PetscScalar>();
848:       (*loadedSym)(data->levels[0]->P, loc, data->is, sub[0], ismatis ? C : data->aux, initial, &data->N, data->levels);
849:       if (!data->Neumann)
850:         MatDestroySubMatrices(1, &sub);
851:       if (ismatis) data->is = NULL;
852:       for (n = 0; n < data->N - 1 + (reused > 0); ++n) {
853:         if (data->levels[n]->P) {
854:           PC spc;

856:           /* force the PC to be PCSHELL to do the coarse grid corrections */
857:           KSPSetSkipPCSetFromOptions(data->levels[n]->ksp, PETSC_TRUE);
858:           KSPGetPC(data->levels[n]->ksp, &spc);
859:           PCSetType(spc, PCSHELL);
860:           PCShellSetContext(spc, data->levels[n]);
861:           PCShellSetSetUp(spc, PCHPDDMShellSetUp);
862:           PCShellSetApply(spc, PCHPDDMShellApply);
863:           PCShellSetMatApply(spc, PCHPDDMShellMatApply);
864:           PCShellSetDestroy(spc, PCHPDDMShellDestroy);
865:           if (!data->levels[n]->pc) {
866:             PCCreate(PetscObjectComm((PetscObject)data->levels[n]->ksp), &data->levels[n]->pc);
867:           }
868:           if (n < reused) {
869:             PCSetReusePreconditioner(spc, PETSC_TRUE);
870:             PCSetReusePreconditioner(data->levels[n]->pc, PETSC_TRUE);
871:           }
872:           PCSetUp(spc);
873:         }
874:       }
875:     } else flag = reused ? PETSC_FALSE : PETSC_TRUE;
876:     if (!ismatis && subdomains) {
877:       if (flag) {
878:         KSPGetPC(data->levels[0]->ksp, &inner);
879:       } else inner = data->levels[0]->pc;
880:       if (inner) {
881:         PCSetType(inner, PCASM);
882:         if (!inner->setupcalled) {
883:           PCASMSetLocalSubdomains(inner, 1, is, &loc);
884:         }
885:       }
886:     }
887:     ISDestroy(&loc);
888:   } else data->N = 1 + reused; /* enforce this value to 1 + reused if there is no way to build another level */
889:   if (requested != data->N + reused) {
890:     PetscInfo5(pc, "%D levels requested, only %D built + %D reused. Options for level(s) > %D, including -%spc_hpddm_coarse_ will not be taken into account\n", requested, data->N, reused, data->N, pcpre ? pcpre : "");
891:     PetscInfo2(pc, "It is best to tune parameters, e.g., a higher value for -%spc_hpddm_levels_%D_eps_threshold so that at least one local deflation vector will be selected\n", pcpre ? pcpre : "", data->N);
892:     /* cannot use PCHPDDMShellDestroy because PCSHELL not set for unassembled levels */
893:     for (n = data->N - 1; n < requested - 1; ++n) {
894:       if (data->levels[n]->P) {
895:         HPDDM::Schwarz<PetscScalar>::destroy(data->levels[n], PETSC_TRUE);
896:         VecDestroyVecs(1, &data->levels[n]->v[0]);
897:         VecDestroyVecs(2, &data->levels[n]->v[1]);
898:         MatDestroy(&data->levels[n]->V);
899:         VecDestroy(&data->levels[n]->D);
900:         VecScatterDestroy(&data->levels[n]->scatter);
901:       }
902:     }
903:     if (reused) {
904:       for (n = reused; n < PETSC_HPDDM_MAXLEVELS && data->levels[n]; ++n) {
905:         KSPDestroy(&data->levels[n]->ksp);
906:         PCDestroy(&data->levels[n]->pc);
907:       }
908:     }
909:     if (PetscDefined(USE_DEBUG)) SETERRQ7(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "%D levels requested, only %D built + %D reused. Options for level(s) > %D, including -%spc_hpddm_coarse_ will not be taken into account. It is best to tune parameters, e.g., a higher value for -%spc_hpddm_levels_%D_eps_threshold so that at least one local deflation vector will be selected. If you don't want this to error out, compile --with-debugging=0", requested, data->N, reused, data->N, pcpre ? pcpre : "", pcpre ? pcpre : "", data->N);
910:   }

912:   /* these solvers are created after PCSetFromOptions is called */
913:   if (pc->setfromoptionscalled) {
914:     for (n = 0; n < data->N; ++n) {
915:       if (data->levels[n]->ksp) {
916:         KSPSetFromOptions(data->levels[n]->ksp);
917:       }
918:       if (data->levels[n]->pc) {
919:         PCSetFromOptions(data->levels[n]->pc);
920:       }
921:     }
922:     pc->setfromoptionscalled = 0;
923:   }
924:   data->N += reused;
925:   return(0);
926: }

928: /*@
929:      PCHPDDMSetCoarseCorrectionType - Sets the coarse correction type.

931:    Input Parameters:
932: +     pc - preconditioner context
933: -     type - PC_HPDDM_COARSE_CORRECTION_DEFLATED, PC_HPDDM_COARSE_CORRECTION_ADDITIVE, or PC_HPDDM_COARSE_CORRECTION_BALANCED

935:    Options Database Key:
936: .   -pc_hpddm_coarse_correction <deflated, additive, balanced> - type of coarse correction to apply

938:    Level: intermediate

940: .seealso:  PCHPDDMGetCoarseCorrectionType(), PCHPDDM, PCHPDDMCoarseCorrectionType
941: @*/
942: PetscErrorCode PCHPDDMSetCoarseCorrectionType(PC pc, PCHPDDMCoarseCorrectionType type)
943: {

948:   PetscTryMethod(pc, "PCHPDDMSetCoarseCorrectionType_C", (PC, PCHPDDMCoarseCorrectionType), (pc, type));
949:   return(0);
950: }

952: /*@
953:      PCHPDDMGetCoarseCorrectionType - Gets the coarse correction type.

955:    Input Parameter:
956: .     pc - preconditioner context

958:    Output Parameter:
959: .     type - PC_HPDDM_COARSE_CORRECTION_DEFLATED, PC_HPDDM_COARSE_CORRECTION_ADDITIVE, or PC_HPDDM_COARSE_CORRECTION_BALANCED

961:    Level: intermediate

963: .seealso:  PCHPDDMSetCoarseCorrectionType(), PCHPDDM, PCHPDDMCoarseCorrectionType
964: @*/
965: PetscErrorCode PCHPDDMGetCoarseCorrectionType(PC pc, PCHPDDMCoarseCorrectionType *type)
966: {

971:   PetscUseMethod(pc, "PCHPDDMGetCoarseCorrectionType_C", (PC, PCHPDDMCoarseCorrectionType*), (pc, type));
972:   return(0);
973: }

975: static PetscErrorCode PCHPDDMSetCoarseCorrectionType_HPDDM(PC pc, PCHPDDMCoarseCorrectionType type)
976: {
977:   PC_HPDDM       *data = (PC_HPDDM*)pc->data;

980:   if (type < 0 || type > 2) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown PCHPDDMCoarseCorrectionType %d", type);
981:   data->correction = type;
982:   return(0);
983: }

985: static PetscErrorCode PCHPDDMGetCoarseCorrectionType_HPDDM(PC pc, PCHPDDMCoarseCorrectionType *type)
986: {
987:   PC_HPDDM *data = (PC_HPDDM*)pc->data;

990:   *type = data->correction;
991:   return(0);
992: }

994: PetscErrorCode HPDDMLoadDL_Private(PetscBool *found) {
995:   char           lib[PETSC_MAX_PATH_LEN], dlib[PETSC_MAX_PATH_LEN], dir[PETSC_MAX_PATH_LEN];

999:   PetscStrcpy(dir, "${PETSC_LIB_DIR}");
1000:   PetscOptionsGetString(NULL, NULL, "-hpddm_dir", dir, sizeof(dir), NULL);
1001:   PetscSNPrintf(lib, sizeof(lib), "%s/libhpddm_petsc", dir);
1002:   PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found);
1003:   if (*found) {
1004:     PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, dlib);
1005: #if defined(SLEPC_LIB_DIR) /* this variable is passed during SLEPc ./configure since    */
1006:   } else {                 /* slepcconf.h is not yet build (and thus can't be included) */
1007:     PetscStrcpy(dir, HPDDM_STR(SLEPC_LIB_DIR));
1008:     PetscSNPrintf(lib, sizeof(lib), "%s/libhpddm_petsc", dir);
1009:     PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found);
1010:     if (*found) {
1011:       PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, dlib);
1012: #endif
1013:     } else SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "%s not found", lib);
1014: #if defined(SLEPC_LIB_DIR)
1015:   }
1016: #endif
1017:   return(0);
1018: }

1020: /*MC
1021:      PCHPDDM - Interface with the HPDDM library.

1023:    This PC may be used to build multilevel spectral domain decomposition methods based on the GenEO framework [2011, 2019]. It may be viewed as an alternative to spectral AMGe or PCBDDC with adaptive selection of constraints. A chronological bibliography of relevant publications linked with PC available in HPDDM through PCHPDDM may be found below.

1025:    The matrix to be preconditioned (Pmat) may be unassembled (MATIS) or assembled (MATMPIAIJ, MATMPIBAIJ, or MATMPISBAIJ). For multilevel preconditioning, when using an assembled Pmat, one must provide an auxiliary local Mat (unassembled local operator for GenEO) using PCHPDDMSetAuxiliaryMat. Calling this routine is not needed when using a MATIS Pmat (assembly done internally using MatConvert).

1027:    Options Database Keys:
1028: +   -pc_hpddm_define_subdomains <true, default=false> - on the finest level, calls PCASMSetLocalSubdomains with the IS supplied in PCHPDDMSetAuxiliaryMat (only relevant with an assembled Pmat)
1029: .   -pc_hpddm_has_neumann <true, default=false> - on the finest level, informs the PC that the local Neumann matrix is supplied in PCHPDDMSetAuxiliaryMat 
1030: -   -pc_hpddm_coarse_correction <type, default=deflated> - determines the PCHPDDMCoarseCorrectionType when calling PCApply

1032:    Options for subdomain solvers, subdomain eigensolvers (for computing deflation vectors), and the coarse solver can be set with
1033: .vb
1034:       -pc_hpddm_levels_%d_pc_
1035:       -pc_hpddm_levels_%d_ksp_
1036:       -pc_hpddm_levels_%d_eps_
1037:       -pc_hpddm_levels_%d_p
1038:       -pc_hpddm_levels_%d_mat_type_
1039:       -pc_hpddm_coarse_
1040:       -pc_hpddm_coarse_p
1041:       -pc_hpddm_coarse_mat_type_
1042: .ve
1043:    e.g., -pc_hpddm_levels_1_sub_pc_type lu -pc_hpddm_levels_1_eps_nev 10 -pc_hpddm_levels_2_p 4 -pc_hpddm_levels_2_sub_pc_type lu -pc_hpddm_levels_2_eps_nev 10 -pc_hpddm_coarse_p 2 -pc_hpddm_coarse_mat_type baij will use 10 deflation vectors per subdomain on the fine "level 1", aggregate the fine subdomains into 4 "level 2" subdomains, then use 10 deflation vectors per subdomain on "level 2", and assemble the coarse matrix (of dimension 4 x 10 = 40) on two processes as a MATMPIBAIJ (default is MATMPISBAIJ).

1045:    In order to activate a "level N+1" coarse correction, it is mandatory to call -pc_hpddm_levels_N_eps_nev <nu> or -pc_hpddm_levels_N_eps_threshold <val>. The default -pc_hpddm_coarse_p value is 1, meaning that the coarse operator is aggregated on a single process.

1047:    This preconditioner requires that you build PETSc with SLEPc (--download-slepc=1). By default, the underlying concurrent eigenproblems are solved using SLEPc shift-and-invert spectral transformation. This is usually what gives the best performance for GenEO, cf. [2011, 2013]. As stated above, SLEPc options are available through -pc_hpddm_levels_%d_, e.g., -pc_hpddm_levels_1_eps_type arpack -pc_hpddm_levels_1_eps_threshold 0.1 -pc_hpddm_levels_1_st_type sinvert.

1049:    References:
1050: +   2011 - A robust two-level domain decomposition preconditioner for systems of PDEs. Spillane, Dolean, Hauret, Nataf, Pechstein, and Scheichl. Comptes Rendus Mathematique.
1051: .   2013 - Scalable Domain Decomposition Preconditioners For Heterogeneous Elliptic Problems. Jolivet, Hecht, Nataf, and Prud'homme. SC13.
1052: .   2015 - An Introduction to Domain Decomposition Methods: Algorithms, Theory, and Parallel Implementation. Dolean, Jolivet, and Nataf. SIAM.
1053: -   2019 - A Multilevel Schwarz Preconditioner Based on a Hierarchy of Robust Coarse Spaces. Al Daas, Grigori, Jolivet, and Tournier.

1055:    Level: intermediate

1057: .seealso:  PCCreate(), PCSetType(), PCType (for list of available types), PC, PCHPDDMSetAuxiliaryMat(), MATIS, PCBDDC, PCDEFLATION, PCTELESCOPE
1058: M*/
1059: PETSC_EXTERN PetscErrorCode PCCreate_HPDDM(PC pc)
1060: {
1061:   PC_HPDDM       *data;
1062:   PetscBool      found;

1066:   if (!loadedSym) {
1067:     HPDDMLoadDL_Private(&found);
1068:     if (found) {
1069:       PetscDLLibrarySym(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, NULL, "PCHPDDM_Internal", (void**)&loadedSym);
1070:     }
1071:   }
1072:   if (!loadedSym) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCHPDDM_Internal symbol not found in loaded libhpddm_petsc");
1073:   PetscNewLog(pc, &data);
1074:   pc->data                     = data;
1075:   pc->ops->reset               = PCReset_HPDDM;
1076:   pc->ops->destroy             = PCDestroy_HPDDM;
1077:   pc->ops->setfromoptions      = PCSetFromOptions_HPDDM;
1078:   pc->ops->setup               = PCSetUp_HPDDM;
1079:   pc->ops->apply               = PCApply_HPDDM;
1080:   pc->ops->matapply            = PCMatApply_HPDDM;
1081:   pc->ops->view                = PCView_HPDDM;
1082:   pc->ops->applytranspose      = 0;
1083:   pc->ops->applysymmetricleft  = 0;
1084:   pc->ops->applysymmetricright = 0;
1085:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetAuxiliaryMat_C", PCHPDDMSetAuxiliaryMat_HPDDM);
1086:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMHasNeumannMat_C", PCHPDDMHasNeumannMat_HPDDM);
1087:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetRHSMat_C", PCHPDDMSetRHSMat_HPDDM);
1088:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetCoarseCorrectionType_C", PCHPDDMSetCoarseCorrectionType_HPDDM);
1089:   PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetCoarseCorrectionType_C", PCHPDDMGetCoarseCorrectionType_HPDDM);
1090:   return(0);
1091: }

1093: /*@C
1094:      PCHPDDMInitializePackage - This function initializes everything in the PCHPDDM package. It is called from PCInitializePackage().

1096:    Level: intermediate

1098: .seealso:  PetscInitialize()
1099: @*/
1100: PetscErrorCode PCHPDDMInitializePackage(void)
1101: {

1105:   if (PCHPDDMPackageInitialized) return(0);
1106:   PCHPDDMPackageInitialized = PETSC_TRUE;
1107:   PetscRegisterFinalize(PCHPDDMFinalizePackage);
1108:   /* general events registered once during package initialization */
1109:   /* these events are not triggered in libpetsc,                  */
1110:   /* but rather directly in libhpddm_petsc,                       */
1111:   /* which is in charge of performing the following operations    */

1113:   /* domain decomposition structure from Pmat sparsity pattern    */
1114:   PetscLogEventRegister("PCHPDDMStrc", PC_CLASSID, &PC_HPDDM_Strc);
1115:   /* Galerkin product, redistribution, and setup                  */
1116:   PetscLogEventRegister("PCHPDDMPtAP", PC_CLASSID, &PC_HPDDM_PtAP);
1117:   /* Galerkin product with summation, redistribution, and setup   */
1118:   PetscLogEventRegister("PCHPDDMPtBP", PC_CLASSID, &PC_HPDDM_PtBP);
1119:   /* next level construction using PtAP and PtBP                  */
1120:   PetscLogEventRegister("PCHPDDMNext", PC_CLASSID, &PC_HPDDM_Next);
1121:   return(0);
1122: }

1124: /*@C
1125:      PCHPDDMFinalizePackage - This function frees everything from the PCHPDDM package. It is called from PetscFinalize().

1127:    Level: intermediate

1129: .seealso:  PetscFinalize()
1130: @*/
1131: PetscErrorCode PCHPDDMFinalizePackage(void)
1132: {
1134:   PCHPDDMPackageInitialized = PETSC_FALSE;
1135:   return(0);
1136: }