xref: /petsc/src/ksp/pc/impls/hpddm/pchpddm.cxx (revision c30dab7b77f34b326fa9c99484936398f8983cf7)
101e3c840SPierre Jolivet #include <petscsf.h>
213044ca3SPierre Jolivet #include <petsc/private/vecimpl.h>
3f1580f4eSBarry Smith #include <petsc/private/matimpl.h>
4f1580f4eSBarry Smith #include <petsc/private/petschpddm.h> /*I "petscpc.h" I*/
5e905f78bSJacob Faibussowitsch #include <petsc/private/pcimpl.h>
6e905f78bSJacob Faibussowitsch #include <petsc/private/dmimpl.h> /* this must be included after petschpddm.h so that DM_MAX_WORK_VECTORS is not defined  */
7f1580f4eSBarry Smith                                   /* otherwise, it is assumed that one is compiling libhpddm_petsc => circular dependency */
8f1580f4eSBarry Smith 
9db4a47b3SPierre Jolivet static PetscErrorCode (*loadedSym)(HPDDM::Schwarz<PetscScalar> *const, IS, Mat, Mat, Mat, std::vector<Vec>, PC_HPDDM_Level **const) = nullptr;
10f1580f4eSBarry Smith 
11f1580f4eSBarry Smith static PetscBool PCHPDDMPackageInitialized = PETSC_FALSE;
12f1580f4eSBarry Smith 
13f1580f4eSBarry Smith PetscLogEvent PC_HPDDM_Strc;
14f1580f4eSBarry Smith PetscLogEvent PC_HPDDM_PtAP;
15f1580f4eSBarry Smith PetscLogEvent PC_HPDDM_PtBP;
16f1580f4eSBarry Smith PetscLogEvent PC_HPDDM_Next;
17f1580f4eSBarry Smith PetscLogEvent PC_HPDDM_SetUp[PETSC_PCHPDDM_MAXLEVELS];
18f1580f4eSBarry Smith PetscLogEvent PC_HPDDM_Solve[PETSC_PCHPDDM_MAXLEVELS];
19f1580f4eSBarry Smith 
20aa1539e9SPierre Jolivet const char *const PCHPDDMCoarseCorrectionTypes[] = {"DEFLATED", "ADDITIVE", "BALANCED", "NONE", "PCHPDDMCoarseCorrectionType", "PC_HPDDM_COARSE_CORRECTION_", nullptr};
2113044ca3SPierre Jolivet const char *const PCHPDDMSchurPreTypes[]         = {"LEAST_SQUARES", "GENEO", "PCHPDDMSchurPreType", "PC_HPDDM_SCHUR_PRE", nullptr};
22f1580f4eSBarry Smith 
23d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCReset_HPDDM(PC pc)
24d71ae5a4SJacob Faibussowitsch {
25f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
26f1580f4eSBarry Smith 
27f1580f4eSBarry Smith   PetscFunctionBegin;
28f1580f4eSBarry Smith   if (data->levels) {
29811e8887SPierre Jolivet     for (PetscInt i = 0; i < PETSC_PCHPDDM_MAXLEVELS && data->levels[i]; ++i) {
30f1580f4eSBarry Smith       PetscCall(KSPDestroy(&data->levels[i]->ksp));
31f1580f4eSBarry Smith       PetscCall(PCDestroy(&data->levels[i]->pc));
32f1580f4eSBarry Smith       PetscCall(PetscFree(data->levels[i]));
33f1580f4eSBarry Smith     }
34f1580f4eSBarry Smith     PetscCall(PetscFree(data->levels));
35f1580f4eSBarry Smith   }
36f1580f4eSBarry Smith   PetscCall(ISDestroy(&data->is));
37f1580f4eSBarry Smith   PetscCall(MatDestroy(&data->aux));
38f1580f4eSBarry Smith   PetscCall(MatDestroy(&data->B));
39f1580f4eSBarry Smith   PetscCall(VecDestroy(&data->normal));
40f1580f4eSBarry Smith   data->correction = PC_HPDDM_COARSE_CORRECTION_DEFLATED;
41c8ea6600SPierre Jolivet   data->Neumann    = PETSC_BOOL3_UNKNOWN;
42f1580f4eSBarry Smith   data->deflation  = PETSC_FALSE;
43db4a47b3SPierre Jolivet   data->setup      = nullptr;
44db4a47b3SPierre Jolivet   data->setup_ctx  = nullptr;
453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46f1580f4eSBarry Smith }
47f1580f4eSBarry Smith 
48d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCDestroy_HPDDM(PC pc)
49d71ae5a4SJacob Faibussowitsch {
50f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
51f1580f4eSBarry Smith 
52f1580f4eSBarry Smith   PetscFunctionBegin;
53f1580f4eSBarry Smith   PetscCall(PCReset_HPDDM(pc));
54f1580f4eSBarry Smith   PetscCall(PetscFree(data));
55db4a47b3SPierre Jolivet   PetscCall(PetscObjectChangeTypeName((PetscObject)pc, nullptr));
56db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetAuxiliaryMat_C", nullptr));
57db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMHasNeumannMat_C", nullptr));
58db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetRHSMat_C", nullptr));
59db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetCoarseCorrectionType_C", nullptr));
60db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetCoarseCorrectionType_C", nullptr));
61db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetSTShareSubKSP_C", nullptr));
62db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetSTShareSubKSP_C", nullptr));
63db4a47b3SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetDeflationMat_C", nullptr));
6413044ca3SPierre Jolivet   PetscCall(PetscObjectCompose((PetscObject)pc, "_PCHPDDM_Schur", nullptr));
653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
66f1580f4eSBarry Smith }
67f1580f4eSBarry Smith 
68d71ae5a4SJacob Faibussowitsch static inline PetscErrorCode PCHPDDMSetAuxiliaryMat_Private(PC pc, IS is, Mat A, PetscBool deflation)
69d71ae5a4SJacob Faibussowitsch {
70f1580f4eSBarry Smith   PC_HPDDM                   *data = (PC_HPDDM *)pc->data;
71cdbd50ebSPierre Jolivet   PCHPDDMCoarseCorrectionType type = data->correction;
72f1580f4eSBarry Smith 
73f1580f4eSBarry Smith   PetscFunctionBegin;
74*c30dab7bSPierre Jolivet   PetscValidLogicalCollectiveBool(pc, deflation, 4);
75*c30dab7bSPierre Jolivet   if (is && A) {
76*c30dab7bSPierre Jolivet     PetscInt m[2];
77*c30dab7bSPierre Jolivet 
78*c30dab7bSPierre Jolivet     PetscCall(ISGetLocalSize(is, m));
79*c30dab7bSPierre Jolivet     PetscCall(MatGetLocalSize(A, m + 1, nullptr));
80*c30dab7bSPierre Jolivet     PetscCheck(m[0] == m[1], PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Inconsistent IS and Mat sizes (%" PetscInt_FMT " v. %" PetscInt_FMT ")", m[0], m[1]);
81*c30dab7bSPierre Jolivet   }
82f1580f4eSBarry Smith   if (is) {
83f1580f4eSBarry Smith     PetscCall(PetscObjectReference((PetscObject)is));
84f1580f4eSBarry Smith     if (data->is) { /* new overlap definition resets the PC */
85f1580f4eSBarry Smith       PetscCall(PCReset_HPDDM(pc));
86f1580f4eSBarry Smith       pc->setfromoptionscalled = 0;
87b853e353SPierre Jolivet       pc->setupcalled          = 0;
88cdbd50ebSPierre Jolivet       data->correction         = type;
89f1580f4eSBarry Smith     }
90f1580f4eSBarry Smith     PetscCall(ISDestroy(&data->is));
91f1580f4eSBarry Smith     data->is = is;
92f1580f4eSBarry Smith   }
93f1580f4eSBarry Smith   if (A) {
94f1580f4eSBarry Smith     PetscCall(PetscObjectReference((PetscObject)A));
95f1580f4eSBarry Smith     PetscCall(MatDestroy(&data->aux));
96f1580f4eSBarry Smith     data->aux = A;
97f1580f4eSBarry Smith   }
98f1580f4eSBarry Smith   data->deflation = deflation;
993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
100f1580f4eSBarry Smith }
101f1580f4eSBarry Smith 
102281f8ce6SPierre Jolivet static inline PetscErrorCode PCHPDDMSplittingMatNormal_Private(Mat A, IS *is, Mat *splitting[])
103281f8ce6SPierre Jolivet {
104281f8ce6SPierre Jolivet   Mat *sub;
105281f8ce6SPierre Jolivet   IS   zero;
106281f8ce6SPierre Jolivet 
107281f8ce6SPierre Jolivet   PetscFunctionBegin;
108281f8ce6SPierre Jolivet   PetscCall(MatSetOption(A, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
109281f8ce6SPierre Jolivet   PetscCall(MatCreateSubMatrices(A, 1, is + 2, is, MAT_INITIAL_MATRIX, splitting));
110281f8ce6SPierre Jolivet   PetscCall(MatCreateSubMatrices(**splitting, 1, is + 2, is + 1, MAT_INITIAL_MATRIX, &sub));
111281f8ce6SPierre Jolivet   PetscCall(MatFindZeroRows(*sub, &zero));
112281f8ce6SPierre Jolivet   PetscCall(MatDestroySubMatrices(1, &sub));
113281f8ce6SPierre Jolivet   PetscCall(MatSetOption(**splitting, MAT_KEEP_NONZERO_PATTERN, PETSC_TRUE));
114281f8ce6SPierre Jolivet   PetscCall(MatZeroRowsIS(**splitting, zero, 0.0, nullptr, nullptr));
115281f8ce6SPierre Jolivet   PetscCall(ISDestroy(&zero));
116281f8ce6SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
117281f8ce6SPierre Jolivet }
118281f8ce6SPierre Jolivet 
119281f8ce6SPierre Jolivet static inline PetscErrorCode PCHPDDMSetAuxiliaryMatNormal_Private(PC pc, Mat A, Mat N, Mat *B, const char *pcpre, Vec *diagonal = nullptr, Mat B01 = nullptr)
120d71ae5a4SJacob Faibussowitsch {
121f1580f4eSBarry Smith   PC_HPDDM *data         = (PC_HPDDM *)pc->data;
122281f8ce6SPierre Jolivet   Mat      *splitting[2] = {}, aux;
1233df4cd7bSPierre Jolivet   Vec       d;
124281f8ce6SPierre Jolivet   IS        is[3];
125f1580f4eSBarry Smith   PetscReal norm;
126f1580f4eSBarry Smith   PetscBool flg;
127f1580f4eSBarry Smith   char      type[256] = {}; /* same size as in src/ksp/pc/interface/pcset.c */
128f1580f4eSBarry Smith 
129f1580f4eSBarry Smith   PetscFunctionBegin;
130281f8ce6SPierre Jolivet   if (!B01) PetscCall(MatConvert(N, MATAIJ, MAT_INITIAL_MATRIX, B));
131281f8ce6SPierre Jolivet   else PetscCall(MatTransposeMatMult(B01, A, MAT_INITIAL_MATRIX, PETSC_DETERMINE, B));
132feebddf4SPierre Jolivet   PetscCall(MatEliminateZeros(*B, PETSC_TRUE));
133281f8ce6SPierre Jolivet   PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->n, A->cmap->rstart, 1, is));
134281f8ce6SPierre Jolivet   PetscCall(MatIncreaseOverlap(*B, 1, is, 1));
135281f8ce6SPierre Jolivet   PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->n, A->cmap->rstart, 1, is + 2));
136281f8ce6SPierre Jolivet   PetscCall(ISEmbed(is[0], is[2], PETSC_TRUE, is + 1));
137281f8ce6SPierre Jolivet   PetscCall(ISDestroy(is + 2));
138281f8ce6SPierre Jolivet   PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->N, 0, 1, is + 2));
139281f8ce6SPierre Jolivet   PetscCall(PCHPDDMSplittingMatNormal_Private(A, is, &splitting[0]));
140281f8ce6SPierre Jolivet   if (B01) {
141281f8ce6SPierre Jolivet     PetscCall(PCHPDDMSplittingMatNormal_Private(B01, is, &splitting[1]));
142281f8ce6SPierre Jolivet     PetscCall(MatDestroy(&B01));
143281f8ce6SPierre Jolivet   }
144281f8ce6SPierre Jolivet   PetscCall(ISDestroy(is + 2));
145281f8ce6SPierre Jolivet   PetscCall(ISDestroy(is + 1));
146db4a47b3SPierre Jolivet   PetscCall(PetscOptionsGetString(nullptr, pcpre, "-pc_hpddm_levels_1_sub_pc_type", type, sizeof(type), nullptr));
147f1580f4eSBarry Smith   PetscCall(PetscStrcmp(type, PCQR, &flg));
148f1580f4eSBarry Smith   if (!flg) {
149281f8ce6SPierre Jolivet     Mat conjugate = *splitting[splitting[1] ? 1 : 0];
150811e8887SPierre Jolivet 
151281f8ce6SPierre Jolivet     if (PetscDefined(USE_COMPLEX) && !splitting[1]) {
152281f8ce6SPierre Jolivet       PetscCall(MatDuplicate(*splitting[0], MAT_COPY_VALUES, &conjugate));
153f1580f4eSBarry Smith       PetscCall(MatConjugate(conjugate));
154f1580f4eSBarry Smith     }
155281f8ce6SPierre Jolivet     PetscCall(MatTransposeMatMult(conjugate, *splitting[0], MAT_INITIAL_MATRIX, PETSC_DETERMINE, &aux));
156281f8ce6SPierre Jolivet     if (PetscDefined(USE_COMPLEX) && !splitting[1]) PetscCall(MatDestroy(&conjugate));
157281f8ce6SPierre Jolivet     else if (splitting[1]) PetscCall(MatDestroySubMatrices(1, &splitting[1]));
158f1580f4eSBarry Smith     PetscCall(MatNorm(aux, NORM_FROBENIUS, &norm));
159f1580f4eSBarry Smith     PetscCall(MatSetOption(aux, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
1603df4cd7bSPierre Jolivet     if (diagonal) {
161811e8887SPierre Jolivet       PetscReal norm;
162811e8887SPierre Jolivet 
163feebddf4SPierre Jolivet       PetscCall(VecScale(*diagonal, -1.0));
1643df4cd7bSPierre Jolivet       PetscCall(VecNorm(*diagonal, NORM_INFINITY, &norm));
1653df4cd7bSPierre Jolivet       if (norm > PETSC_SMALL) {
16601e3c840SPierre Jolivet         PetscSF  scatter;
1673df4cd7bSPierre Jolivet         PetscInt n;
168811e8887SPierre Jolivet 
169281f8ce6SPierre Jolivet         PetscCall(ISGetLocalSize(*is, &n));
1703df4cd7bSPierre Jolivet         PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)pc), n, PETSC_DECIDE, &d));
171281f8ce6SPierre Jolivet         PetscCall(VecScatterCreate(*diagonal, *is, d, nullptr, &scatter));
1723df4cd7bSPierre Jolivet         PetscCall(VecScatterBegin(scatter, *diagonal, d, INSERT_VALUES, SCATTER_FORWARD));
1733df4cd7bSPierre Jolivet         PetscCall(VecScatterEnd(scatter, *diagonal, d, INSERT_VALUES, SCATTER_FORWARD));
17401e3c840SPierre Jolivet         PetscCall(PetscSFDestroy(&scatter));
1753df4cd7bSPierre Jolivet         PetscCall(MatDiagonalSet(aux, d, ADD_VALUES));
1763df4cd7bSPierre Jolivet         PetscCall(VecDestroy(&d));
1773df4cd7bSPierre Jolivet       } else PetscCall(VecDestroy(diagonal));
1783df4cd7bSPierre Jolivet     }
1793df4cd7bSPierre Jolivet     if (!diagonal) PetscCall(MatShift(aux, PETSC_SMALL * norm));
180f1580f4eSBarry Smith   } else {
181f1580f4eSBarry Smith     PetscBool flg;
182811e8887SPierre Jolivet 
183281f8ce6SPierre Jolivet     PetscCheck(!splitting[1], PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot use PCQR when A01 != A10^T");
1843df4cd7bSPierre Jolivet     if (diagonal) {
1853df4cd7bSPierre Jolivet       PetscCall(VecNorm(*diagonal, NORM_INFINITY, &norm));
1863df4cd7bSPierre Jolivet       PetscCheck(norm < PETSC_SMALL, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Nonzero diagonal A11 block");
1873df4cd7bSPierre Jolivet       PetscCall(VecDestroy(diagonal));
1883df4cd7bSPierre Jolivet     }
189f1580f4eSBarry Smith     PetscCall(PetscObjectTypeCompare((PetscObject)N, MATNORMAL, &flg));
190281f8ce6SPierre Jolivet     if (flg) PetscCall(MatCreateNormal(*splitting[0], &aux));
191281f8ce6SPierre Jolivet     else PetscCall(MatCreateNormalHermitian(*splitting[0], &aux));
192f1580f4eSBarry Smith   }
193281f8ce6SPierre Jolivet   PetscCall(MatDestroySubMatrices(1, &splitting[0]));
194281f8ce6SPierre Jolivet   PetscCall(PCHPDDMSetAuxiliaryMat(pc, *is, aux, nullptr, nullptr));
195c8ea6600SPierre Jolivet   data->Neumann = PETSC_BOOL3_TRUE;
196281f8ce6SPierre Jolivet   PetscCall(ISDestroy(is));
197f1580f4eSBarry Smith   PetscCall(MatDestroy(&aux));
1983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
199f1580f4eSBarry Smith }
200f1580f4eSBarry Smith 
201d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMSetAuxiliaryMat_HPDDM(PC pc, IS is, Mat A, PetscErrorCode (*setup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void *setup_ctx)
202d71ae5a4SJacob Faibussowitsch {
203f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
204f1580f4eSBarry Smith 
205f1580f4eSBarry Smith   PetscFunctionBegin;
206f1580f4eSBarry Smith   PetscCall(PCHPDDMSetAuxiliaryMat_Private(pc, is, A, PETSC_FALSE));
207f1580f4eSBarry Smith   if (setup) {
208f1580f4eSBarry Smith     data->setup     = setup;
209f1580f4eSBarry Smith     data->setup_ctx = setup_ctx;
210f1580f4eSBarry Smith   }
2113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
212f1580f4eSBarry Smith }
213f1580f4eSBarry Smith 
21473329a61SPierre Jolivet typedef struct {
21573329a61SPierre Jolivet   KSP      ksp;
21673329a61SPierre Jolivet   PetscInt its;
21773329a61SPierre Jolivet } PC_KSP;
21873329a61SPierre Jolivet 
21973329a61SPierre Jolivet static inline PetscErrorCode PCSetUp_KSP_Private(PC pc)
22073329a61SPierre Jolivet {
22173329a61SPierre Jolivet   PC_KSP           *data   = (PC_KSP *)pc->data;
22273329a61SPierre Jolivet   const std::string prefix = ((PetscObject)data->ksp)->prefix;
22373329a61SPierre Jolivet   std::string       sub;
22473329a61SPierre Jolivet 
22573329a61SPierre Jolivet   PetscFunctionBegin;
22673329a61SPierre Jolivet   PetscCheck(prefix.size() >= 9, PETSC_COMM_SELF, PETSC_ERR_PLIB, "The prefix of this PCKSP should be of length at least 9 to hold the suffix pc_hpddm_");
22773329a61SPierre Jolivet   sub = prefix.substr(0, prefix.size() - 9);
22873329a61SPierre Jolivet   PetscCall(PCSetType(pc, PCHPDDM));
22973329a61SPierre Jolivet   PetscCall(PCSetOptionsPrefix(pc, sub.c_str()));
23073329a61SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
23173329a61SPierre Jolivet }
23273329a61SPierre Jolivet 
23373329a61SPierre Jolivet static PetscErrorCode PCSetUp_KSP(PC pc)
23473329a61SPierre Jolivet {
23573329a61SPierre Jolivet   PetscFunctionBegin;
23673329a61SPierre Jolivet   PetscCall(PCSetUp_KSP_Private(pc));
23773329a61SPierre Jolivet   PetscCall(PCSetFromOptions(pc));
23873329a61SPierre Jolivet   PetscCall(PCSetUp(pc));
23973329a61SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
24073329a61SPierre Jolivet }
24173329a61SPierre Jolivet 
24270009435SPierre Jolivet /*@C
24304c3f3b8SBarry Smith   PCHPDDMSetAuxiliaryMat - Sets the auxiliary matrix used by `PCHPDDM` for the concurrent GenEO problems at the finest level.
244f1580f4eSBarry Smith 
245f1580f4eSBarry Smith   Input Parameters:
246f1580f4eSBarry Smith + pc    - preconditioner context
247f1580f4eSBarry Smith . is    - index set of the local auxiliary, e.g., Neumann, matrix
248f1580f4eSBarry Smith . A     - auxiliary sequential matrix
24904c3f3b8SBarry Smith . setup - function for generating the auxiliary matrix entries, may be `NULL`
25004c3f3b8SBarry Smith - ctx   - context for `setup`, may be `NULL`
25104c3f3b8SBarry Smith 
25204c3f3b8SBarry Smith   Calling sequence of `setup`:
25304c3f3b8SBarry Smith + J   - matrix whose values are to be set
25404c3f3b8SBarry Smith . t   - time
25504c3f3b8SBarry Smith . X   - linearization point
25604c3f3b8SBarry Smith . X_t - time-derivative of the linearization point
25704c3f3b8SBarry Smith . s   - step
25804c3f3b8SBarry Smith . ovl - index set of the local auxiliary, e.g., Neumann, matrix
25904c3f3b8SBarry Smith - ctx - context for `setup`, may be `NULL`
260f1580f4eSBarry Smith 
261f1580f4eSBarry Smith   Level: intermediate
262f1580f4eSBarry Smith 
26304c3f3b8SBarry Smith   Note:
26404c3f3b8SBarry Smith   As an example, in a finite element context with nonoverlapping subdomains plus (overlapping) ghost elements, this could be the unassembled (Neumann)
26504c3f3b8SBarry Smith   local overlapping operator. As opposed to the assembled (Dirichlet) local overlapping operator obtained by summing neighborhood contributions
26604c3f3b8SBarry Smith   at the interface of ghost elements.
26704c3f3b8SBarry Smith 
26870009435SPierre Jolivet   Fortran Notes:
26904c3f3b8SBarry Smith   Only `PETSC_NULL_FUNCTION` is supported for `setup` and `ctx` is never accessed
27070009435SPierre Jolivet 
271562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHPDDMSetRHSMat()`, `MATIS`
272f1580f4eSBarry Smith @*/
27304c3f3b8SBarry Smith PetscErrorCode PCHPDDMSetAuxiliaryMat(PC pc, IS is, Mat A, PetscErrorCode (*setup)(Mat J, PetscReal t, Vec X, Vec X_t, PetscReal s, IS ovl, void *ctx), void *ctx)
274d71ae5a4SJacob Faibussowitsch {
275f1580f4eSBarry Smith   PetscFunctionBegin;
276f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
277f1580f4eSBarry Smith   if (is) PetscValidHeaderSpecific(is, IS_CLASSID, 2);
278f1580f4eSBarry Smith   if (A) PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
27973329a61SPierre Jolivet   if (pc->ops->setup == PCSetUp_KSP) PetscCall(PCSetUp_KSP_Private(pc));
28004c3f3b8SBarry Smith   PetscTryMethod(pc, "PCHPDDMSetAuxiliaryMat_C", (PC, IS, Mat, PetscErrorCode (*)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void *), (pc, is, A, setup, ctx));
2813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
282f1580f4eSBarry Smith }
283f1580f4eSBarry Smith 
284d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMHasNeumannMat_HPDDM(PC pc, PetscBool has)
285d71ae5a4SJacob Faibussowitsch {
286f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
287f1580f4eSBarry Smith 
288f1580f4eSBarry Smith   PetscFunctionBegin;
289c8ea6600SPierre Jolivet   data->Neumann = PetscBoolToBool3(has);
2903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
291f1580f4eSBarry Smith }
292f1580f4eSBarry Smith 
293f1580f4eSBarry Smith /*@
294f1580f4eSBarry Smith   PCHPDDMHasNeumannMat - Informs `PCHPDDM` that the `Mat` passed to `PCHPDDMSetAuxiliaryMat()` is the local Neumann matrix.
295f1580f4eSBarry Smith 
296f1580f4eSBarry Smith   Input Parameters:
297f1580f4eSBarry Smith + pc  - preconditioner context
298f1580f4eSBarry Smith - has - Boolean value
299f1580f4eSBarry Smith 
300f1580f4eSBarry Smith   Level: intermediate
301f1580f4eSBarry Smith 
302f1580f4eSBarry Smith   Notes:
3037eb095acSPierre Jolivet   This may be used to bypass a call to `MatCreateSubMatrices()` and to `MatConvert()` for `MATSBAIJ` matrices.
304f1580f4eSBarry Smith 
305907a3e9cSStefano Zampini   If a function is composed with DMCreateNeumannOverlap_C 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`.
306f1580f4eSBarry Smith 
307562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMSetAuxiliaryMat()`
308f1580f4eSBarry Smith @*/
309d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMHasNeumannMat(PC pc, PetscBool has)
310d71ae5a4SJacob Faibussowitsch {
311f1580f4eSBarry Smith   PetscFunctionBegin;
312f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
313f1580f4eSBarry Smith   PetscTryMethod(pc, "PCHPDDMHasNeumannMat_C", (PC, PetscBool), (pc, has));
3143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
315f1580f4eSBarry Smith }
316f1580f4eSBarry Smith 
317d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMSetRHSMat_HPDDM(PC pc, Mat B)
318d71ae5a4SJacob Faibussowitsch {
319f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
320f1580f4eSBarry Smith 
321f1580f4eSBarry Smith   PetscFunctionBegin;
322f1580f4eSBarry Smith   PetscCall(PetscObjectReference((PetscObject)B));
323f1580f4eSBarry Smith   PetscCall(MatDestroy(&data->B));
324f1580f4eSBarry Smith   data->B = B;
3253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
326f1580f4eSBarry Smith }
327f1580f4eSBarry Smith 
328f1580f4eSBarry Smith /*@
32904c3f3b8SBarry Smith   PCHPDDMSetRHSMat - Sets the right-hand side matrix used by `PCHPDDM` for the concurrent GenEO problems at the finest level.
330f1580f4eSBarry Smith 
331f1580f4eSBarry Smith   Input Parameters:
332f1580f4eSBarry Smith + pc - preconditioner context
333f1580f4eSBarry Smith - B  - right-hand side sequential matrix
334f1580f4eSBarry Smith 
335f1580f4eSBarry Smith   Level: advanced
336f1580f4eSBarry Smith 
33704c3f3b8SBarry Smith   Note:
33804c3f3b8SBarry Smith   Must be used in conjunction with `PCHPDDMSetAuxiliaryMat`(N), so that Nv = lambda Bv is solved using `EPSSetOperators`(N, B).
33904c3f3b8SBarry Smith   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.
34004c3f3b8SBarry Smith 
341562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDMSetAuxiliaryMat()`, `PCHPDDM`
342f1580f4eSBarry Smith @*/
343d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMSetRHSMat(PC pc, Mat B)
344d71ae5a4SJacob Faibussowitsch {
345f1580f4eSBarry Smith   PetscFunctionBegin;
346f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
347f1580f4eSBarry Smith   if (B) {
348f1580f4eSBarry Smith     PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
349f1580f4eSBarry Smith     PetscTryMethod(pc, "PCHPDDMSetRHSMat_C", (PC, Mat), (pc, B));
350f1580f4eSBarry Smith   }
3513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
352f1580f4eSBarry Smith }
353f1580f4eSBarry Smith 
354ce78bad3SBarry Smith static PetscErrorCode PCSetFromOptions_HPDDM(PC pc, PetscOptionItems PetscOptionsObject)
355d71ae5a4SJacob Faibussowitsch {
356f1580f4eSBarry Smith   PC_HPDDM                   *data   = (PC_HPDDM *)pc->data;
357f1580f4eSBarry Smith   PC_HPDDM_Level            **levels = data->levels;
358f1580f4eSBarry Smith   char                        prefix[256];
359f1580f4eSBarry Smith   int                         i = 1;
360f1580f4eSBarry Smith   PetscMPIInt                 size, previous;
3619bb5c669SPierre Jolivet   PetscInt                    n, overlap = 1;
362f1580f4eSBarry Smith   PCHPDDMCoarseCorrectionType type;
363c8ea6600SPierre Jolivet   PetscBool                   flg = PETSC_TRUE, set;
364f1580f4eSBarry Smith 
365f1580f4eSBarry Smith   PetscFunctionBegin;
366f1580f4eSBarry Smith   if (!data->levels) {
367f1580f4eSBarry Smith     PetscCall(PetscCalloc1(PETSC_PCHPDDM_MAXLEVELS, &levels));
368f1580f4eSBarry Smith     data->levels = levels;
369f1580f4eSBarry Smith   }
370f1580f4eSBarry Smith   PetscOptionsHeadBegin(PetscOptionsObject, "PCHPDDM options");
3719bb5c669SPierre Jolivet   PetscCall(PetscOptionsBoundedInt("-pc_hpddm_harmonic_overlap", "Overlap prior to computing local harmonic extensions", "PCHPDDM", overlap, &overlap, &set, 1));
3729bb5c669SPierre Jolivet   if (!set) overlap = -1;
373f1580f4eSBarry Smith   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size));
374f1580f4eSBarry Smith   previous = size;
375f1580f4eSBarry Smith   while (i < PETSC_PCHPDDM_MAXLEVELS) {
376f1580f4eSBarry Smith     PetscInt p = 1;
377f1580f4eSBarry Smith 
3784dfa11a4SJacob Faibussowitsch     if (!data->levels[i - 1]) PetscCall(PetscNew(data->levels + i - 1));
379f1580f4eSBarry Smith     data->levels[i - 1]->parent = data;
380f1580f4eSBarry Smith     /* if the previous level has a single process, it is not possible to coarsen further */
381f1580f4eSBarry Smith     if (previous == 1 || !flg) break;
382f1580f4eSBarry Smith     data->levels[i - 1]->nu        = 0;
383f1580f4eSBarry Smith     data->levels[i - 1]->threshold = -1.0;
384f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_nev", i));
385db4a47b3SPierre Jolivet     PetscCall(PetscOptionsBoundedInt(prefix, "Local number of deflation vectors computed by SLEPc", "EPSSetDimensions", data->levels[i - 1]->nu, &data->levels[i - 1]->nu, nullptr, 0));
386f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold", i));
387db4a47b3SPierre Jolivet     PetscCall(PetscOptionsReal(prefix, "Local threshold for selecting deflation vectors returned by SLEPc", "PCHPDDM", data->levels[i - 1]->threshold, &data->levels[i - 1]->threshold, nullptr));
388f1580f4eSBarry Smith     if (i == 1) {
389aa1539e9SPierre Jolivet       PetscCheck(overlap == -1 || PetscAbsReal(data->levels[i - 1]->threshold + static_cast<PetscReal>(1.0)) < PETSC_MACHINE_EPSILON, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply both -pc_hpddm_levels_1_eps_threshold and -pc_hpddm_harmonic_overlap");
3909bb5c669SPierre Jolivet       if (overlap != -1) {
3919bb5c669SPierre Jolivet         PetscInt nsv = 0;
392811e8887SPierre Jolivet 
3939bb5c669SPierre Jolivet         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_svd_nsv", i));
3949bb5c669SPierre Jolivet         PetscCall(PetscOptionsBoundedInt(prefix, "Local number of deflation vectors computed by SLEPc", "SVDSetDimensions", nsv, &nsv, nullptr, 0));
3959bb5c669SPierre Jolivet         PetscCheck(bool(data->levels[0]->nu) != bool(nsv), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply %s -pc_hpddm_levels_1_eps_nev %s -pc_hpddm_levels_1_svd_nsv", nsv ? "both" : "neither", nsv ? "and" : "nor");
3969bb5c669SPierre Jolivet         if (nsv) {
3979bb5c669SPierre Jolivet           data->levels[0]->nu = nsv;
3989bb5c669SPierre Jolivet           PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_svd_relative_threshold", i));
3999bb5c669SPierre Jolivet         } else PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_relative_threshold", i));
4009bb5c669SPierre Jolivet         PetscCall(PetscOptionsReal(prefix, "Local relative threshold for selecting deflation vectors returned by SLEPc", "PCHPDDM", data->levels[0]->threshold, &data->levels[0]->threshold, nullptr));
4019bb5c669SPierre Jolivet       }
402f1580f4eSBarry Smith       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_1_st_share_sub_ksp"));
403db4a47b3SPierre Jolivet       PetscCall(PetscOptionsBool(prefix, "Shared KSP between SLEPc ST and the fine-level subdomain solver", "PCHPDDMSetSTShareSubKSP", PETSC_FALSE, &data->share, nullptr));
404f1580f4eSBarry Smith     }
405f1580f4eSBarry Smith     /* if there is no prescribed coarsening, just break out of the loop */
4060594bca0SPierre Jolivet     if (data->levels[i - 1]->threshold <= PetscReal() && data->levels[i - 1]->nu <= 0 && !(data->deflation && i == 1)) break;
407f1580f4eSBarry Smith     else {
408f1580f4eSBarry Smith       ++i;
409f1580f4eSBarry Smith       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_nev", i));
410f1580f4eSBarry Smith       PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
411f1580f4eSBarry Smith       if (!flg) {
412f1580f4eSBarry Smith         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold", i));
413f1580f4eSBarry Smith         PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
414f1580f4eSBarry Smith       }
415f1580f4eSBarry Smith       if (flg) {
416f1580f4eSBarry Smith         /* if there are coarsening options for the next level, then register it  */
417f1580f4eSBarry Smith         /* otherwise, don't to avoid having both options levels_N_p and coarse_p */
418f1580f4eSBarry Smith         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_p", i));
419f1580f4eSBarry Smith         PetscCall(PetscOptionsRangeInt(prefix, "Number of processes used to assemble the coarse operator at this level", "PCHPDDM", p, &p, &flg, 1, PetscMax(1, previous / 2)));
420f1580f4eSBarry Smith         previous = p;
421f1580f4eSBarry Smith       }
422f1580f4eSBarry Smith     }
423f1580f4eSBarry Smith   }
424f1580f4eSBarry Smith   data->N = i;
425f1580f4eSBarry Smith   n       = 1;
426f1580f4eSBarry Smith   if (i > 1) {
427f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_coarse_p"));
428db4a47b3SPierre Jolivet     PetscCall(PetscOptionsRangeInt(prefix, "Number of processes used to assemble the coarsest operator", "PCHPDDM", n, &n, nullptr, 1, PetscMax(1, previous / 2)));
42902800ff6SPierre Jolivet #if PetscDefined(HAVE_MUMPS)
430f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "pc_hpddm_coarse_"));
431db4a47b3SPierre Jolivet     PetscCall(PetscOptionsHasName(nullptr, prefix, "-mat_mumps_use_omp_threads", &flg));
432f1580f4eSBarry Smith     if (flg) {
433f1580f4eSBarry Smith       char type[64]; /* same size as in src/ksp/pc/impls/factor/factimpl.c */
434811e8887SPierre Jolivet 
435c6a7a370SJeremy L Thompson       PetscCall(PetscStrncpy(type, n > 1 && PetscDefined(HAVE_MUMPS) ? MATSOLVERMUMPS : MATSOLVERPETSC, sizeof(type))); /* default solver for a MatMPIAIJ or a MatSeqAIJ */
436db4a47b3SPierre Jolivet       PetscCall(PetscOptionsGetString(nullptr, prefix, "-pc_factor_mat_solver_type", type, sizeof(type), nullptr));
4373ce573a3SPierre Jolivet       PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
438f1580f4eSBarry Smith       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "-%smat_mumps_use_omp_threads and -%spc_factor_mat_solver_type != %s", prefix, prefix, MATSOLVERMUMPS);
439f1580f4eSBarry Smith       size = n;
440f1580f4eSBarry Smith       n    = -1;
441db4a47b3SPierre Jolivet       PetscCall(PetscOptionsGetInt(nullptr, prefix, "-mat_mumps_use_omp_threads", &n, nullptr));
442f1580f4eSBarry Smith       PetscCheck(n >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Need to specify a positive integer for -%smat_mumps_use_omp_threads", prefix);
443f1580f4eSBarry Smith       PetscCheck(n * size <= previous, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%d MPI process%s x %d OpenMP thread%s greater than %d available MPI process%s for the coarsest operator", (int)size, size > 1 ? "es" : "", (int)n, n > 1 ? "s" : "", (int)previous, previous > 1 ? "es" : "");
444f1580f4eSBarry Smith     }
445f1580f4eSBarry Smith #endif
446f1580f4eSBarry Smith     PetscCall(PetscOptionsEnum("-pc_hpddm_coarse_correction", "Type of coarse correction applied each iteration", "PCHPDDMSetCoarseCorrectionType", PCHPDDMCoarseCorrectionTypes, (PetscEnum)data->correction, (PetscEnum *)&type, &flg));
447f1580f4eSBarry Smith     if (flg) PetscCall(PCHPDDMSetCoarseCorrectionType(pc, type));
448f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_has_neumann"));
449c8ea6600SPierre Jolivet     PetscCall(PetscOptionsBool(prefix, "Is the auxiliary Mat the local Neumann matrix?", "PCHPDDMHasNeumannMat", PetscBool3ToBool(data->Neumann), &flg, &set));
450c8ea6600SPierre Jolivet     if (set) data->Neumann = PetscBoolToBool3(flg);
451f1580f4eSBarry Smith     data->log_separate = PETSC_FALSE;
452f1580f4eSBarry Smith     if (PetscDefined(USE_LOG)) {
453f1580f4eSBarry Smith       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_log_separate"));
454db4a47b3SPierre Jolivet       PetscCall(PetscOptionsBool(prefix, "Log events level by level instead of inside PCSetUp()/KSPSolve()", nullptr, data->log_separate, &data->log_separate, nullptr));
455f1580f4eSBarry Smith     }
456f1580f4eSBarry Smith   }
457f1580f4eSBarry Smith   PetscOptionsHeadEnd();
458f1580f4eSBarry Smith   while (i < PETSC_PCHPDDM_MAXLEVELS && data->levels[i]) PetscCall(PetscFree(data->levels[i++]));
4593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
460f1580f4eSBarry Smith }
461f1580f4eSBarry Smith 
462d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCApply_HPDDM(PC pc, Vec x, Vec y)
463d71ae5a4SJacob Faibussowitsch {
464f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
465f1580f4eSBarry Smith 
466f1580f4eSBarry Smith   PetscFunctionBegin;
467f1580f4eSBarry Smith   PetscCall(PetscCitationsRegister(HPDDMCitation, &HPDDMCite));
468f1580f4eSBarry Smith   PetscCheck(data->levels[0]->ksp, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No KSP attached to PCHPDDM");
469db4a47b3SPierre Jolivet   if (data->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_Solve[0], data->levels[0]->ksp, nullptr, nullptr, nullptr)); /* coarser-level events are directly triggered in HPDDM */
470f1580f4eSBarry Smith   PetscCall(KSPSolve(data->levels[0]->ksp, x, y));
471db4a47b3SPierre Jolivet   if (data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_Solve[0], data->levels[0]->ksp, nullptr, nullptr, nullptr));
4723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
473f1580f4eSBarry Smith }
474f1580f4eSBarry Smith 
475d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCMatApply_HPDDM(PC pc, Mat X, Mat Y)
476d71ae5a4SJacob Faibussowitsch {
477f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
478f1580f4eSBarry Smith 
479f1580f4eSBarry Smith   PetscFunctionBegin;
480f1580f4eSBarry Smith   PetscCall(PetscCitationsRegister(HPDDMCitation, &HPDDMCite));
481f1580f4eSBarry Smith   PetscCheck(data->levels[0]->ksp, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No KSP attached to PCHPDDM");
482f1580f4eSBarry Smith   PetscCall(KSPMatSolve(data->levels[0]->ksp, X, Y));
4833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
484f1580f4eSBarry Smith }
485f1580f4eSBarry Smith 
486cc4c1da9SBarry Smith /*@
487f1580f4eSBarry Smith   PCHPDDMGetComplexities - Computes the grid and operator complexities.
488f1580f4eSBarry Smith 
489c71f06a7SPierre Jolivet   Collective
490c71f06a7SPierre Jolivet 
491f1580f4eSBarry Smith   Input Parameter:
492f1580f4eSBarry Smith . pc - preconditioner context
493f1580f4eSBarry Smith 
494f1580f4eSBarry Smith   Output Parameters:
495cc4c1da9SBarry Smith + gc - grid complexity $ \sum_i m_i / m_1 $
496cc4c1da9SBarry Smith - oc - operator complexity $ \sum_i nnz_i / nnz_1 $
497f1580f4eSBarry Smith 
498f1580f4eSBarry Smith   Level: advanced
499f1580f4eSBarry Smith 
500562efe2eSBarry Smith .seealso: [](ch_ksp), `PCMGGetGridComplexity()`, `PCHPDDM`, `PCHYPRE`, `PCGAMG`
501f1580f4eSBarry Smith @*/
502cc4c1da9SBarry Smith PetscErrorCode PCHPDDMGetComplexities(PC pc, PetscReal *gc, PetscReal *oc)
503d71ae5a4SJacob Faibussowitsch {
504f1580f4eSBarry Smith   PC_HPDDM      *data = (PC_HPDDM *)pc->data;
505f1580f4eSBarry Smith   MatInfo        info;
506f1580f4eSBarry Smith   PetscLogDouble accumulate[2]{}, nnz1 = 1.0, m1 = 1.0;
507f1580f4eSBarry Smith 
508f1580f4eSBarry Smith   PetscFunctionBegin;
509715c1178SPierre Jolivet   if (gc) {
510715c1178SPierre Jolivet     PetscAssertPointer(gc, 2);
511715c1178SPierre Jolivet     *gc = 0;
512715c1178SPierre Jolivet   }
513715c1178SPierre Jolivet   if (oc) {
514715c1178SPierre Jolivet     PetscAssertPointer(oc, 3);
515715c1178SPierre Jolivet     *oc = 0;
516715c1178SPierre Jolivet   }
517715c1178SPierre Jolivet   for (PetscInt n = 0; n < data->N; ++n) {
518f1580f4eSBarry Smith     if (data->levels[n]->ksp) {
51913044ca3SPierre Jolivet       Mat       P, A = nullptr;
520715c1178SPierre Jolivet       PetscInt  m;
52113044ca3SPierre Jolivet       PetscBool flg = PETSC_FALSE;
52213044ca3SPierre Jolivet 
523db4a47b3SPierre Jolivet       PetscCall(KSPGetOperators(data->levels[n]->ksp, nullptr, &P));
524db4a47b3SPierre Jolivet       PetscCall(MatGetSize(P, &m, nullptr));
525f1580f4eSBarry Smith       accumulate[0] += m;
526f1580f4eSBarry Smith       if (n == 0) {
527f1580f4eSBarry Smith         PetscCall(PetscObjectTypeCompareAny((PetscObject)P, &flg, MATNORMAL, MATNORMALHERMITIAN, ""));
528f1580f4eSBarry Smith         if (flg) {
529f1580f4eSBarry Smith           PetscCall(MatConvert(P, MATAIJ, MAT_INITIAL_MATRIX, &A));
530f1580f4eSBarry Smith           P = A;
53113044ca3SPierre Jolivet         } else {
53213044ca3SPierre Jolivet           PetscCall(PetscObjectTypeCompare((PetscObject)P, MATSCHURCOMPLEMENT, &flg));
53313044ca3SPierre Jolivet           PetscCall(PetscObjectReference((PetscObject)P));
534f1580f4eSBarry Smith         }
53513044ca3SPierre Jolivet       }
53613044ca3SPierre Jolivet       if (!A && flg) accumulate[1] += m * m; /* assumption that a MATSCHURCOMPLEMENT is dense if stored explicitly */
53713044ca3SPierre Jolivet       else if (P->ops->getinfo) {
538f1580f4eSBarry Smith         PetscCall(MatGetInfo(P, MAT_GLOBAL_SUM, &info));
539f1580f4eSBarry Smith         accumulate[1] += info.nz_used;
540f1580f4eSBarry Smith       }
541f1580f4eSBarry Smith       if (n == 0) {
542f1580f4eSBarry Smith         m1 = m;
54313044ca3SPierre Jolivet         if (!A && flg) nnz1 = m * m;
54413044ca3SPierre Jolivet         else if (P->ops->getinfo) nnz1 = info.nz_used;
545f1580f4eSBarry Smith         PetscCall(MatDestroy(&P));
546f1580f4eSBarry Smith       }
547f1580f4eSBarry Smith     }
548f1580f4eSBarry Smith   }
549715c1178SPierre Jolivet   /* only process #0 has access to the full hierarchy by construction, so broadcast to ensure consistent outputs */
550715c1178SPierre Jolivet   PetscCallMPI(MPI_Bcast(accumulate, 2, MPIU_PETSCLOGDOUBLE, 0, PetscObjectComm((PetscObject)pc)));
551715c1178SPierre Jolivet   if (gc) *gc = static_cast<PetscReal>(accumulate[0] / m1);
552715c1178SPierre Jolivet   if (oc) *oc = static_cast<PetscReal>(accumulate[1] / nnz1);
5533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
554f1580f4eSBarry Smith }
555f1580f4eSBarry Smith 
556d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCView_HPDDM(PC pc, PetscViewer viewer)
557d71ae5a4SJacob Faibussowitsch {
558f1580f4eSBarry Smith   PC_HPDDM         *data = (PC_HPDDM *)pc->data;
559f1580f4eSBarry Smith   PetscViewer       subviewer;
560aa21023fSPierre Jolivet   PetscViewerFormat format;
561f1580f4eSBarry Smith   PetscSubcomm      subcomm;
562f1580f4eSBarry Smith   PetscReal         oc, gc;
563811e8887SPierre Jolivet   PetscInt          tabs;
564f1580f4eSBarry Smith   PetscMPIInt       size, color, rank;
565aa21023fSPierre Jolivet   PetscBool         flg;
566aa21023fSPierre Jolivet   const char       *name;
567f1580f4eSBarry Smith 
568f1580f4eSBarry Smith   PetscFunctionBegin;
569aa21023fSPierre Jolivet   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &flg));
570aa21023fSPierre Jolivet   if (flg) {
571f1580f4eSBarry Smith     PetscCall(PetscViewerASCIIPrintf(viewer, "level%s: %" PetscInt_FMT "\n", data->N > 1 ? "s" : "", data->N));
572f1580f4eSBarry Smith     PetscCall(PCHPDDMGetComplexities(pc, &gc, &oc));
573f1580f4eSBarry Smith     if (data->N > 1) {
574f1580f4eSBarry Smith       if (!data->deflation) {
575c8ea6600SPierre Jolivet         PetscCall(PetscViewerASCIIPrintf(viewer, "Neumann matrix attached? %s\n", PetscBools[PetscBool3ToBool(data->Neumann)]));
576f1580f4eSBarry Smith         PetscCall(PetscViewerASCIIPrintf(viewer, "shared subdomain KSP between SLEPc and PETSc? %s\n", PetscBools[data->share]));
577f1580f4eSBarry Smith       } else PetscCall(PetscViewerASCIIPrintf(viewer, "user-supplied deflation matrix\n"));
578f1580f4eSBarry Smith       PetscCall(PetscViewerASCIIPrintf(viewer, "coarse correction: %s\n", PCHPDDMCoarseCorrectionTypes[data->correction]));
579f1580f4eSBarry Smith       PetscCall(PetscViewerASCIIPrintf(viewer, "on process #0, value%s (+ threshold%s if available) for selecting deflation vectors:", data->N > 2 ? "s" : "", data->N > 2 ? "s" : ""));
580f1580f4eSBarry Smith       PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
581f1580f4eSBarry Smith       PetscCall(PetscViewerASCIISetTab(viewer, 0));
582811e8887SPierre Jolivet       for (PetscInt i = 1; i < data->N; ++i) {
583f1580f4eSBarry Smith         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, data->levels[i - 1]->nu));
5840594bca0SPierre Jolivet         if (data->levels[i - 1]->threshold > static_cast<PetscReal>(-0.1)) PetscCall(PetscViewerASCIIPrintf(viewer, " (%g)", (double)data->levels[i - 1]->threshold));
585f1580f4eSBarry Smith       }
586f1580f4eSBarry Smith       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
587f1580f4eSBarry Smith       PetscCall(PetscViewerASCIISetTab(viewer, tabs));
588f1580f4eSBarry Smith     }
589f1580f4eSBarry Smith     PetscCall(PetscViewerASCIIPrintf(viewer, "grid and operator complexities: %g %g\n", (double)gc, (double)oc));
5901fe44b27SPierre Jolivet     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size));
591f1580f4eSBarry Smith     if (data->levels[0]->ksp) {
592f1580f4eSBarry Smith       PetscCall(KSPView(data->levels[0]->ksp, viewer));
593f1580f4eSBarry Smith       if (data->levels[0]->pc) PetscCall(PCView(data->levels[0]->pc, viewer));
594eea1a2f1SRaphael Zanella       PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)pc), &rank));
595811e8887SPierre Jolivet       for (PetscInt i = 1; i < data->N; ++i) {
596f1580f4eSBarry Smith         if (data->levels[i]->ksp) color = 1;
597f1580f4eSBarry Smith         else color = 0;
598f1580f4eSBarry Smith         PetscCall(PetscSubcommCreate(PetscObjectComm((PetscObject)pc), &subcomm));
599f1580f4eSBarry Smith         PetscCall(PetscSubcommSetNumber(subcomm, PetscMin(size, 2)));
600f1580f4eSBarry Smith         PetscCall(PetscSubcommSetTypeGeneral(subcomm, color, rank));
601f1580f4eSBarry Smith         PetscCall(PetscViewerASCIIPushTab(viewer));
602f1580f4eSBarry Smith         PetscCall(PetscViewerGetSubViewer(viewer, PetscSubcommChild(subcomm), &subviewer));
603f1580f4eSBarry Smith         if (color == 1) {
604f1580f4eSBarry Smith           PetscCall(KSPView(data->levels[i]->ksp, subviewer));
605f1580f4eSBarry Smith           if (data->levels[i]->pc) PetscCall(PCView(data->levels[i]->pc, subviewer));
606f1580f4eSBarry Smith           PetscCall(PetscViewerFlush(subviewer));
607f1580f4eSBarry Smith         }
608f1580f4eSBarry Smith         PetscCall(PetscViewerRestoreSubViewer(viewer, PetscSubcommChild(subcomm), &subviewer));
609f1580f4eSBarry Smith         PetscCall(PetscViewerASCIIPopTab(viewer));
610f1580f4eSBarry Smith         PetscCall(PetscSubcommDestroy(&subcomm));
611f1580f4eSBarry Smith       }
612f1580f4eSBarry Smith     }
613aa21023fSPierre Jolivet     PetscCall(PetscViewerGetFormat(viewer, &format));
614aa21023fSPierre Jolivet     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
615aa21023fSPierre Jolivet       PetscCall(PetscViewerFileGetName(viewer, &name));
616aa21023fSPierre Jolivet       if (name) {
617eea1a2f1SRaphael Zanella         Mat             aux[2];
618aa21023fSPierre Jolivet         IS              is;
619eea1a2f1SRaphael Zanella         const PetscInt *indices;
620eea1a2f1SRaphael Zanella         PetscInt        m, n, sizes[5] = {pc->mat->rmap->n, pc->mat->cmap->n, pc->mat->rmap->N, pc->mat->cmap->N, 0};
621aa21023fSPierre Jolivet         char           *tmp;
622aa21023fSPierre Jolivet         std::string     prefix, suffix;
623aa21023fSPierre Jolivet         size_t          pos;
624aa21023fSPierre Jolivet 
625aa21023fSPierre Jolivet         PetscCall(PetscStrstr(name, ".", &tmp));
626aa21023fSPierre Jolivet         if (tmp) {
627aa21023fSPierre Jolivet           pos    = std::distance(const_cast<char *>(name), tmp);
628aa21023fSPierre Jolivet           prefix = std::string(name, pos);
629aa21023fSPierre Jolivet           suffix = std::string(name + pos + 1);
630aa21023fSPierre Jolivet         } else prefix = name;
631aa21023fSPierre Jolivet         if (data->aux) {
632eea1a2f1SRaphael Zanella           PetscCall(MatGetSize(data->aux, &m, &n));
633eea1a2f1SRaphael Zanella           PetscCall(MatCreate(PetscObjectComm((PetscObject)pc), aux));
634eea1a2f1SRaphael Zanella           PetscCall(MatSetSizes(aux[0], m, n, PETSC_DETERMINE, PETSC_DETERMINE));
635eea1a2f1SRaphael Zanella           PetscCall(PetscObjectBaseTypeCompare((PetscObject)data->aux, MATSEQAIJ, &flg));
636eea1a2f1SRaphael Zanella           if (flg) PetscCall(MatSetType(aux[0], MATMPIAIJ));
637eea1a2f1SRaphael Zanella           else {
638eea1a2f1SRaphael Zanella             PetscCall(PetscObjectBaseTypeCompare((PetscObject)data->aux, MATSEQBAIJ, &flg));
639eea1a2f1SRaphael Zanella             if (flg) PetscCall(MatSetType(aux[0], MATMPIBAIJ));
640eea1a2f1SRaphael Zanella             else {
641eea1a2f1SRaphael Zanella               PetscCall(PetscObjectBaseTypeCompare((PetscObject)data->aux, MATSEQSBAIJ, &flg));
642eea1a2f1SRaphael Zanella               PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "MatType of auxiliary Mat (%s) is not any of the following: MATSEQAIJ, MATSEQBAIJ, or MATSEQSBAIJ", ((PetscObject)data->aux)->type_name);
643eea1a2f1SRaphael Zanella               PetscCall(MatSetType(aux[0], MATMPISBAIJ));
644eea1a2f1SRaphael Zanella             }
645eea1a2f1SRaphael Zanella           }
646eea1a2f1SRaphael Zanella           PetscCall(MatSetBlockSizesFromMats(aux[0], data->aux, data->aux));
647eea1a2f1SRaphael Zanella           PetscCall(MatAssemblyBegin(aux[0], MAT_FINAL_ASSEMBLY));
648eea1a2f1SRaphael Zanella           PetscCall(MatAssemblyEnd(aux[0], MAT_FINAL_ASSEMBLY));
649eea1a2f1SRaphael Zanella           PetscCall(MatGetDiagonalBlock(aux[0], aux + 1));
650eea1a2f1SRaphael Zanella           PetscCall(MatCopy(data->aux, aux[1], DIFFERENT_NONZERO_PATTERN));
651eea1a2f1SRaphael Zanella           PetscCall(PetscViewerBinaryOpen(PetscObjectComm((PetscObject)pc), std::string(prefix + "_aux_" + std::to_string(size) + (tmp ? ("." + suffix) : "")).c_str(), FILE_MODE_WRITE, &subviewer));
652eea1a2f1SRaphael Zanella           PetscCall(MatView(aux[0], subviewer));
653aa21023fSPierre Jolivet           PetscCall(PetscViewerDestroy(&subviewer));
654eea1a2f1SRaphael Zanella           PetscCall(MatDestroy(aux));
655aa21023fSPierre Jolivet         }
656aa21023fSPierre Jolivet         if (data->is) {
657eea1a2f1SRaphael Zanella           PetscCall(ISGetIndices(data->is, &indices));
658eea1a2f1SRaphael Zanella           PetscCall(ISGetSize(data->is, sizes + 4));
659eea1a2f1SRaphael Zanella           PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)pc), sizes[4], indices, PETSC_USE_POINTER, &is));
660eea1a2f1SRaphael Zanella           PetscCall(PetscViewerBinaryOpen(PetscObjectComm((PetscObject)pc), std::string(prefix + "_is_" + std::to_string(size) + (tmp ? ("." + suffix) : "")).c_str(), FILE_MODE_WRITE, &subviewer));
661eea1a2f1SRaphael Zanella           PetscCall(ISView(is, subviewer));
662aa21023fSPierre Jolivet           PetscCall(PetscViewerDestroy(&subviewer));
663eea1a2f1SRaphael Zanella           PetscCall(ISDestroy(&is));
664eea1a2f1SRaphael Zanella           PetscCall(ISRestoreIndices(data->is, &indices));
665aa21023fSPierre Jolivet         }
666eea1a2f1SRaphael Zanella         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)pc), PETSC_STATIC_ARRAY_LENGTH(sizes), sizes, PETSC_USE_POINTER, &is));
667eea1a2f1SRaphael Zanella         PetscCall(PetscViewerBinaryOpen(PetscObjectComm((PetscObject)pc), std::string(prefix + "_sizes_" + std::to_string(size) + (tmp ? ("." + suffix) : "")).c_str(), FILE_MODE_WRITE, &subviewer));
668aa21023fSPierre Jolivet         PetscCall(ISView(is, subviewer));
669aa21023fSPierre Jolivet         PetscCall(PetscViewerDestroy(&subviewer));
670aa21023fSPierre Jolivet         PetscCall(ISDestroy(&is));
671aa21023fSPierre Jolivet       }
672aa21023fSPierre Jolivet     }
673f1580f4eSBarry Smith   }
6743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
675f1580f4eSBarry Smith }
676f1580f4eSBarry Smith 
677d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCPreSolve_HPDDM(PC pc, KSP ksp, Vec, Vec)
678d71ae5a4SJacob Faibussowitsch {
679f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
680f1580f4eSBarry Smith   Mat       A;
681cdbd50ebSPierre Jolivet   PetscBool flg;
682f1580f4eSBarry Smith 
683f1580f4eSBarry Smith   PetscFunctionBegin;
684f1580f4eSBarry Smith   if (ksp) {
685f1580f4eSBarry Smith     PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPLSQR, &flg));
686f1580f4eSBarry Smith     if (flg && !data->normal) {
687db4a47b3SPierre Jolivet       PetscCall(KSPGetOperators(ksp, &A, nullptr));
688db4a47b3SPierre Jolivet       PetscCall(MatCreateVecs(A, nullptr, &data->normal)); /* temporary Vec used in PCApply_HPDDMShell() for coarse grid corrections */
689cdbd50ebSPierre Jolivet     } else if (!flg) {
690cdbd50ebSPierre Jolivet       PetscCall(PetscObjectTypeCompareAny((PetscObject)ksp, &flg, KSPCG, KSPGROPPCG, KSPPIPECG, KSPPIPECGRR, KSPPIPELCG, KSPPIPEPRCG, KSPPIPECG2, KSPSTCG, KSPFCG, KSPPIPEFCG, KSPMINRES, KSPNASH, KSPSYMMLQ, ""));
691cdbd50ebSPierre Jolivet       if (!flg) {
692cdbd50ebSPierre Jolivet         PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPHPDDM, &flg));
693cdbd50ebSPierre Jolivet         if (flg) {
694cdbd50ebSPierre Jolivet           KSPHPDDMType type;
695811e8887SPierre Jolivet 
696cdbd50ebSPierre Jolivet           PetscCall(KSPHPDDMGetType(ksp, &type));
697cdbd50ebSPierre Jolivet           flg = (type == KSP_HPDDM_TYPE_CG || type == KSP_HPDDM_TYPE_BCG || type == KSP_HPDDM_TYPE_BFBCG ? PETSC_TRUE : PETSC_FALSE);
698cdbd50ebSPierre Jolivet         }
699cdbd50ebSPierre Jolivet       }
700cdbd50ebSPierre Jolivet     }
701cdbd50ebSPierre Jolivet     if (flg) {
702cdbd50ebSPierre Jolivet       if (data->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED) {
703cdbd50ebSPierre Jolivet         PetscCall(PetscOptionsHasName(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, "-pc_hpddm_coarse_correction", &flg));
704cdbd50ebSPierre Jolivet         PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "PCHPDDMCoarseCorrectionType %s is known to be not symmetric, but KSPType %s requires a symmetric PC, if you insist on using this configuration, use the additional option -%spc_hpddm_coarse_correction %s, or alternatively, switch to a symmetric PCHPDDMCoarseCorrectionType such as %s",
705cdbd50ebSPierre Jolivet                    PCHPDDMCoarseCorrectionTypes[data->correction], ((PetscObject)ksp)->type_name, ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", PCHPDDMCoarseCorrectionTypes[data->correction], PCHPDDMCoarseCorrectionTypes[PC_HPDDM_COARSE_CORRECTION_BALANCED]);
706cdbd50ebSPierre Jolivet       }
707cdbd50ebSPierre Jolivet       for (PetscInt n = 0; n < data->N; ++n) {
708cdbd50ebSPierre Jolivet         if (data->levels[n]->pc) {
709cdbd50ebSPierre Jolivet           PetscCall(PetscObjectTypeCompare((PetscObject)data->levels[n]->pc, PCASM, &flg));
710cdbd50ebSPierre Jolivet           if (flg) {
711cdbd50ebSPierre Jolivet             PCASMType type;
712811e8887SPierre Jolivet 
713cdbd50ebSPierre Jolivet             PetscCall(PCASMGetType(data->levels[n]->pc, &type));
714cdbd50ebSPierre Jolivet             if (type == PC_ASM_RESTRICT || type == PC_ASM_INTERPOLATE) {
715cdbd50ebSPierre Jolivet               PetscCall(PetscOptionsHasName(((PetscObject)data->levels[n]->pc)->options, ((PetscObject)data->levels[n]->pc)->prefix, "-pc_asm_type", &flg));
716cdbd50ebSPierre Jolivet               PetscCheck(flg, PetscObjectComm((PetscObject)data->levels[n]->pc), PETSC_ERR_ARG_INCOMP, "PCASMType %s is known to be not symmetric, but KSPType %s requires a symmetric PC, if you insist on using this configuration, use the additional option -%spc_asm_type %s, or alternatively, switch to a symmetric PCASMType such as %s", PCASMTypes[type],
717cdbd50ebSPierre Jolivet                          ((PetscObject)ksp)->type_name, ((PetscObject)data->levels[n]->pc)->prefix, PCASMTypes[type], PCASMTypes[PC_ASM_BASIC]);
718cdbd50ebSPierre Jolivet             }
719cdbd50ebSPierre Jolivet           }
720cdbd50ebSPierre Jolivet         }
721cdbd50ebSPierre Jolivet       }
722f1580f4eSBarry Smith     }
723f1580f4eSBarry Smith   }
7243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
725f1580f4eSBarry Smith }
726f1580f4eSBarry Smith 
727d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCSetUp_HPDDMShell(PC pc)
728d71ae5a4SJacob Faibussowitsch {
729f1580f4eSBarry Smith   PC_HPDDM_Level *ctx;
730f1580f4eSBarry Smith   Mat             A, P;
731f1580f4eSBarry Smith   Vec             x;
732f1580f4eSBarry Smith   const char     *pcpre;
733f1580f4eSBarry Smith 
734f1580f4eSBarry Smith   PetscFunctionBegin;
735f1580f4eSBarry Smith   PetscCall(PCShellGetContext(pc, &ctx));
736f1580f4eSBarry Smith   PetscCall(KSPGetOptionsPrefix(ctx->ksp, &pcpre));
737f1580f4eSBarry Smith   PetscCall(KSPGetOperators(ctx->ksp, &A, &P));
738f1580f4eSBarry Smith   /* smoother */
739f1580f4eSBarry Smith   PetscCall(PCSetOptionsPrefix(ctx->pc, pcpre));
740f1580f4eSBarry Smith   PetscCall(PCSetOperators(ctx->pc, A, P));
741f1580f4eSBarry Smith   if (!ctx->v[0]) {
742f1580f4eSBarry Smith     PetscCall(VecDuplicateVecs(ctx->D, 1, &ctx->v[0]));
743f1580f4eSBarry Smith     if (!std::is_same<PetscScalar, PetscReal>::value) PetscCall(VecDestroy(&ctx->D));
744db4a47b3SPierre Jolivet     PetscCall(MatCreateVecs(A, &x, nullptr));
745f1580f4eSBarry Smith     PetscCall(VecDuplicateVecs(x, 2, &ctx->v[1]));
746f1580f4eSBarry Smith     PetscCall(VecDestroy(&x));
747f1580f4eSBarry Smith   }
748f1580f4eSBarry Smith   std::fill_n(ctx->V, 3, nullptr);
7493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
750f1580f4eSBarry Smith }
751f1580f4eSBarry Smith 
752f1580f4eSBarry Smith template <class Type, typename std::enable_if<std::is_same<Type, Vec>::value>::type * = nullptr>
753d71ae5a4SJacob Faibussowitsch static inline PetscErrorCode PCHPDDMDeflate_Private(PC pc, Type x, Type y)
754d71ae5a4SJacob Faibussowitsch {
755f1580f4eSBarry Smith   PC_HPDDM_Level *ctx;
756f1580f4eSBarry Smith   PetscScalar    *out;
757f1580f4eSBarry Smith 
758f1580f4eSBarry Smith   PetscFunctionBegin;
759f1580f4eSBarry Smith   PetscCall(PCShellGetContext(pc, &ctx));
760f1580f4eSBarry Smith   /* going from PETSc to HPDDM numbering */
761f1580f4eSBarry Smith   PetscCall(VecScatterBegin(ctx->scatter, x, ctx->v[0][0], INSERT_VALUES, SCATTER_FORWARD));
762f1580f4eSBarry Smith   PetscCall(VecScatterEnd(ctx->scatter, x, ctx->v[0][0], INSERT_VALUES, SCATTER_FORWARD));
763f1580f4eSBarry Smith   PetscCall(VecGetArrayWrite(ctx->v[0][0], &out));
764db4a47b3SPierre Jolivet   ctx->P->deflation<false>(nullptr, out, 1); /* y = Q x */
765f1580f4eSBarry Smith   PetscCall(VecRestoreArrayWrite(ctx->v[0][0], &out));
766f1580f4eSBarry Smith   /* going from HPDDM to PETSc numbering */
767f1580f4eSBarry Smith   PetscCall(VecScatterBegin(ctx->scatter, ctx->v[0][0], y, INSERT_VALUES, SCATTER_REVERSE));
768f1580f4eSBarry Smith   PetscCall(VecScatterEnd(ctx->scatter, ctx->v[0][0], y, INSERT_VALUES, SCATTER_REVERSE));
7693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
770f1580f4eSBarry Smith }
771f1580f4eSBarry Smith 
772f1580f4eSBarry Smith template <class Type, typename std::enable_if<std::is_same<Type, Mat>::value>::type * = nullptr>
773d71ae5a4SJacob Faibussowitsch static inline PetscErrorCode PCHPDDMDeflate_Private(PC pc, Type X, Type Y)
774d71ae5a4SJacob Faibussowitsch {
775f1580f4eSBarry Smith   PC_HPDDM_Level *ctx;
776f1580f4eSBarry Smith   Vec             vX, vY, vC;
777f1580f4eSBarry Smith   PetscScalar    *out;
778811e8887SPierre Jolivet   PetscInt        N;
779f1580f4eSBarry Smith 
780f1580f4eSBarry Smith   PetscFunctionBegin;
781f1580f4eSBarry Smith   PetscCall(PCShellGetContext(pc, &ctx));
782db4a47b3SPierre Jolivet   PetscCall(MatGetSize(X, nullptr, &N));
783f1580f4eSBarry Smith   /* going from PETSc to HPDDM numbering */
784811e8887SPierre Jolivet   for (PetscInt i = 0; i < N; ++i) {
785f1580f4eSBarry Smith     PetscCall(MatDenseGetColumnVecRead(X, i, &vX));
786f1580f4eSBarry Smith     PetscCall(MatDenseGetColumnVecWrite(ctx->V[0], i, &vC));
787f1580f4eSBarry Smith     PetscCall(VecScatterBegin(ctx->scatter, vX, vC, INSERT_VALUES, SCATTER_FORWARD));
788f1580f4eSBarry Smith     PetscCall(VecScatterEnd(ctx->scatter, vX, vC, INSERT_VALUES, SCATTER_FORWARD));
789f1580f4eSBarry Smith     PetscCall(MatDenseRestoreColumnVecWrite(ctx->V[0], i, &vC));
790f1580f4eSBarry Smith     PetscCall(MatDenseRestoreColumnVecRead(X, i, &vX));
791f1580f4eSBarry Smith   }
792f1580f4eSBarry Smith   PetscCall(MatDenseGetArrayWrite(ctx->V[0], &out));
793db4a47b3SPierre Jolivet   ctx->P->deflation<false>(nullptr, out, N); /* Y = Q X */
794f1580f4eSBarry Smith   PetscCall(MatDenseRestoreArrayWrite(ctx->V[0], &out));
795f1580f4eSBarry Smith   /* going from HPDDM to PETSc numbering */
796811e8887SPierre Jolivet   for (PetscInt i = 0; i < N; ++i) {
797f1580f4eSBarry Smith     PetscCall(MatDenseGetColumnVecRead(ctx->V[0], i, &vC));
798f1580f4eSBarry Smith     PetscCall(MatDenseGetColumnVecWrite(Y, i, &vY));
799f1580f4eSBarry Smith     PetscCall(VecScatterBegin(ctx->scatter, vC, vY, INSERT_VALUES, SCATTER_REVERSE));
800f1580f4eSBarry Smith     PetscCall(VecScatterEnd(ctx->scatter, vC, vY, INSERT_VALUES, SCATTER_REVERSE));
801f1580f4eSBarry Smith     PetscCall(MatDenseRestoreColumnVecWrite(Y, i, &vY));
802f1580f4eSBarry Smith     PetscCall(MatDenseRestoreColumnVecRead(ctx->V[0], i, &vC));
803f1580f4eSBarry Smith   }
8043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
805f1580f4eSBarry Smith }
806f1580f4eSBarry Smith 
807f1580f4eSBarry Smith /*
808aa1539e9SPierre Jolivet      PCApply_HPDDMShell - Applies a (2) deflated, (1) additive, (3) balanced, or (4) no coarse correction. In what follows, E = Z Pmat Z^T and Q = Z^T E^-1 Z.
809f1580f4eSBarry Smith 
810f1580f4eSBarry Smith .vb
811f1580f4eSBarry Smith    (1) y =                Pmat^-1              x + Q x,
812f1580f4eSBarry Smith    (2) y =                Pmat^-1 (I - Amat Q) x + Q x (default),
813aa1539e9SPierre Jolivet    (3) y = (I - Q Amat^T) Pmat^-1 (I - Amat Q) x + Q x,
814aa1539e9SPierre Jolivet    (4) y =                Pmat^-1              x      .
815f1580f4eSBarry Smith .ve
816f1580f4eSBarry Smith 
817f1580f4eSBarry Smith    Input Parameters:
818f1580f4eSBarry Smith +     pc - preconditioner context
819f1580f4eSBarry Smith -     x - input vector
820f1580f4eSBarry Smith 
821f1580f4eSBarry Smith    Output Parameter:
822f1580f4eSBarry Smith .     y - output vector
823f1580f4eSBarry Smith 
824f1580f4eSBarry Smith    Notes:
825f1580f4eSBarry Smith      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.
826f1580f4eSBarry Smith      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.
827f1580f4eSBarry Smith      (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.
828f1580f4eSBarry Smith 
829f1580f4eSBarry Smith    Level: advanced
830f1580f4eSBarry Smith 
831f1580f4eSBarry Smith    Developer Note:
832f1580f4eSBarry Smith    Since this is not an actual manual page the material below should be moved to an appropriate manual page with the appropriate context, i.e. explaining when it is used and how
833f1580f4eSBarry Smith    to trigger it. Likely the manual page is `PCHPDDM`
834f1580f4eSBarry Smith 
835562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMCoarseCorrectionType`
836f1580f4eSBarry Smith */
837d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCApply_HPDDMShell(PC pc, Vec x, Vec y)
838d71ae5a4SJacob Faibussowitsch {
839f1580f4eSBarry Smith   PC_HPDDM_Level *ctx;
840f1580f4eSBarry Smith   Mat             A;
841f1580f4eSBarry Smith 
842f1580f4eSBarry Smith   PetscFunctionBegin;
843f1580f4eSBarry Smith   PetscCall(PCShellGetContext(pc, &ctx));
844f1580f4eSBarry Smith   PetscCheck(ctx->P, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
845db4a47b3SPierre Jolivet   PetscCall(KSPGetOperators(ctx->ksp, &A, nullptr));
846aa1539e9SPierre Jolivet   if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_NONE) PetscCall(PCApply(ctx->pc, x, y)); /* y = M^-1 x */
847aa1539e9SPierre Jolivet   else {
848f1580f4eSBarry Smith     PetscCall(PCHPDDMDeflate_Private(pc, x, y)); /* y = Q x */
849f1580f4eSBarry Smith     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
850f1580f4eSBarry Smith       if (!ctx->parent->normal || ctx != ctx->parent->levels[0]) PetscCall(MatMult(A, y, ctx->v[1][0])); /* y = A Q x     */
851f1580f4eSBarry Smith       else { /* KSPLSQR and finest level */ PetscCall(MatMult(A, y, ctx->parent->normal));               /* y = A Q x     */
852f1580f4eSBarry Smith         PetscCall(MatMultHermitianTranspose(A, ctx->parent->normal, ctx->v[1][0]));                      /* y = A^T A Q x */
853f1580f4eSBarry Smith       }
854f1580f4eSBarry Smith       PetscCall(VecWAXPY(ctx->v[1][1], -1.0, ctx->v[1][0], x)); /* y = (I - A Q) x                             */
855f1580f4eSBarry Smith       PetscCall(PCApply(ctx->pc, ctx->v[1][1], ctx->v[1][0]));  /* y = M^-1 (I - A Q) x                        */
856f1580f4eSBarry Smith       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
857f1580f4eSBarry Smith         if (!ctx->parent->normal || ctx != ctx->parent->levels[0]) PetscCall(MatMultHermitianTranspose(A, ctx->v[1][0], ctx->v[1][1])); /* z = A^T y */
858f1580f4eSBarry Smith         else {
859f1580f4eSBarry Smith           PetscCall(MatMult(A, ctx->v[1][0], ctx->parent->normal));
860f1580f4eSBarry Smith           PetscCall(MatMultHermitianTranspose(A, ctx->parent->normal, ctx->v[1][1])); /* z = A^T A y           */
861f1580f4eSBarry Smith         }
862f1580f4eSBarry Smith         PetscCall(PCHPDDMDeflate_Private(pc, ctx->v[1][1], ctx->v[1][1]));
863f1580f4eSBarry Smith         PetscCall(VecAXPBYPCZ(y, -1.0, 1.0, 1.0, ctx->v[1][1], ctx->v[1][0])); /* y = (I - Q A^T) y + Q x      */
864f1580f4eSBarry Smith       } else PetscCall(VecAXPY(y, 1.0, ctx->v[1][0]));                         /* y = Q M^-1 (I - A Q) x + Q x */
865f1580f4eSBarry Smith     } else {
866f1580f4eSBarry Smith       PetscCheck(ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
867f1580f4eSBarry Smith       PetscCall(PCApply(ctx->pc, x, ctx->v[1][0]));
868f1580f4eSBarry Smith       PetscCall(VecAXPY(y, 1.0, ctx->v[1][0])); /* y = M^-1 x + Q x */
869f1580f4eSBarry Smith     }
870aa1539e9SPierre Jolivet   }
8713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
872f1580f4eSBarry Smith }
873f1580f4eSBarry Smith 
874f1580f4eSBarry Smith /*
875f1580f4eSBarry Smith      PCMatApply_HPDDMShell - Variant of PCApply_HPDDMShell() for blocks of vectors.
876f1580f4eSBarry Smith 
877f1580f4eSBarry Smith    Input Parameters:
878f1580f4eSBarry Smith +     pc - preconditioner context
879f1580f4eSBarry Smith -     X - block of input vectors
880f1580f4eSBarry Smith 
881f1580f4eSBarry Smith    Output Parameter:
882f1580f4eSBarry Smith .     Y - block of output vectors
883f1580f4eSBarry Smith 
884f1580f4eSBarry Smith    Level: advanced
885f1580f4eSBarry Smith 
886562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCApply_HPDDMShell()`, `PCHPDDMCoarseCorrectionType`
887f1580f4eSBarry Smith */
888d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCMatApply_HPDDMShell(PC pc, Mat X, Mat Y)
889d71ae5a4SJacob Faibussowitsch {
890f1580f4eSBarry Smith   PC_HPDDM_Level *ctx;
891f1580f4eSBarry Smith   Mat             A, *ptr;
892db4a47b3SPierre Jolivet   PetscContainer  container = nullptr;
893f1580f4eSBarry Smith   PetscScalar    *array;
894f1580f4eSBarry Smith   PetscInt        m, M, N, prev = 0;
895f1580f4eSBarry Smith   PetscBool       reset = PETSC_FALSE;
896f1580f4eSBarry Smith 
897f1580f4eSBarry Smith   PetscFunctionBegin;
898f1580f4eSBarry Smith   PetscCall(PCShellGetContext(pc, &ctx));
899f1580f4eSBarry Smith   PetscCheck(ctx->P, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
900db4a47b3SPierre Jolivet   PetscCall(MatGetSize(X, nullptr, &N));
901db4a47b3SPierre Jolivet   PetscCall(KSPGetOperators(ctx->ksp, &A, nullptr));
902aa1539e9SPierre Jolivet   if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_NONE) PetscCall(PCMatApply(ctx->pc, X, Y));
903aa1539e9SPierre Jolivet   else {
904f1580f4eSBarry Smith     PetscCall(PetscObjectQuery((PetscObject)A, "_HPDDM_MatProduct", (PetscObject *)&container));
905f1580f4eSBarry Smith     if (container) { /* MatProduct container already attached */
906f1580f4eSBarry Smith       PetscCall(PetscContainerGetPointer(container, (void **)&ptr));
907f1580f4eSBarry Smith       if (ptr[1] != ctx->V[2]) /* Mat has changed or may have been set first in KSPHPDDM */
908f1580f4eSBarry Smith         for (m = 0; m < 2; ++m) {
909f1580f4eSBarry Smith           PetscCall(MatDestroy(ctx->V + m + 1));
910f1580f4eSBarry Smith           ctx->V[m + 1] = ptr[m];
911f1580f4eSBarry Smith           PetscCall(PetscObjectReference((PetscObject)ctx->V[m + 1]));
912f1580f4eSBarry Smith         }
913f1580f4eSBarry Smith     }
914db4a47b3SPierre Jolivet     if (ctx->V[1]) PetscCall(MatGetSize(ctx->V[1], nullptr, &prev));
915f1580f4eSBarry Smith     if (N != prev || !ctx->V[0]) {
916f1580f4eSBarry Smith       PetscCall(MatDestroy(ctx->V));
917f1580f4eSBarry Smith       PetscCall(VecGetLocalSize(ctx->v[0][0], &m));
918db4a47b3SPierre Jolivet       PetscCall(MatCreateDense(PetscObjectComm((PetscObject)pc), m, PETSC_DECIDE, PETSC_DECIDE, N, nullptr, ctx->V));
919f1580f4eSBarry Smith       if (N != prev) {
920f1580f4eSBarry Smith         PetscCall(MatDestroy(ctx->V + 1));
921f1580f4eSBarry Smith         PetscCall(MatDestroy(ctx->V + 2));
922db4a47b3SPierre Jolivet         PetscCall(MatGetLocalSize(X, &m, nullptr));
923db4a47b3SPierre Jolivet         PetscCall(MatGetSize(X, &M, nullptr));
924f1580f4eSBarry Smith         if (ctx->parent->correction != PC_HPDDM_COARSE_CORRECTION_BALANCED) PetscCall(MatDenseGetArrayWrite(ctx->V[0], &array));
925db4a47b3SPierre Jolivet         else array = nullptr;
926f1580f4eSBarry Smith         PetscCall(MatCreateDense(PetscObjectComm((PetscObject)pc), m, PETSC_DECIDE, M, N, array, ctx->V + 1));
927f1580f4eSBarry Smith         if (ctx->parent->correction != PC_HPDDM_COARSE_CORRECTION_BALANCED) PetscCall(MatDenseRestoreArrayWrite(ctx->V[0], &array));
928db4a47b3SPierre Jolivet         PetscCall(MatCreateDense(PetscObjectComm((PetscObject)pc), m, PETSC_DECIDE, M, N, nullptr, ctx->V + 2));
929db4a47b3SPierre Jolivet         PetscCall(MatProductCreateWithMat(A, Y, nullptr, ctx->V[1]));
930f1580f4eSBarry Smith         PetscCall(MatProductSetType(ctx->V[1], MATPRODUCT_AB));
931f1580f4eSBarry Smith         PetscCall(MatProductSetFromOptions(ctx->V[1]));
932f1580f4eSBarry Smith         PetscCall(MatProductSymbolic(ctx->V[1]));
933715c1178SPierre Jolivet         if (!container) PetscCall(PetscObjectContainerCompose((PetscObject)A, "_HPDDM_MatProduct", ctx->V + 1, nullptr)); /* no MatProduct container attached, create one to be queried in KSPHPDDM or at the next call to PCMatApply() */
934715c1178SPierre Jolivet         else PetscCall(PetscContainerSetPointer(container, ctx->V + 1));                                                  /* need to compose B and D from MatProductCreateWithMat(A, B, NULL, D), which are stored in the contiguous array ctx->V */
935f1580f4eSBarry Smith       }
936f1580f4eSBarry Smith       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
937db4a47b3SPierre Jolivet         PetscCall(MatProductCreateWithMat(A, ctx->V[1], nullptr, ctx->V[2]));
938f1580f4eSBarry Smith         PetscCall(MatProductSetType(ctx->V[2], MATPRODUCT_AtB));
939f1580f4eSBarry Smith         PetscCall(MatProductSetFromOptions(ctx->V[2]));
940f1580f4eSBarry Smith         PetscCall(MatProductSymbolic(ctx->V[2]));
941f1580f4eSBarry Smith       }
942f1580f4eSBarry Smith       ctx->P->start(N);
943f1580f4eSBarry Smith     }
944f1580f4eSBarry Smith     if (N == prev || container) { /* when MatProduct container is attached, always need to MatProductReplaceMats() since KSPHPDDM may have replaced the Mat as well */
945db4a47b3SPierre Jolivet       PetscCall(MatProductReplaceMats(nullptr, Y, nullptr, ctx->V[1]));
946f1580f4eSBarry Smith       if (container && ctx->parent->correction != PC_HPDDM_COARSE_CORRECTION_BALANCED) {
947f1580f4eSBarry Smith         PetscCall(MatDenseGetArrayWrite(ctx->V[0], &array));
948f1580f4eSBarry Smith         PetscCall(MatDensePlaceArray(ctx->V[1], array));
949f1580f4eSBarry Smith         PetscCall(MatDenseRestoreArrayWrite(ctx->V[0], &array));
950f1580f4eSBarry Smith         reset = PETSC_TRUE;
951f1580f4eSBarry Smith       }
952f1580f4eSBarry Smith     }
953f1580f4eSBarry Smith     PetscCall(PCHPDDMDeflate_Private(pc, X, Y));
954f1580f4eSBarry Smith     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
955f1580f4eSBarry Smith       PetscCall(MatProductNumeric(ctx->V[1]));
956f1580f4eSBarry Smith       PetscCall(MatCopy(ctx->V[1], ctx->V[2], SAME_NONZERO_PATTERN));
957f1580f4eSBarry Smith       PetscCall(MatAXPY(ctx->V[2], -1.0, X, SAME_NONZERO_PATTERN));
958f1580f4eSBarry Smith       PetscCall(PCMatApply(ctx->pc, ctx->V[2], ctx->V[1]));
959f1580f4eSBarry Smith       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
960f1580f4eSBarry Smith         PetscCall(MatProductNumeric(ctx->V[2]));
961f1580f4eSBarry Smith         PetscCall(PCHPDDMDeflate_Private(pc, ctx->V[2], ctx->V[2]));
962f1580f4eSBarry Smith         PetscCall(MatAXPY(ctx->V[1], -1.0, ctx->V[2], SAME_NONZERO_PATTERN));
963f1580f4eSBarry Smith       }
964f1580f4eSBarry Smith       PetscCall(MatAXPY(Y, -1.0, ctx->V[1], SAME_NONZERO_PATTERN));
965f1580f4eSBarry Smith     } else {
966f1580f4eSBarry Smith       PetscCheck(ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
967f1580f4eSBarry Smith       PetscCall(PCMatApply(ctx->pc, X, ctx->V[1]));
968f1580f4eSBarry Smith       PetscCall(MatAXPY(Y, 1.0, ctx->V[1], SAME_NONZERO_PATTERN));
969f1580f4eSBarry Smith     }
970f1580f4eSBarry Smith     if (reset) PetscCall(MatDenseResetArray(ctx->V[1]));
971aa1539e9SPierre Jolivet   }
9723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
973f1580f4eSBarry Smith }
974f1580f4eSBarry Smith 
975d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCDestroy_HPDDMShell(PC pc)
976d71ae5a4SJacob Faibussowitsch {
977f1580f4eSBarry Smith   PC_HPDDM_Level *ctx;
978f1580f4eSBarry Smith 
979f1580f4eSBarry Smith   PetscFunctionBegin;
980f1580f4eSBarry Smith   PetscCall(PCShellGetContext(pc, &ctx));
981f1580f4eSBarry Smith   PetscCall(HPDDM::Schwarz<PetscScalar>::destroy(ctx, PETSC_TRUE));
982f1580f4eSBarry Smith   PetscCall(VecDestroyVecs(1, &ctx->v[0]));
983f1580f4eSBarry Smith   PetscCall(VecDestroyVecs(2, &ctx->v[1]));
984f4f49eeaSPierre Jolivet   PetscCall(PetscObjectCompose((PetscObject)ctx->pc->mat, "_HPDDM_MatProduct", nullptr));
985f1580f4eSBarry Smith   PetscCall(MatDestroy(ctx->V));
986f1580f4eSBarry Smith   PetscCall(MatDestroy(ctx->V + 1));
987f1580f4eSBarry Smith   PetscCall(MatDestroy(ctx->V + 2));
988f1580f4eSBarry Smith   PetscCall(VecDestroy(&ctx->D));
98901e3c840SPierre Jolivet   PetscCall(PetscSFDestroy(&ctx->scatter));
990f1580f4eSBarry Smith   PetscCall(PCDestroy(&ctx->pc));
9913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
992f1580f4eSBarry Smith }
993f1580f4eSBarry Smith 
9949bb5c669SPierre Jolivet template <class Type, bool T = false, typename std::enable_if<std::is_same<Type, Vec>::value>::type * = nullptr>
9959bb5c669SPierre Jolivet static inline PetscErrorCode PCApply_Schur_Private(std::tuple<KSP, IS, Vec[2]> *p, PC factor, Type x, Type y)
9969bb5c669SPierre Jolivet {
9979bb5c669SPierre Jolivet   PetscFunctionBegin;
9989bb5c669SPierre Jolivet   PetscCall(VecISCopy(std::get<2>(*p)[0], std::get<1>(*p), SCATTER_FORWARD, x));
9999bb5c669SPierre Jolivet   if (!T) PetscCall(PCApply(factor, std::get<2>(*p)[0], std::get<2>(*p)[1]));
10009bb5c669SPierre Jolivet   else PetscCall(PCApplyTranspose(factor, std::get<2>(*p)[0], std::get<2>(*p)[1]));
10019bb5c669SPierre Jolivet   PetscCall(VecISCopy(std::get<2>(*p)[1], std::get<1>(*p), SCATTER_REVERSE, y));
10029bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
10039bb5c669SPierre Jolivet }
10049bb5c669SPierre Jolivet 
10059bb5c669SPierre Jolivet template <class Type, bool = false, typename std::enable_if<std::is_same<Type, Mat>::value>::type * = nullptr>
10069bb5c669SPierre Jolivet static inline PetscErrorCode PCApply_Schur_Private(std::tuple<KSP, IS, Vec[2]> *p, PC factor, Type X, Type Y)
10079bb5c669SPierre Jolivet {
10089bb5c669SPierre Jolivet   Mat B[2];
10099bb5c669SPierre Jolivet   Vec x, y;
10109bb5c669SPierre Jolivet 
10119bb5c669SPierre Jolivet   PetscFunctionBegin;
10129bb5c669SPierre Jolivet   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, factor->mat->rmap->n, X->cmap->n, nullptr, B));
10139bb5c669SPierre Jolivet   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, factor->mat->rmap->n, X->cmap->n, nullptr, B + 1));
10149bb5c669SPierre Jolivet   for (PetscInt i = 0; i < X->cmap->n; ++i) {
10159bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecRead(X, i, &x));
10169bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecWrite(B[0], i, &y));
10179bb5c669SPierre Jolivet     PetscCall(VecISCopy(y, std::get<1>(*p), SCATTER_FORWARD, x));
10189bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecWrite(B[0], i, &y));
10199bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecRead(X, i, &x));
10209bb5c669SPierre Jolivet   }
10219bb5c669SPierre Jolivet   PetscCall(PCMatApply(factor, B[0], B[1]));
10229bb5c669SPierre Jolivet   PetscCall(MatDestroy(B));
10239bb5c669SPierre Jolivet   for (PetscInt i = 0; i < X->cmap->n; ++i) {
10249bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecRead(B[1], i, &x));
10259bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecWrite(Y, i, &y));
10269bb5c669SPierre Jolivet     PetscCall(VecISCopy(x, std::get<1>(*p), SCATTER_REVERSE, y));
10279bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecWrite(Y, i, &y));
10289bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecRead(B[1], i, &x));
10299bb5c669SPierre Jolivet   }
10309bb5c669SPierre Jolivet   PetscCall(MatDestroy(B + 1));
10319bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
10329bb5c669SPierre Jolivet }
10339bb5c669SPierre Jolivet 
10349bb5c669SPierre Jolivet template <class Type = Vec, bool T = false>
10359bb5c669SPierre Jolivet static PetscErrorCode PCApply_Schur(PC pc, Type x, Type y)
10369bb5c669SPierre Jolivet {
10379bb5c669SPierre Jolivet   PC                           factor;
10389bb5c669SPierre Jolivet   Mat                          A;
10399bb5c669SPierre Jolivet   MatSolverType                type;
10409bb5c669SPierre Jolivet   PetscBool                    flg;
10419bb5c669SPierre Jolivet   std::tuple<KSP, IS, Vec[2]> *p;
10429bb5c669SPierre Jolivet 
10439bb5c669SPierre Jolivet   PetscFunctionBegin;
10449bb5c669SPierre Jolivet   PetscCall(PCShellGetContext(pc, &p));
10459bb5c669SPierre Jolivet   PetscCall(KSPGetPC(std::get<0>(*p), &factor));
10469bb5c669SPierre Jolivet   PetscCall(PCFactorGetMatSolverType(factor, &type));
10479bb5c669SPierre Jolivet   PetscCall(PCFactorGetMatrix(factor, &A));
10489bb5c669SPierre Jolivet   PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
10499bb5c669SPierre Jolivet   if (flg) {
10509bb5c669SPierre Jolivet     PetscCheck(PetscDefined(HAVE_MUMPS), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Inconsistent MatSolverType");
10519bb5c669SPierre Jolivet #if PetscDefined(HAVE_MUMPS)
10529bb5c669SPierre Jolivet     PetscCall(MatMumpsSetIcntl(A, 26, 0));
10539bb5c669SPierre Jolivet #endif
10549bb5c669SPierre Jolivet   } else {
10559bb5c669SPierre Jolivet     PetscCall(PetscStrcmp(type, MATSOLVERMKL_PARDISO, &flg));
10569bb5c669SPierre Jolivet     PetscCheck(flg && PetscDefined(HAVE_MKL_PARDISO), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Inconsistent MatSolverType");
10579bb5c669SPierre Jolivet     flg = PETSC_FALSE;
10589bb5c669SPierre Jolivet #if PetscDefined(HAVE_MKL_PARDISO)
10599bb5c669SPierre Jolivet     PetscCall(MatMkl_PardisoSetCntl(A, 70, 1));
10609bb5c669SPierre Jolivet #endif
10619bb5c669SPierre Jolivet   }
10629bb5c669SPierre Jolivet   PetscCall(PCApply_Schur_Private<Type, T>(p, factor, x, y));
10639bb5c669SPierre Jolivet   if (flg) {
10649bb5c669SPierre Jolivet #if PetscDefined(HAVE_MUMPS)
10659bb5c669SPierre Jolivet     PetscCall(MatMumpsSetIcntl(A, 26, -1));
10669bb5c669SPierre Jolivet #endif
10679bb5c669SPierre Jolivet   } else {
10689bb5c669SPierre Jolivet #if PetscDefined(HAVE_MKL_PARDISO)
10699bb5c669SPierre Jolivet     PetscCall(MatMkl_PardisoSetCntl(A, 70, 0));
10709bb5c669SPierre Jolivet #endif
10719bb5c669SPierre Jolivet   }
10729bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
10739bb5c669SPierre Jolivet }
10749bb5c669SPierre Jolivet 
10759bb5c669SPierre Jolivet static PetscErrorCode PCDestroy_Schur(PC pc)
10769bb5c669SPierre Jolivet {
10779bb5c669SPierre Jolivet   std::tuple<KSP, IS, Vec[2]> *p;
10789bb5c669SPierre Jolivet 
10799bb5c669SPierre Jolivet   PetscFunctionBegin;
10809bb5c669SPierre Jolivet   PetscCall(PCShellGetContext(pc, &p));
10819bb5c669SPierre Jolivet   PetscCall(ISDestroy(&std::get<1>(*p)));
10829bb5c669SPierre Jolivet   PetscCall(VecDestroy(std::get<2>(*p)));
10839bb5c669SPierre Jolivet   PetscCall(VecDestroy(std::get<2>(*p) + 1));
10849bb5c669SPierre Jolivet   PetscCall(PetscFree(p));
10859bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
10869bb5c669SPierre Jolivet }
10879bb5c669SPierre Jolivet 
1088d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMSolve_Private(const PC_HPDDM_Level *ctx, PetscScalar *rhs, const unsigned short &mu)
1089d71ae5a4SJacob Faibussowitsch {
1090f1580f4eSBarry Smith   Mat      B, X;
1091f1580f4eSBarry Smith   PetscInt n, N, j = 0;
1092f1580f4eSBarry Smith 
1093f1580f4eSBarry Smith   PetscFunctionBegin;
1094db4a47b3SPierre Jolivet   PetscCall(KSPGetOperators(ctx->ksp, &B, nullptr));
1095db4a47b3SPierre Jolivet   PetscCall(MatGetLocalSize(B, &n, nullptr));
1096db4a47b3SPierre Jolivet   PetscCall(MatGetSize(B, &N, nullptr));
1097f1580f4eSBarry Smith   if (ctx->parent->log_separate) {
1098f1580f4eSBarry Smith     j = std::distance(ctx->parent->levels, std::find(ctx->parent->levels, ctx->parent->levels + ctx->parent->N, ctx));
1099db4a47b3SPierre Jolivet     PetscCall(PetscLogEventBegin(PC_HPDDM_Solve[j], ctx->ksp, nullptr, nullptr, nullptr));
1100f1580f4eSBarry Smith   }
1101f1580f4eSBarry Smith   if (mu == 1) {
1102f1580f4eSBarry Smith     if (!ctx->ksp->vec_rhs) {
1103db4a47b3SPierre Jolivet       PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)ctx->ksp), 1, n, N, nullptr, &ctx->ksp->vec_rhs));
1104f1580f4eSBarry Smith       PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)ctx->ksp), n, N, &ctx->ksp->vec_sol));
1105f1580f4eSBarry Smith     }
1106f1580f4eSBarry Smith     PetscCall(VecPlaceArray(ctx->ksp->vec_rhs, rhs));
1107db4a47b3SPierre Jolivet     PetscCall(KSPSolve(ctx->ksp, nullptr, nullptr));
1108f1580f4eSBarry Smith     PetscCall(VecCopy(ctx->ksp->vec_sol, ctx->ksp->vec_rhs));
1109f1580f4eSBarry Smith     PetscCall(VecResetArray(ctx->ksp->vec_rhs));
1110f1580f4eSBarry Smith   } else {
1111f1580f4eSBarry Smith     PetscCall(MatCreateDense(PetscObjectComm((PetscObject)ctx->ksp), n, PETSC_DECIDE, N, mu, rhs, &B));
1112db4a47b3SPierre Jolivet     PetscCall(MatCreateDense(PetscObjectComm((PetscObject)ctx->ksp), n, PETSC_DECIDE, N, mu, nullptr, &X));
1113f1580f4eSBarry Smith     PetscCall(KSPMatSolve(ctx->ksp, B, X));
1114f1580f4eSBarry Smith     PetscCall(MatCopy(X, B, SAME_NONZERO_PATTERN));
1115f1580f4eSBarry Smith     PetscCall(MatDestroy(&X));
1116f1580f4eSBarry Smith     PetscCall(MatDestroy(&B));
1117f1580f4eSBarry Smith   }
1118db4a47b3SPierre Jolivet   if (ctx->parent->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_Solve[j], ctx->ksp, nullptr, nullptr, nullptr));
11193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1120f1580f4eSBarry Smith }
1121f1580f4eSBarry Smith 
1122d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMSetUpNeumannOverlap_Private(PC pc)
1123d71ae5a4SJacob Faibussowitsch {
1124f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
1125f1580f4eSBarry Smith 
1126f1580f4eSBarry Smith   PetscFunctionBegin;
1127f1580f4eSBarry Smith   if (data->setup) {
1128f1580f4eSBarry Smith     Mat       P;
1129db4a47b3SPierre Jolivet     Vec       x, xt = nullptr;
1130f1580f4eSBarry Smith     PetscReal t = 0.0, s = 0.0;
1131f1580f4eSBarry Smith 
1132db4a47b3SPierre Jolivet     PetscCall(PCGetOperators(pc, nullptr, &P));
1133f1580f4eSBarry Smith     PetscCall(PetscObjectQuery((PetscObject)P, "__SNES_latest_X", (PetscObject *)&x));
1134f1580f4eSBarry Smith     PetscCallBack("PCHPDDM Neumann callback", (*data->setup)(data->aux, t, x, xt, s, data->is, data->setup_ctx));
1135f1580f4eSBarry Smith   }
11363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1137f1580f4eSBarry Smith }
1138f1580f4eSBarry Smith 
1139d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMCreateSubMatrices_Private(Mat mat, PetscInt n, const IS *, const IS *, MatReuse scall, Mat *submat[])
1140d71ae5a4SJacob Faibussowitsch {
1141f1580f4eSBarry Smith   Mat       A;
114213044ca3SPierre Jolivet   PetscBool flg;
1143f1580f4eSBarry Smith 
1144f1580f4eSBarry Smith   PetscFunctionBegin;
1145f1580f4eSBarry Smith   PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MatCreateSubMatrices() called to extract %" PetscInt_FMT " submatrices, which is different than 1", n);
1146f1580f4eSBarry Smith   /* previously composed Mat */
1147f1580f4eSBarry Smith   PetscCall(PetscObjectQuery((PetscObject)mat, "_PCHPDDM_SubMatrices", (PetscObject *)&A));
1148f1580f4eSBarry Smith   PetscCheck(A, PETSC_COMM_SELF, PETSC_ERR_PLIB, "SubMatrices not found in Mat");
114913044ca3SPierre Jolivet   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSCHURCOMPLEMENT, &flg)); /* MATSCHURCOMPLEMENT has neither a MatDuplicate() nor a MatCopy() implementation */
1150f1580f4eSBarry Smith   if (scall == MAT_INITIAL_MATRIX) {
11516f2c871aSStefano Zampini     PetscCall(PetscCalloc1(2, submat)); /* allocate an extra Mat to avoid errors in MatDestroySubMatrices_Dummy() */
115213044ca3SPierre Jolivet     if (!flg) PetscCall(MatDuplicate(A, MAT_COPY_VALUES, *submat));
115313044ca3SPierre Jolivet   } else if (!flg) PetscCall(MatCopy(A, (*submat)[0], SAME_NONZERO_PATTERN));
115413044ca3SPierre Jolivet   if (flg) {
1155bf583f0cSPierre Jolivet     PetscCall(MatDestroy(*submat)); /* previously created Mat has to be destroyed */
115613044ca3SPierre Jolivet     (*submat)[0] = A;
115713044ca3SPierre Jolivet     PetscCall(PetscObjectReference((PetscObject)A));
115813044ca3SPierre Jolivet   }
11593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1160f1580f4eSBarry Smith }
1161f1580f4eSBarry Smith 
1162d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMCommunicationAvoidingPCASM_Private(PC pc, Mat C, PetscBool sorted)
1163d71ae5a4SJacob Faibussowitsch {
1164f1580f4eSBarry Smith   void (*op)(void);
1165f1580f4eSBarry Smith 
1166f1580f4eSBarry Smith   PetscFunctionBegin;
1167f1580f4eSBarry Smith   /* previously-composed Mat */
1168f1580f4eSBarry Smith   PetscCall(PetscObjectCompose((PetscObject)pc->pmat, "_PCHPDDM_SubMatrices", (PetscObject)C));
1169f1580f4eSBarry Smith   PetscCall(MatGetOperation(pc->pmat, MATOP_CREATE_SUBMATRICES, &op));
1170f1580f4eSBarry Smith   /* trick suggested by Barry https://lists.mcs.anl.gov/pipermail/petsc-dev/2020-January/025491.html */
1171f1580f4eSBarry Smith   PetscCall(MatSetOperation(pc->pmat, MATOP_CREATE_SUBMATRICES, (void (*)(void))PCHPDDMCreateSubMatrices_Private));
1172f1580f4eSBarry Smith   if (sorted) PetscCall(PCASMSetSortIndices(pc, PETSC_FALSE)); /* everything is already sorted */
1173f1580f4eSBarry Smith   PetscCall(PCSetFromOptions(pc));                             /* otherwise -pc_hpddm_levels_1_pc_asm_sub_mat_type is not used */
1174f1580f4eSBarry Smith   PetscCall(PCSetUp(pc));
1175f1580f4eSBarry Smith   /* reset MatCreateSubMatrices() */
1176f1580f4eSBarry Smith   PetscCall(MatSetOperation(pc->pmat, MATOP_CREATE_SUBMATRICES, op));
1177db4a47b3SPierre Jolivet   PetscCall(PetscObjectCompose((PetscObject)pc->pmat, "_PCHPDDM_SubMatrices", nullptr));
11783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1179f1580f4eSBarry Smith }
1180f1580f4eSBarry Smith 
1181d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMPermute_Private(IS is, IS in_is, IS *out_is, Mat in_C, Mat *out_C, IS *p)
1182d71ae5a4SJacob Faibussowitsch {
1183f1580f4eSBarry Smith   IS                           perm;
1184f1580f4eSBarry Smith   const PetscInt              *ptr;
1185811e8887SPierre Jolivet   PetscInt                    *concatenate, size, bs;
1186f1580f4eSBarry Smith   std::map<PetscInt, PetscInt> order;
1187f1580f4eSBarry Smith   PetscBool                    sorted;
1188f1580f4eSBarry Smith 
1189f1580f4eSBarry Smith   PetscFunctionBegin;
1190cf67ef9dSPierre Jolivet   PetscValidHeaderSpecific(is, IS_CLASSID, 1);
1191cf67ef9dSPierre Jolivet   PetscValidHeaderSpecific(in_C, MAT_CLASSID, 4);
1192f1580f4eSBarry Smith   PetscCall(ISSorted(is, &sorted));
1193f1580f4eSBarry Smith   if (!sorted) {
1194f1580f4eSBarry Smith     PetscCall(ISGetLocalSize(is, &size));
1195f1580f4eSBarry Smith     PetscCall(ISGetIndices(is, &ptr));
1196b07dfdedSPierre Jolivet     PetscCall(ISGetBlockSize(is, &bs));
1197f1580f4eSBarry Smith     /* MatCreateSubMatrices(), called by PCASM, follows the global numbering of Pmat */
1198811e8887SPierre Jolivet     for (PetscInt n = 0; n < size; n += bs) order.insert(std::make_pair(ptr[n] / bs, n / bs));
1199f1580f4eSBarry Smith     PetscCall(ISRestoreIndices(is, &ptr));
1200b07dfdedSPierre Jolivet     size /= bs;
1201f1580f4eSBarry Smith     if (out_C) {
1202f1580f4eSBarry Smith       PetscCall(PetscMalloc1(size, &concatenate));
1203f1580f4eSBarry Smith       for (const std::pair<const PetscInt, PetscInt> &i : order) *concatenate++ = i.second;
1204f1580f4eSBarry Smith       concatenate -= size;
1205b07dfdedSPierre Jolivet       PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)in_C), bs, size, concatenate, PETSC_OWN_POINTER, &perm));
1206f1580f4eSBarry Smith       PetscCall(ISSetPermutation(perm));
1207f1580f4eSBarry Smith       /* permute user-provided Mat so that it matches with MatCreateSubMatrices() numbering */
1208f1580f4eSBarry Smith       PetscCall(MatPermute(in_C, perm, perm, out_C));
1209f1580f4eSBarry Smith       if (p) *p = perm;
1210f1580f4eSBarry Smith       else PetscCall(ISDestroy(&perm)); /* no need to save the permutation */
1211f1580f4eSBarry Smith     }
1212f1580f4eSBarry Smith     if (out_is) {
1213f1580f4eSBarry Smith       PetscCall(PetscMalloc1(size, &concatenate));
1214f1580f4eSBarry Smith       for (const std::pair<const PetscInt, PetscInt> &i : order) *concatenate++ = i.first;
1215f1580f4eSBarry Smith       concatenate -= size;
1216f1580f4eSBarry Smith       /* permute user-provided IS so that it matches with MatCreateSubMatrices() numbering */
1217b07dfdedSPierre Jolivet       PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)in_is), bs, size, concatenate, PETSC_OWN_POINTER, out_is));
1218f1580f4eSBarry Smith     }
1219f1580f4eSBarry Smith   } else { /* input IS is sorted, nothing to permute, simply duplicate inputs when needed */
1220f1580f4eSBarry Smith     if (out_C) PetscCall(MatDuplicate(in_C, MAT_COPY_VALUES, out_C));
1221f1580f4eSBarry Smith     if (out_is) PetscCall(ISDuplicate(in_is, out_is));
1222f1580f4eSBarry Smith   }
12233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1224f1580f4eSBarry Smith }
1225f1580f4eSBarry Smith 
1226281f8ce6SPierre Jolivet static PetscErrorCode PCHPDDMCheckSymmetry_Private(PC pc, Mat A01, Mat A10, Mat *B01 = nullptr)
122713044ca3SPierre Jolivet {
122813044ca3SPierre Jolivet   Mat       T, U = nullptr, B = nullptr;
122913044ca3SPierre Jolivet   IS        z;
1230281f8ce6SPierre Jolivet   PetscBool flg, conjugate = PETSC_FALSE;
123113044ca3SPierre Jolivet 
123213044ca3SPierre Jolivet   PetscFunctionBegin;
1233281f8ce6SPierre Jolivet   PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATTRANSPOSEVIRTUAL, &flg));
1234281f8ce6SPierre Jolivet   if (B01) *B01 = nullptr;
1235281f8ce6SPierre Jolivet   if (flg) {
1236811e8887SPierre Jolivet     PetscCall(MatShellGetScalingShifts(A10, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1237811e8887SPierre Jolivet     PetscCall(MatTransposeGetMat(A10, &U));
1238811e8887SPierre Jolivet   } else {
1239281f8ce6SPierre Jolivet     PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
1240281f8ce6SPierre Jolivet     if (flg) {
1241811e8887SPierre Jolivet       PetscCall(MatShellGetScalingShifts(A10, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1242811e8887SPierre Jolivet       PetscCall(MatHermitianTransposeGetMat(A10, &U));
1243281f8ce6SPierre Jolivet       conjugate = PETSC_TRUE;
1244811e8887SPierre Jolivet     }
124513044ca3SPierre Jolivet   }
124613044ca3SPierre Jolivet   if (U) PetscCall(MatDuplicate(U, MAT_COPY_VALUES, &T));
124713044ca3SPierre Jolivet   else PetscCall(MatHermitianTranspose(A10, MAT_INITIAL_MATRIX, &T));
1248281f8ce6SPierre Jolivet   PetscCall(PetscObjectTypeCompare((PetscObject)A01, MATTRANSPOSEVIRTUAL, &flg));
1249281f8ce6SPierre Jolivet   if (flg) {
1250811e8887SPierre Jolivet     PetscCall(MatShellGetScalingShifts(A01, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
125113044ca3SPierre Jolivet     PetscCall(MatTransposeGetMat(A01, &A01));
125213044ca3SPierre Jolivet     PetscCall(MatTranspose(A01, MAT_INITIAL_MATRIX, &B));
125313044ca3SPierre Jolivet     A01 = B;
125413044ca3SPierre Jolivet   } else {
1255281f8ce6SPierre Jolivet     PetscCall(PetscObjectTypeCompare((PetscObject)A01, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
1256281f8ce6SPierre Jolivet     if (flg) {
1257811e8887SPierre Jolivet       PetscCall(MatShellGetScalingShifts(A01, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
125813044ca3SPierre Jolivet       PetscCall(MatHermitianTransposeGetMat(A01, &A01));
125913044ca3SPierre Jolivet       PetscCall(MatHermitianTranspose(A01, MAT_INITIAL_MATRIX, &B));
126013044ca3SPierre Jolivet       A01 = B;
126113044ca3SPierre Jolivet     }
126213044ca3SPierre Jolivet   }
1263281f8ce6SPierre Jolivet   PetscCall(PetscLayoutCompare(T->rmap, A01->rmap, &flg));
1264281f8ce6SPierre Jolivet   if (flg) {
1265281f8ce6SPierre Jolivet     PetscCall(PetscLayoutCompare(T->cmap, A01->cmap, &flg));
1266281f8ce6SPierre Jolivet     if (flg) {
126713044ca3SPierre Jolivet       PetscCall(MatFindZeroRows(A01, &z)); /* for essential boundary conditions, some implementations will */
126813044ca3SPierre Jolivet       if (z) {                             /*  zero rows in [P00 A01] except for the diagonal of P00       */
1269281f8ce6SPierre Jolivet         if (B01) PetscCall(MatDuplicate(T, MAT_COPY_VALUES, B01));
127013044ca3SPierre Jolivet         PetscCall(MatSetOption(T, MAT_NO_OFF_PROC_ZERO_ROWS, PETSC_TRUE));
127113044ca3SPierre Jolivet         PetscCall(MatZeroRowsIS(T, z, 0.0, nullptr, nullptr)); /* corresponding zero rows from A01 */
1272281f8ce6SPierre Jolivet       }
1273281f8ce6SPierre Jolivet       PetscCall(MatMultEqual(A01, T, 20, &flg));
1274281f8ce6SPierre Jolivet       if (!B01) PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "A01 != A10^T");
1275281f8ce6SPierre Jolivet       else {
1276281f8ce6SPierre Jolivet         PetscCall(PetscInfo(pc, "A01 and A10^T are equal? %s\n", PetscBools[flg]));
1277281f8ce6SPierre Jolivet         if (!flg) {
1278281f8ce6SPierre Jolivet           if (z) PetscCall(MatDestroy(&T));
1279281f8ce6SPierre Jolivet           else *B01 = T;
1280281f8ce6SPierre Jolivet           flg = PETSC_TRUE;
1281281f8ce6SPierre Jolivet         } else PetscCall(MatDestroy(B01));
1282281f8ce6SPierre Jolivet       }
128313044ca3SPierre Jolivet       PetscCall(ISDestroy(&z));
128413044ca3SPierre Jolivet     }
128513044ca3SPierre Jolivet   }
1286281f8ce6SPierre Jolivet   if (!flg) PetscCall(PetscInfo(pc, "A01 and A10^T have non-congruent layouts, cannot test for equality\n"));
1287281f8ce6SPierre Jolivet   if (!B01 || !*B01) PetscCall(MatDestroy(&T));
1288281f8ce6SPierre Jolivet   else if (conjugate) PetscCall(MatConjugate(T));
128913044ca3SPierre Jolivet   PetscCall(MatDestroy(&B));
129013044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
129113044ca3SPierre Jolivet }
129213044ca3SPierre Jolivet 
1293d16c0b94SPierre Jolivet static PetscErrorCode PCHPDDMCheckInclusion_Private(PC pc, IS is, IS is_local, PetscBool check)
1294d16c0b94SPierre Jolivet {
1295d16c0b94SPierre Jolivet   IS          intersect;
1296d16c0b94SPierre Jolivet   const char *str = "IS of the auxiliary Mat does not include all local rows of A";
1297d16c0b94SPierre Jolivet   PetscBool   equal;
1298d16c0b94SPierre Jolivet 
1299d16c0b94SPierre Jolivet   PetscFunctionBegin;
1300d16c0b94SPierre Jolivet   PetscCall(ISIntersect(is, is_local, &intersect));
1301d16c0b94SPierre Jolivet   PetscCall(ISEqualUnsorted(is_local, intersect, &equal));
1302d16c0b94SPierre Jolivet   PetscCall(ISDestroy(&intersect));
1303d16c0b94SPierre Jolivet   if (check) PetscCheck(equal, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%s", str);
1304d16c0b94SPierre Jolivet   else if (!equal) PetscCall(PetscInfo(pc, "%s\n", str));
1305d16c0b94SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
1306d16c0b94SPierre Jolivet }
1307d16c0b94SPierre Jolivet 
1308d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMDestroySubMatrices_Private(PetscBool flg, PetscBool algebraic, Mat *sub)
1309d71ae5a4SJacob Faibussowitsch {
1310f1580f4eSBarry Smith   IS is;
1311f1580f4eSBarry Smith 
1312f1580f4eSBarry Smith   PetscFunctionBegin;
1313f1580f4eSBarry Smith   if (!flg) {
1314f1580f4eSBarry Smith     if (algebraic) {
1315f1580f4eSBarry Smith       PetscCall(PetscObjectQuery((PetscObject)sub[0], "_PCHPDDM_Embed", (PetscObject *)&is));
1316f1580f4eSBarry Smith       PetscCall(ISDestroy(&is));
1317db4a47b3SPierre Jolivet       PetscCall(PetscObjectCompose((PetscObject)sub[0], "_PCHPDDM_Embed", nullptr));
1318db4a47b3SPierre Jolivet       PetscCall(PetscObjectCompose((PetscObject)sub[0], "_PCHPDDM_Compact", nullptr));
1319f1580f4eSBarry Smith     }
1320f1580f4eSBarry Smith     PetscCall(MatDestroySubMatrices(algebraic ? 2 : 1, &sub));
1321f1580f4eSBarry Smith   }
13223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1323f1580f4eSBarry Smith }
1324f1580f4eSBarry Smith 
1325d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMAlgebraicAuxiliaryMat_Private(Mat P, IS *is, Mat *sub[], PetscBool block)
1326d71ae5a4SJacob Faibussowitsch {
1327f1580f4eSBarry Smith   IS         icol[3], irow[2];
1328f1580f4eSBarry Smith   Mat       *M, Q;
1329f1580f4eSBarry Smith   PetscReal *ptr;
133058b7e2c1SStefano Zampini   PetscInt  *idx, p = 0, bs = P->cmap->bs;
1331f1580f4eSBarry Smith   PetscBool  flg;
1332f1580f4eSBarry Smith 
1333f1580f4eSBarry Smith   PetscFunctionBegin;
1334f1580f4eSBarry Smith   PetscCall(ISCreateStride(PETSC_COMM_SELF, P->cmap->N, 0, 1, icol + 2));
1335f1580f4eSBarry Smith   PetscCall(ISSetBlockSize(icol[2], bs));
1336f1580f4eSBarry Smith   PetscCall(ISSetIdentity(icol[2]));
1337f1580f4eSBarry Smith   PetscCall(PetscObjectTypeCompare((PetscObject)P, MATMPISBAIJ, &flg));
1338f1580f4eSBarry Smith   if (flg) {
1339f1580f4eSBarry Smith     /* MatCreateSubMatrices() does not handle MATMPISBAIJ properly when iscol != isrow, so convert first to MATMPIBAIJ */
1340f1580f4eSBarry Smith     PetscCall(MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &Q));
1341f1580f4eSBarry Smith     std::swap(P, Q);
1342f1580f4eSBarry Smith   }
1343f1580f4eSBarry Smith   PetscCall(MatCreateSubMatrices(P, 1, is, icol + 2, MAT_INITIAL_MATRIX, &M));
1344f1580f4eSBarry Smith   if (flg) {
1345f1580f4eSBarry Smith     std::swap(P, Q);
1346f1580f4eSBarry Smith     PetscCall(MatDestroy(&Q));
1347f1580f4eSBarry Smith   }
1348f1580f4eSBarry Smith   PetscCall(ISDestroy(icol + 2));
1349f1580f4eSBarry Smith   PetscCall(ISCreateStride(PETSC_COMM_SELF, M[0]->rmap->N, 0, 1, irow));
1350f1580f4eSBarry Smith   PetscCall(ISSetBlockSize(irow[0], bs));
1351f1580f4eSBarry Smith   PetscCall(ISSetIdentity(irow[0]));
1352f1580f4eSBarry Smith   if (!block) {
1353b07dfdedSPierre Jolivet     PetscCall(PetscMalloc2(P->cmap->N, &ptr, P->cmap->N / bs, &idx));
1354f1580f4eSBarry Smith     PetscCall(MatGetColumnNorms(M[0], NORM_INFINITY, ptr));
1355f1580f4eSBarry Smith     /* check for nonzero columns so that M[0] may be expressed in compact form */
1356811e8887SPierre Jolivet     for (PetscInt n = 0; n < P->cmap->N; n += bs) {
1357b07dfdedSPierre Jolivet       if (std::find_if(ptr + n, ptr + n + bs, [](PetscReal v) { return v > PETSC_MACHINE_EPSILON; }) != ptr + n + bs) idx[p++] = n / bs;
1358f1580f4eSBarry Smith     }
1359b07dfdedSPierre Jolivet     PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, p, idx, PETSC_USE_POINTER, icol + 1));
1360f1580f4eSBarry Smith     PetscCall(ISSetInfo(icol[1], IS_SORTED, IS_GLOBAL, PETSC_TRUE, PETSC_TRUE));
1361f1580f4eSBarry Smith     PetscCall(ISEmbed(*is, icol[1], PETSC_FALSE, icol + 2));
1362f1580f4eSBarry Smith     irow[1] = irow[0];
1363f1580f4eSBarry Smith     /* first Mat will be used in PCASM (if it is used as a PC on this level) and as the left-hand side of GenEO */
1364f1580f4eSBarry Smith     icol[0] = is[0];
1365f1580f4eSBarry Smith     PetscCall(MatCreateSubMatrices(M[0], 2, irow, icol, MAT_INITIAL_MATRIX, sub));
1366f1580f4eSBarry Smith     PetscCall(ISDestroy(icol + 1));
1367f1580f4eSBarry Smith     PetscCall(PetscFree2(ptr, idx));
1368f1580f4eSBarry Smith     /* IS used to go back and forth between the augmented and the original local linear system, see eq. (3.4) of [2022b] */
1369f1580f4eSBarry Smith     PetscCall(PetscObjectCompose((PetscObject)(*sub)[0], "_PCHPDDM_Embed", (PetscObject)icol[2]));
1370f1580f4eSBarry Smith     /* Mat used in eq. (3.1) of [2022b] */
1371f1580f4eSBarry Smith     PetscCall(PetscObjectCompose((PetscObject)(*sub)[0], "_PCHPDDM_Compact", (PetscObject)(*sub)[1]));
1372f1580f4eSBarry Smith   } else {
1373f1580f4eSBarry Smith     Mat aux;
1374811e8887SPierre Jolivet 
1375f1580f4eSBarry Smith     PetscCall(MatSetOption(M[0], MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
1376f1580f4eSBarry Smith     /* diagonal block of the overlapping rows */
1377f1580f4eSBarry Smith     PetscCall(MatCreateSubMatrices(M[0], 1, irow, is, MAT_INITIAL_MATRIX, sub));
1378f1580f4eSBarry Smith     PetscCall(MatDuplicate((*sub)[0], MAT_COPY_VALUES, &aux));
1379f1580f4eSBarry Smith     PetscCall(MatSetOption(aux, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
1380f1580f4eSBarry Smith     if (bs == 1) { /* scalar case */
1381f1580f4eSBarry Smith       Vec sum[2];
1382811e8887SPierre Jolivet 
1383f1580f4eSBarry Smith       PetscCall(MatCreateVecs(aux, sum, sum + 1));
1384f1580f4eSBarry Smith       PetscCall(MatGetRowSum(M[0], sum[0]));
1385f1580f4eSBarry Smith       PetscCall(MatGetRowSum(aux, sum[1]));
1386f1580f4eSBarry Smith       /* off-diagonal block row sum (full rows - diagonal block rows) */
1387f1580f4eSBarry Smith       PetscCall(VecAXPY(sum[0], -1.0, sum[1]));
1388f1580f4eSBarry Smith       /* subdomain matrix plus off-diagonal block row sum */
1389f1580f4eSBarry Smith       PetscCall(MatDiagonalSet(aux, sum[0], ADD_VALUES));
1390f1580f4eSBarry Smith       PetscCall(VecDestroy(sum));
1391f1580f4eSBarry Smith       PetscCall(VecDestroy(sum + 1));
1392f1580f4eSBarry Smith     } else { /* vectorial case */
1393f1580f4eSBarry Smith       /* TODO: missing MatGetValuesBlocked(), so the code below is     */
1394f1580f4eSBarry Smith       /* an extension of the scalar case for when bs > 1, but it could */
1395f1580f4eSBarry Smith       /* be more efficient by avoiding all these MatMatMult()          */
1396f1580f4eSBarry Smith       Mat          sum[2], ones;
1397f1580f4eSBarry Smith       PetscScalar *ptr;
1398811e8887SPierre Jolivet 
1399f1580f4eSBarry Smith       PetscCall(PetscCalloc1(M[0]->cmap->n * bs, &ptr));
1400f1580f4eSBarry Smith       PetscCall(MatCreateDense(PETSC_COMM_SELF, M[0]->cmap->n, bs, M[0]->cmap->n, bs, ptr, &ones));
1401811e8887SPierre Jolivet       for (PetscInt n = 0; n < M[0]->cmap->n; n += bs) {
1402f1580f4eSBarry Smith         for (p = 0; p < bs; ++p) ptr[n + p * (M[0]->cmap->n + 1)] = 1.0;
1403f1580f4eSBarry Smith       }
1404fb842aefSJose E. Roman       PetscCall(MatMatMult(M[0], ones, MAT_INITIAL_MATRIX, PETSC_CURRENT, sum));
1405f1580f4eSBarry Smith       PetscCall(MatDestroy(&ones));
1406f1580f4eSBarry Smith       PetscCall(MatCreateDense(PETSC_COMM_SELF, aux->cmap->n, bs, aux->cmap->n, bs, ptr, &ones));
1407f1580f4eSBarry Smith       PetscCall(MatDenseSetLDA(ones, M[0]->cmap->n));
1408fb842aefSJose E. Roman       PetscCall(MatMatMult(aux, ones, MAT_INITIAL_MATRIX, PETSC_CURRENT, sum + 1));
1409f1580f4eSBarry Smith       PetscCall(MatDestroy(&ones));
1410f1580f4eSBarry Smith       PetscCall(PetscFree(ptr));
1411f1580f4eSBarry Smith       /* off-diagonal block row sum (full rows - diagonal block rows) */
1412f1580f4eSBarry Smith       PetscCall(MatAXPY(sum[0], -1.0, sum[1], SAME_NONZERO_PATTERN));
1413f1580f4eSBarry Smith       PetscCall(MatDestroy(sum + 1));
1414f1580f4eSBarry Smith       /* re-order values to be consistent with MatSetValuesBlocked()           */
1415f1580f4eSBarry Smith       /* equivalent to MatTranspose() which does not truly handle              */
1416f1580f4eSBarry Smith       /* MAT_INPLACE_MATRIX in the rectangular case, as it calls PetscMalloc() */
1417f1580f4eSBarry Smith       PetscCall(MatDenseGetArrayWrite(sum[0], &ptr));
1418f1580f4eSBarry Smith       HPDDM::Wrapper<PetscScalar>::imatcopy<'T'>(bs, sum[0]->rmap->n, ptr, sum[0]->rmap->n, bs);
1419f1580f4eSBarry Smith       /* subdomain matrix plus off-diagonal block row sum */
1420811e8887SPierre Jolivet       for (PetscInt n = 0; n < aux->cmap->n / bs; ++n) PetscCall(MatSetValuesBlocked(aux, 1, &n, 1, &n, ptr + n * bs * bs, ADD_VALUES));
1421f1580f4eSBarry Smith       PetscCall(MatAssemblyBegin(aux, MAT_FINAL_ASSEMBLY));
1422f1580f4eSBarry Smith       PetscCall(MatAssemblyEnd(aux, MAT_FINAL_ASSEMBLY));
1423f1580f4eSBarry Smith       PetscCall(MatDenseRestoreArrayWrite(sum[0], &ptr));
1424f1580f4eSBarry Smith       PetscCall(MatDestroy(sum));
1425f1580f4eSBarry Smith     }
1426f1580f4eSBarry Smith     PetscCall(MatSetOption(aux, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1427f1580f4eSBarry Smith     /* left-hand side of GenEO, with the same sparsity pattern as PCASM subdomain solvers  */
1428f1580f4eSBarry Smith     PetscCall(PetscObjectCompose((PetscObject)(*sub)[0], "_PCHPDDM_Neumann_Mat", (PetscObject)aux));
1429f1580f4eSBarry Smith   }
1430f1580f4eSBarry Smith   PetscCall(ISDestroy(irow));
1431f1580f4eSBarry Smith   PetscCall(MatDestroySubMatrices(1, &M));
14323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1433f1580f4eSBarry Smith }
1434f1580f4eSBarry Smith 
143513044ca3SPierre Jolivet static PetscErrorCode PCApply_Nest(PC pc, Vec x, Vec y)
143613044ca3SPierre Jolivet {
143713044ca3SPierre Jolivet   Mat                    A;
143813044ca3SPierre Jolivet   MatSolverType          type;
143913044ca3SPierre Jolivet   IS                     is[2];
144013044ca3SPierre Jolivet   PetscBool              flg;
144113044ca3SPierre Jolivet   std::pair<PC, Vec[2]> *p;
144213044ca3SPierre Jolivet 
144313044ca3SPierre Jolivet   PetscFunctionBegin;
144413044ca3SPierre Jolivet   PetscCall(PCShellGetContext(pc, &p));
144513044ca3SPierre Jolivet   PetscCall(PCGetOperators(p->first, &A, nullptr));
144613044ca3SPierre Jolivet   PetscCall(MatNestGetISs(A, is, nullptr));
144713044ca3SPierre Jolivet   PetscCall(PCFactorGetMatSolverType(p->first, &type));
144813044ca3SPierre Jolivet   PetscCall(PCFactorGetMatrix(p->first, &A));
144913044ca3SPierre Jolivet   PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
145024ddd604SPierre Jolivet   if (flg && A->schur) {
145113044ca3SPierre Jolivet #if PetscDefined(HAVE_MUMPS)
145213044ca3SPierre Jolivet     PetscCall(MatMumpsSetIcntl(A, 26, 1)); /* reduction/condensation phase followed by Schur complement solve */
145313044ca3SPierre Jolivet #endif
145413044ca3SPierre Jolivet   }
145513044ca3SPierre Jolivet   PetscCall(VecISCopy(p->second[0], is[1], SCATTER_FORWARD, x)); /* assign the RHS associated to the Schur complement */
145613044ca3SPierre Jolivet   PetscCall(PCApply(p->first, p->second[0], p->second[1]));
145713044ca3SPierre Jolivet   PetscCall(VecISCopy(p->second[1], is[1], SCATTER_REVERSE, y)); /* retrieve the partial solution associated to the Schur complement */
145813044ca3SPierre Jolivet   if (flg) {
145913044ca3SPierre Jolivet #if PetscDefined(HAVE_MUMPS)
146013044ca3SPierre Jolivet     PetscCall(MatMumpsSetIcntl(A, 26, -1)); /* default ICNTL(26) value in PETSc */
146113044ca3SPierre Jolivet #endif
146213044ca3SPierre Jolivet   }
146313044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
146413044ca3SPierre Jolivet }
146513044ca3SPierre Jolivet 
146613044ca3SPierre Jolivet static PetscErrorCode PCView_Nest(PC pc, PetscViewer viewer)
146713044ca3SPierre Jolivet {
146813044ca3SPierre Jolivet   std::pair<PC, Vec[2]> *p;
146913044ca3SPierre Jolivet 
147013044ca3SPierre Jolivet   PetscFunctionBegin;
147113044ca3SPierre Jolivet   PetscCall(PCShellGetContext(pc, &p));
147213044ca3SPierre Jolivet   PetscCall(PCView(p->first, viewer));
147313044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
147413044ca3SPierre Jolivet }
147513044ca3SPierre Jolivet 
147613044ca3SPierre Jolivet static PetscErrorCode PCDestroy_Nest(PC pc)
147713044ca3SPierre Jolivet {
147813044ca3SPierre Jolivet   std::pair<PC, Vec[2]> *p;
147913044ca3SPierre Jolivet 
148013044ca3SPierre Jolivet   PetscFunctionBegin;
148113044ca3SPierre Jolivet   PetscCall(PCShellGetContext(pc, &p));
148213044ca3SPierre Jolivet   PetscCall(VecDestroy(p->second));
148313044ca3SPierre Jolivet   PetscCall(VecDestroy(p->second + 1));
148413044ca3SPierre Jolivet   PetscCall(PCDestroy(&p->first));
148513044ca3SPierre Jolivet   PetscCall(PetscFree(p));
148613044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
148713044ca3SPierre Jolivet }
148813044ca3SPierre Jolivet 
148913044ca3SPierre Jolivet template <bool T = false>
149013044ca3SPierre Jolivet static PetscErrorCode MatMult_Schur(Mat A, Vec x, Vec y)
149113044ca3SPierre Jolivet {
149201e3c840SPierre Jolivet   std::tuple<Mat, PetscSF, Vec[2]> *ctx;
149313044ca3SPierre Jolivet 
149413044ca3SPierre Jolivet   PetscFunctionBegin;
149513044ca3SPierre Jolivet   PetscCall(MatShellGetContext(A, &ctx));
149613044ca3SPierre Jolivet   PetscCall(VecScatterBegin(std::get<1>(*ctx), x, std::get<2>(*ctx)[0], INSERT_VALUES, SCATTER_FORWARD)); /* local Vec with overlap */
149713044ca3SPierre Jolivet   PetscCall(VecScatterEnd(std::get<1>(*ctx), x, std::get<2>(*ctx)[0], INSERT_VALUES, SCATTER_FORWARD));
149813044ca3SPierre Jolivet   if (!T) PetscCall(MatMult(std::get<0>(*ctx), std::get<2>(*ctx)[0], std::get<2>(*ctx)[1])); /* local Schur complement */
149913044ca3SPierre Jolivet   else PetscCall(MatMultTranspose(std::get<0>(*ctx), std::get<2>(*ctx)[0], std::get<2>(*ctx)[1]));
150013044ca3SPierre Jolivet   PetscCall(VecSet(y, 0.0));
150113044ca3SPierre Jolivet   PetscCall(VecScatterBegin(std::get<1>(*ctx), std::get<2>(*ctx)[1], y, ADD_VALUES, SCATTER_REVERSE)); /* global Vec with summed up contributions on the overlap */
150213044ca3SPierre Jolivet   PetscCall(VecScatterEnd(std::get<1>(*ctx), std::get<2>(*ctx)[1], y, ADD_VALUES, SCATTER_REVERSE));
150313044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
150413044ca3SPierre Jolivet }
150513044ca3SPierre Jolivet 
150613044ca3SPierre Jolivet static PetscErrorCode MatDestroy_Schur(Mat A)
150713044ca3SPierre Jolivet {
150801e3c840SPierre Jolivet   std::tuple<Mat, PetscSF, Vec[2]> *ctx;
150913044ca3SPierre Jolivet 
151013044ca3SPierre Jolivet   PetscFunctionBegin;
151113044ca3SPierre Jolivet   PetscCall(MatShellGetContext(A, &ctx));
151213044ca3SPierre Jolivet   PetscCall(VecDestroy(std::get<2>(*ctx)));
151313044ca3SPierre Jolivet   PetscCall(VecDestroy(std::get<2>(*ctx) + 1));
151413044ca3SPierre Jolivet   PetscCall(PetscFree(ctx));
151513044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
151613044ca3SPierre Jolivet }
151713044ca3SPierre Jolivet 
151813044ca3SPierre Jolivet static PetscErrorCode MatMult_SchurCorrection(Mat A, Vec x, Vec y)
151913044ca3SPierre Jolivet {
152013044ca3SPierre Jolivet   PC                                         pc;
152113044ca3SPierre Jolivet   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx;
152213044ca3SPierre Jolivet 
152313044ca3SPierre Jolivet   PetscFunctionBegin;
152413044ca3SPierre Jolivet   PetscCall(MatShellGetContext(A, &ctx));
152513044ca3SPierre Jolivet   pc = ((PC_HPDDM *)std::get<0>(*ctx)[0]->data)->levels[0]->ksp->pc;
152613044ca3SPierre Jolivet   if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) {             /* Q_0 is the coarse correction associated to the A00 block from PCFIELDSPLIT */
152713044ca3SPierre Jolivet     PetscCall(MatMult(std::get<1>(*ctx)[0], x, std::get<3>(*ctx)[1]));                    /*     A_01 x                 */
152813044ca3SPierre Jolivet     PetscCall(PCHPDDMDeflate_Private(pc, std::get<3>(*ctx)[1], std::get<3>(*ctx)[1]));    /*     Q_0 A_01 x             */
152913044ca3SPierre Jolivet     PetscCall(MatMult(std::get<1>(*ctx)[1], std::get<3>(*ctx)[1], std::get<3>(*ctx)[0])); /*     A_10 Q_0 A_01 x        */
153013044ca3SPierre Jolivet     PetscCall(PCApply(std::get<0>(*ctx)[1], std::get<3>(*ctx)[0], y));                    /* y = M_S^-1 A_10 Q_0 A_01 x */
153113044ca3SPierre Jolivet   } else {
153213044ca3SPierre Jolivet     PetscCall(PCApply(std::get<0>(*ctx)[1], x, std::get<3>(*ctx)[0]));                    /*     M_S^-1 x               */
153313044ca3SPierre Jolivet     PetscCall(MatMult(std::get<1>(*ctx)[0], std::get<3>(*ctx)[0], std::get<3>(*ctx)[1])); /*     A_01 M_S^-1 x          */
153413044ca3SPierre Jolivet     PetscCall(PCHPDDMDeflate_Private(pc, std::get<3>(*ctx)[1], std::get<3>(*ctx)[1]));    /*     Q_0 A_01 M_S^-1 x      */
153513044ca3SPierre Jolivet     PetscCall(MatMult(std::get<1>(*ctx)[1], std::get<3>(*ctx)[1], y));                    /* y = A_10 Q_0 A_01 M_S^-1 x */
153613044ca3SPierre Jolivet   }
153713044ca3SPierre Jolivet   PetscCall(VecAXPY(y, -1.0, x)); /* y -= x, preconditioned eq. (24) of https://hal.science/hal-02343808v6/document (with a sign flip) */
153813044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
153913044ca3SPierre Jolivet }
154013044ca3SPierre Jolivet 
154113044ca3SPierre Jolivet static PetscErrorCode MatView_SchurCorrection(Mat A, PetscViewer viewer)
154213044ca3SPierre Jolivet {
154313044ca3SPierre Jolivet   PetscBool                                  ascii;
154413044ca3SPierre Jolivet   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx;
154513044ca3SPierre Jolivet 
154613044ca3SPierre Jolivet   PetscFunctionBegin;
154713044ca3SPierre Jolivet   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &ascii));
154813044ca3SPierre Jolivet   if (ascii) {
154913044ca3SPierre Jolivet     PetscCall(MatShellGetContext(A, &ctx));
155013044ca3SPierre Jolivet     PetscCall(PetscViewerASCIIPrintf(viewer, "action of %s\n", std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT ? "(I - M_S^-1 A_10 Q_0 A_01)" : "(I - A_10 Q_0 A_01 M_S^-1)"));
155113044ca3SPierre Jolivet     PetscCall(PCView(std::get<0>(*ctx)[1], viewer)); /* no need to PCView(Q_0) since it will be done by PCFIELDSPLIT */
155213044ca3SPierre Jolivet   }
155313044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
155413044ca3SPierre Jolivet }
155513044ca3SPierre Jolivet 
155613044ca3SPierre Jolivet static PetscErrorCode MatDestroy_SchurCorrection(Mat A)
155713044ca3SPierre Jolivet {
155813044ca3SPierre Jolivet   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx;
155913044ca3SPierre Jolivet 
156013044ca3SPierre Jolivet   PetscFunctionBegin;
156113044ca3SPierre Jolivet   PetscCall(MatShellGetContext(A, &ctx));
156213044ca3SPierre Jolivet   PetscCall(VecDestroy(std::get<3>(*ctx)));
156313044ca3SPierre Jolivet   PetscCall(VecDestroy(std::get<3>(*ctx) + 1));
156413044ca3SPierre Jolivet   PetscCall(VecDestroy(std::get<3>(*ctx) + 2));
156513044ca3SPierre Jolivet   PetscCall(PCDestroy(std::get<0>(*ctx) + 1));
156613044ca3SPierre Jolivet   PetscCall(PetscFree(ctx));
156713044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
156813044ca3SPierre Jolivet }
156913044ca3SPierre Jolivet 
1570feebddf4SPierre Jolivet static PetscErrorCode PCPostSolve_SchurPreLeastSquares(PC, KSP, Vec, Vec x)
1571feebddf4SPierre Jolivet {
1572feebddf4SPierre Jolivet   PetscFunctionBegin;
1573feebddf4SPierre Jolivet   PetscCall(VecScale(x, -1.0));
1574feebddf4SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
1575feebddf4SPierre Jolivet }
1576feebddf4SPierre Jolivet 
157713044ca3SPierre Jolivet static PetscErrorCode KSPPreSolve_SchurCorrection(KSP, Vec b, Vec, void *context)
157813044ca3SPierre Jolivet {
157913044ca3SPierre Jolivet   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx = reinterpret_cast<std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *>(context);
158013044ca3SPierre Jolivet 
1581a6b3e571SPierre Jolivet   PetscFunctionBegin;
158213044ca3SPierre Jolivet   if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) {
158313044ca3SPierre Jolivet     PetscCall(PCApply(std::get<0>(*ctx)[1], b, std::get<3>(*ctx)[2]));
158413044ca3SPierre Jolivet     std::swap(*b, *std::get<3>(*ctx)[2]); /* replace b by M^-1 b, but need to keep a copy of the original RHS, so swap it with the work Vec */
158513044ca3SPierre Jolivet   }
158613044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
158713044ca3SPierre Jolivet }
158813044ca3SPierre Jolivet 
158913044ca3SPierre Jolivet static PetscErrorCode KSPPostSolve_SchurCorrection(KSP, Vec b, Vec x, void *context)
159013044ca3SPierre Jolivet {
159113044ca3SPierre Jolivet   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx = reinterpret_cast<std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *>(context);
159213044ca3SPierre Jolivet 
1593a6b3e571SPierre Jolivet   PetscFunctionBegin;
159413044ca3SPierre Jolivet   if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) std::swap(*b, *std::get<3>(*ctx)[2]); /* put back the original RHS where it belongs */
159513044ca3SPierre Jolivet   else {
159613044ca3SPierre Jolivet     PetscCall(PCApply(std::get<0>(*ctx)[1], x, std::get<3>(*ctx)[2]));
159713044ca3SPierre Jolivet     PetscCall(VecCopy(std::get<3>(*ctx)[2], x)); /* replace x by M^-1 x */
159813044ca3SPierre Jolivet   }
159913044ca3SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
160013044ca3SPierre Jolivet }
160113044ca3SPierre Jolivet 
16029bb5c669SPierre Jolivet static PetscErrorCode MatMult_Harmonic(Mat, Vec, Vec);
16039bb5c669SPierre Jolivet static PetscErrorCode MatMultTranspose_Harmonic(Mat, Vec, Vec);
16049bb5c669SPierre Jolivet static PetscErrorCode MatProduct_AB_Harmonic(Mat, Mat, Mat, void *);
16059bb5c669SPierre Jolivet static PetscErrorCode MatDestroy_Harmonic(Mat);
16069bb5c669SPierre Jolivet 
1607d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCSetUp_HPDDM(PC pc)
1608d71ae5a4SJacob Faibussowitsch {
1609f1580f4eSBarry Smith   PC_HPDDM                                  *data = (PC_HPDDM *)pc->data;
1610f1580f4eSBarry Smith   PC                                         inner;
1611f1580f4eSBarry Smith   KSP                                       *ksp;
161213044ca3SPierre Jolivet   Mat                                       *sub, A, P, N, C = nullptr, uaux = nullptr, weighted, subA[2], S;
1613f1580f4eSBarry Smith   Vec                                        xin, v;
1614f1580f4eSBarry Smith   std::vector<Vec>                           initial;
1615db4a47b3SPierre Jolivet   IS                                         is[1], loc, uis = data->is, unsorted = nullptr;
1616f1580f4eSBarry Smith   ISLocalToGlobalMapping                     l2g;
1617f1580f4eSBarry Smith   char                                       prefix[256];
1618f1580f4eSBarry Smith   const char                                *pcpre;
1619f1580f4eSBarry Smith   const PetscScalar *const                  *ev;
16209bb5c669SPierre Jolivet   PetscInt                                   n, requested = data->N, reused = 0, overlap = -1;
1621f1580f4eSBarry Smith   MatStructure                               structure  = UNKNOWN_NONZERO_PATTERN;
1622f1580f4eSBarry Smith   PetscBool                                  subdomains = PETSC_FALSE, flg = PETSC_FALSE, ismatis, swap = PETSC_FALSE, algebraic = PETSC_FALSE, block = PETSC_FALSE;
1623f1580f4eSBarry Smith   DM                                         dm;
162413044ca3SPierre Jolivet   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx = nullptr;
1625398c7888SPierre Jolivet #if PetscDefined(USE_DEBUG)
1626db4a47b3SPierre Jolivet   IS  dis  = nullptr;
1627db4a47b3SPierre Jolivet   Mat daux = nullptr;
1628398c7888SPierre Jolivet #endif
1629f1580f4eSBarry Smith 
1630f1580f4eSBarry Smith   PetscFunctionBegin;
1631f1580f4eSBarry Smith   PetscCheck(data->levels && data->levels[0], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not a single level allocated");
1632f1580f4eSBarry Smith   PetscCall(PCGetOptionsPrefix(pc, &pcpre));
1633f1580f4eSBarry Smith   PetscCall(PCGetOperators(pc, &A, &P));
1634f1580f4eSBarry Smith   if (!data->levels[0]->ksp) {
1635f1580f4eSBarry Smith     PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->ksp));
16363821be0aSBarry Smith     PetscCall(KSPSetNestLevel(data->levels[0]->ksp, pc->kspnestlevel));
1637f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_%s_", pcpre ? pcpre : "", data->N > 1 ? "levels_1" : "coarse"));
1638f1580f4eSBarry Smith     PetscCall(KSPSetOptionsPrefix(data->levels[0]->ksp, prefix));
1639f1580f4eSBarry Smith     PetscCall(KSPSetType(data->levels[0]->ksp, KSPPREONLY));
1640f1580f4eSBarry Smith   } else if (data->levels[0]->ksp->pc && data->levels[0]->ksp->pc->setupcalled == 1 && data->levels[0]->ksp->pc->reusepreconditioner) {
1641f1580f4eSBarry Smith     /* if the fine-level PCSHELL exists, its setup has succeeded, and one wants to reuse it, */
1642f1580f4eSBarry Smith     /* then just propagate the appropriate flag to the coarser levels                        */
1643f1580f4eSBarry Smith     for (n = 0; n < PETSC_PCHPDDM_MAXLEVELS && data->levels[n]; ++n) {
1644f1580f4eSBarry Smith       /* the following KSP and PC may be NULL for some processes, hence the check            */
1645f1580f4eSBarry Smith       if (data->levels[n]->ksp) PetscCall(KSPSetReusePreconditioner(data->levels[n]->ksp, PETSC_TRUE));
1646f1580f4eSBarry Smith       if (data->levels[n]->pc) PetscCall(PCSetReusePreconditioner(data->levels[n]->pc, PETSC_TRUE));
1647f1580f4eSBarry Smith     }
1648f1580f4eSBarry Smith     /* early bail out because there is nothing to do */
16493ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1650f1580f4eSBarry Smith   } else {
1651f1580f4eSBarry Smith     /* reset coarser levels */
1652f1580f4eSBarry Smith     for (n = 1; n < PETSC_PCHPDDM_MAXLEVELS && data->levels[n]; ++n) {
1653f1580f4eSBarry Smith       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) {
1654f1580f4eSBarry Smith         reused = data->N - n;
1655f1580f4eSBarry Smith         break;
1656f1580f4eSBarry Smith       }
1657f1580f4eSBarry Smith       PetscCall(KSPDestroy(&data->levels[n]->ksp));
1658f1580f4eSBarry Smith       PetscCall(PCDestroy(&data->levels[n]->pc));
1659f1580f4eSBarry Smith     }
1660f1580f4eSBarry Smith     /* check if some coarser levels are being reused */
1661462c564dSBarry Smith     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &reused, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)pc)));
1662f1580f4eSBarry Smith     const int *addr = data->levels[0]->P ? data->levels[0]->P->getAddrLocal() : &HPDDM::i__0;
1663f1580f4eSBarry Smith 
1664f1580f4eSBarry Smith     if (addr != &HPDDM::i__0 && reused != data->N - 1) {
1665f1580f4eSBarry Smith       /* reuse previously computed eigenvectors */
1666f1580f4eSBarry Smith       ev = data->levels[0]->P->getVectors();
1667f1580f4eSBarry Smith       if (ev) {
1668f1580f4eSBarry Smith         initial.reserve(*addr);
1669f1580f4eSBarry Smith         PetscCall(VecCreateSeqWithArray(PETSC_COMM_SELF, 1, data->levels[0]->P->getDof(), ev[0], &xin));
1670f1580f4eSBarry Smith         for (n = 0; n < *addr; ++n) {
1671f1580f4eSBarry Smith           PetscCall(VecDuplicate(xin, &v));
1672f1580f4eSBarry Smith           PetscCall(VecPlaceArray(xin, ev[n]));
1673f1580f4eSBarry Smith           PetscCall(VecCopy(xin, v));
1674f1580f4eSBarry Smith           initial.emplace_back(v);
1675f1580f4eSBarry Smith           PetscCall(VecResetArray(xin));
1676f1580f4eSBarry Smith         }
1677f1580f4eSBarry Smith         PetscCall(VecDestroy(&xin));
1678f1580f4eSBarry Smith       }
1679f1580f4eSBarry Smith     }
1680f1580f4eSBarry Smith   }
1681f1580f4eSBarry Smith   data->N -= reused;
1682f1580f4eSBarry Smith   PetscCall(KSPSetOperators(data->levels[0]->ksp, A, P));
1683f1580f4eSBarry Smith 
1684f1580f4eSBarry Smith   PetscCall(PetscObjectTypeCompare((PetscObject)P, MATIS, &ismatis));
1685f1580f4eSBarry Smith   if (!data->is && !ismatis) {
1686db4a47b3SPierre Jolivet     PetscErrorCode (*create)(DM, IS *, Mat *, PetscErrorCode (**)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void **) = nullptr;
1687db4a47b3SPierre Jolivet     PetscErrorCode (*usetup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *)                                                = nullptr;
1688db4a47b3SPierre Jolivet     void *uctx                                                                                                               = nullptr;
1689f1580f4eSBarry Smith 
1690f1580f4eSBarry Smith     /* first see if we can get the data from the DM */
1691f1580f4eSBarry Smith     PetscCall(MatGetDM(P, &dm));
1692f1580f4eSBarry Smith     if (!dm) PetscCall(MatGetDM(A, &dm));
1693f1580f4eSBarry Smith     if (!dm) PetscCall(PCGetDM(pc, &dm));
1694907a3e9cSStefano Zampini     if (dm) { /* this is the hook for DMPLEX for which the auxiliary Mat is the local Neumann matrix */
1695f1580f4eSBarry Smith       PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", &create));
1696f1580f4eSBarry Smith       if (create) {
1697f1580f4eSBarry Smith         PetscCall((*create)(dm, &uis, &uaux, &usetup, &uctx));
1698c8ea6600SPierre Jolivet         if (data->Neumann == PETSC_BOOL3_UNKNOWN) data->Neumann = PETSC_BOOL3_TRUE; /* set the value only if it was not already provided by the user */
1699f1580f4eSBarry Smith       }
1700f1580f4eSBarry Smith     }
1701f1580f4eSBarry Smith     if (!create) {
1702f1580f4eSBarry Smith       if (!uis) {
1703f1580f4eSBarry Smith         PetscCall(PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Neumann_IS", (PetscObject *)&uis));
1704f1580f4eSBarry Smith         PetscCall(PetscObjectReference((PetscObject)uis));
1705f1580f4eSBarry Smith       }
1706f1580f4eSBarry Smith       if (!uaux) {
1707f1580f4eSBarry Smith         PetscCall(PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Neumann_Mat", (PetscObject *)&uaux));
1708f1580f4eSBarry Smith         PetscCall(PetscObjectReference((PetscObject)uaux));
1709f1580f4eSBarry Smith       }
1710f1580f4eSBarry Smith       /* look inside the Pmat instead of the PC, needed for MatSchurComplementComputeExplicitOperator() */
1711f1580f4eSBarry Smith       if (!uis) {
1712f1580f4eSBarry Smith         PetscCall(PetscObjectQuery((PetscObject)P, "_PCHPDDM_Neumann_IS", (PetscObject *)&uis));
1713f1580f4eSBarry Smith         PetscCall(PetscObjectReference((PetscObject)uis));
1714f1580f4eSBarry Smith       }
1715f1580f4eSBarry Smith       if (!uaux) {
1716f1580f4eSBarry Smith         PetscCall(PetscObjectQuery((PetscObject)P, "_PCHPDDM_Neumann_Mat", (PetscObject *)&uaux));
1717f1580f4eSBarry Smith         PetscCall(PetscObjectReference((PetscObject)uaux));
1718f1580f4eSBarry Smith       }
1719f1580f4eSBarry Smith     }
1720f1580f4eSBarry Smith     PetscCall(PCHPDDMSetAuxiliaryMat(pc, uis, uaux, usetup, uctx));
1721f1580f4eSBarry Smith     PetscCall(MatDestroy(&uaux));
1722f1580f4eSBarry Smith     PetscCall(ISDestroy(&uis));
1723f1580f4eSBarry Smith   }
1724f1580f4eSBarry Smith 
1725f1580f4eSBarry Smith   if (!ismatis) {
1726f1580f4eSBarry Smith     PetscCall(PCHPDDMSetUpNeumannOverlap_Private(pc));
1727db4a47b3SPierre Jolivet     PetscCall(PetscOptionsGetBool(nullptr, pcpre, "-pc_hpddm_block_splitting", &block, nullptr));
17289bb5c669SPierre Jolivet     PetscCall(PetscOptionsGetInt(nullptr, pcpre, "-pc_hpddm_harmonic_overlap", &overlap, nullptr));
17295e642048SPierre Jolivet     PetscCall(PetscObjectTypeCompare((PetscObject)P, MATSCHURCOMPLEMENT, &flg));
17305e642048SPierre Jolivet     if (data->is || (data->N > 1 && flg)) {
17319bb5c669SPierre Jolivet       if (block || overlap != -1) {
173202800ff6SPierre Jolivet         PetscCall(ISDestroy(&data->is));
173302800ff6SPierre Jolivet         PetscCall(MatDestroy(&data->aux));
17345e642048SPierre Jolivet       } else if (data->N > 1 && flg) {
173513044ca3SPierre Jolivet         PCHPDDMSchurPreType type = PC_HPDDM_SCHUR_PRE_GENEO;
173613044ca3SPierre Jolivet 
173713044ca3SPierre Jolivet         PetscCall(PetscOptionsGetEnum(nullptr, pcpre, "-pc_hpddm_schur_precondition", PCHPDDMSchurPreTypes, (PetscEnum *)&type, &flg));
173813044ca3SPierre Jolivet         if (type == PC_HPDDM_SCHUR_PRE_LEAST_SQUARES) {
173913044ca3SPierre Jolivet           PetscCall(ISDestroy(&data->is)); /* destroy any previously user-set objects since they will be set automatically */
174013044ca3SPierre Jolivet           PetscCall(MatDestroy(&data->aux));
174113044ca3SPierre Jolivet         } else if (type == PC_HPDDM_SCHUR_PRE_GENEO) {
174213044ca3SPierre Jolivet           PetscContainer container = nullptr;
174313044ca3SPierre Jolivet 
174413044ca3SPierre Jolivet           PetscCall(PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Schur", (PetscObject *)&container));
174513044ca3SPierre Jolivet           if (!container) { /* first call to PCSetUp() on the PC associated to the Schur complement */
174613044ca3SPierre Jolivet             PC_HPDDM *data_00;
174713044ca3SPierre Jolivet             KSP       ksp, inner_ksp;
174813044ca3SPierre Jolivet             PC        pc_00;
1749cf67ef9dSPierre Jolivet             Mat       A11 = nullptr;
1750cf67ef9dSPierre Jolivet             Vec       d   = nullptr;
175113044ca3SPierre Jolivet             char     *prefix;
175213044ca3SPierre Jolivet 
175313044ca3SPierre Jolivet             PetscCall(MatSchurComplementGetKSP(P, &ksp));
175413044ca3SPierre Jolivet             PetscCall(KSPGetPC(ksp, &pc_00));
175513044ca3SPierre Jolivet             PetscCall(PetscObjectTypeCompare((PetscObject)pc_00, PCHPDDM, &flg));
1756fd310a01SPierre Jolivet             PetscCheck(flg, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s and -%spc_type %s (!= %s)", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type], ((PetscObject)pc_00)->prefix ? ((PetscObject)pc_00)->prefix : "",
175713044ca3SPierre Jolivet                        ((PetscObject)pc_00)->type_name, PCHPDDM);
175813044ca3SPierre Jolivet             data_00 = (PC_HPDDM *)pc_00->data;
1759fd310a01SPierre Jolivet             PetscCheck(data_00->N == 2, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s and %" PetscInt_FMT " level%s instead of 2 for the A00 block -%s", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type],
1760fd310a01SPierre Jolivet                        data_00->N, data_00->N > 1 ? "s" : "", ((PetscObject)pc_00)->prefix);
176113044ca3SPierre Jolivet             PetscCall(PetscObjectTypeCompare((PetscObject)data_00->levels[0]->pc, PCASM, &flg));
1762fd310a01SPierre Jolivet             PetscCheck(flg, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s and -%spc_type %s (!= %s)", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type], ((PetscObject)data_00->levels[0]->pc)->prefix,
176313044ca3SPierre Jolivet                        ((PetscObject)data_00->levels[0]->pc)->type_name, PCASM);
1764d16c0b94SPierre Jolivet             PetscCall(MatSchurComplementGetSubMatrices(P, nullptr, nullptr, nullptr, nullptr, &A11));
17655e642048SPierre Jolivet             if (PetscDefined(USE_DEBUG) || !data->is) {
17665e642048SPierre Jolivet               Mat A01, A10, B = nullptr, C = nullptr, *sub;
176713044ca3SPierre Jolivet 
17685e642048SPierre Jolivet               PetscCall(MatSchurComplementGetSubMatrices(P, &A, nullptr, &A01, &A10, nullptr));
17695e642048SPierre Jolivet               PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATTRANSPOSEVIRTUAL, &flg));
17705e642048SPierre Jolivet               if (flg) {
17715e642048SPierre Jolivet                 PetscCall(MatTransposeGetMat(A10, &C));
17725e642048SPierre Jolivet                 PetscCall(MatTranspose(C, MAT_INITIAL_MATRIX, &B));
17735e642048SPierre Jolivet               } else {
17745e642048SPierre Jolivet                 PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
17755e642048SPierre Jolivet                 if (flg) {
17765e642048SPierre Jolivet                   PetscCall(MatHermitianTransposeGetMat(A10, &C));
17775e642048SPierre Jolivet                   PetscCall(MatHermitianTranspose(C, MAT_INITIAL_MATRIX, &B));
17785e642048SPierre Jolivet                 }
17795e642048SPierre Jolivet               }
1780811e8887SPierre Jolivet               if (flg)
1781811e8887SPierre Jolivet                 PetscCall(MatShellGetScalingShifts(A10, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
17825e642048SPierre Jolivet               if (!B) {
17835e642048SPierre Jolivet                 B = A10;
17845e642048SPierre Jolivet                 PetscCall(PetscObjectReference((PetscObject)B));
17855e642048SPierre Jolivet               } else if (!data->is) {
17865e642048SPierre Jolivet                 PetscCall(PetscObjectTypeCompareAny((PetscObject)A01, &flg, MATTRANSPOSEVIRTUAL, MATHERMITIANTRANSPOSEVIRTUAL, ""));
17875e642048SPierre Jolivet                 if (!flg) C = A01;
1788811e8887SPierre Jolivet                 else
1789811e8887SPierre Jolivet                   PetscCall(MatShellGetScalingShifts(A01, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
17905e642048SPierre Jolivet               }
179113044ca3SPierre Jolivet               PetscCall(ISCreateStride(PETSC_COMM_SELF, B->rmap->N, 0, 1, &uis));
17925e642048SPierre Jolivet               PetscCall(ISSetIdentity(uis));
17935e642048SPierre Jolivet               if (!data->is) {
17945e642048SPierre Jolivet                 if (C) PetscCall(PetscObjectReference((PetscObject)C));
17955e642048SPierre Jolivet                 else PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &C));
17965e642048SPierre Jolivet                 PetscCall(ISDuplicate(data_00->is, is));
17975e642048SPierre Jolivet                 PetscCall(MatIncreaseOverlap(A, 1, is, 1));
17985e642048SPierre Jolivet                 PetscCall(MatSetOption(C, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
17995e642048SPierre Jolivet                 PetscCall(MatCreateSubMatrices(C, 1, is, &uis, MAT_INITIAL_MATRIX, &sub));
18005e642048SPierre Jolivet                 PetscCall(MatDestroy(&C));
18015e642048SPierre Jolivet                 PetscCall(MatTranspose(sub[0], MAT_INITIAL_MATRIX, &C));
18025e642048SPierre Jolivet                 PetscCall(MatDestroySubMatrices(1, &sub));
18035e642048SPierre Jolivet                 PetscCall(MatFindNonzeroRows(C, &data->is));
18045e642048SPierre Jolivet                 PetscCall(MatDestroy(&C));
18055e642048SPierre Jolivet                 PetscCall(ISDestroy(is));
1806d16c0b94SPierre Jolivet                 PetscCall(ISCreateStride(PetscObjectComm((PetscObject)data->is), A11->rmap->n, A11->rmap->rstart, 1, &loc));
1807d16c0b94SPierre Jolivet                 if (PetscDefined(USE_DEBUG)) PetscCall(PCHPDDMCheckInclusion_Private(pc, data->is, loc, PETSC_FALSE));
1808d16c0b94SPierre Jolivet                 PetscCall(ISExpand(data->is, loc, is));
1809d16c0b94SPierre Jolivet                 PetscCall(ISDestroy(&loc));
1810d16c0b94SPierre Jolivet                 PetscCall(ISDestroy(&data->is));
1811d16c0b94SPierre Jolivet                 data->is = is[0];
1812d16c0b94SPierre Jolivet                 is[0]    = nullptr;
18135e642048SPierre Jolivet               }
18145e642048SPierre Jolivet               if (PetscDefined(USE_DEBUG)) {
18155e642048SPierre Jolivet                 PetscCall(PCHPDDMCheckSymmetry_Private(pc, A01, A10));
181613044ca3SPierre Jolivet                 PetscCall(MatCreateSubMatrices(B, 1, &uis, &data_00->is, MAT_INITIAL_MATRIX, &sub)); /* expensive check since all processes fetch all rows (but only some columns) of the constraint matrix */
181713044ca3SPierre Jolivet                 PetscCall(ISDestroy(&uis));
181813044ca3SPierre Jolivet                 PetscCall(ISDuplicate(data->is, &uis));
181913044ca3SPierre Jolivet                 PetscCall(ISSort(uis));
18205e642048SPierre Jolivet                 PetscCall(ISComplement(uis, 0, B->rmap->N, is));
182113044ca3SPierre Jolivet                 PetscCall(MatDuplicate(sub[0], MAT_COPY_VALUES, &C));
18225e642048SPierre Jolivet                 PetscCall(MatZeroRowsIS(C, is[0], 0.0, nullptr, nullptr));
18235e642048SPierre Jolivet                 PetscCall(ISDestroy(is));
182413044ca3SPierre Jolivet                 PetscCall(MatMultEqual(sub[0], C, 20, &flg));
182513044ca3SPierre Jolivet                 PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "The image of A_10 (R_i^p)^T from the local primal (e.g., velocity) space to the full dual (e.g., pressure) space is not restricted to the local dual space: A_10 (R_i^p)^T != R_i^d (R_i^d)^T A_10 (R_i^p)^T"); /* cf. eq. (9) of https://hal.science/hal-02343808v6/document */
182613044ca3SPierre Jolivet                 PetscCall(MatDestroy(&C));
182713044ca3SPierre Jolivet                 PetscCall(MatDestroySubMatrices(1, &sub));
182813044ca3SPierre Jolivet               }
18295e642048SPierre Jolivet               PetscCall(ISDestroy(&uis));
18305e642048SPierre Jolivet               PetscCall(MatDestroy(&B));
18315e642048SPierre Jolivet             }
1832cf67ef9dSPierre Jolivet             flg = PETSC_FALSE;
1833cf67ef9dSPierre Jolivet             if (!data->aux) {
1834cf67ef9dSPierre Jolivet               Mat D;
1835cf67ef9dSPierre Jolivet 
1836cf67ef9dSPierre Jolivet               PetscCall(MatCreateVecs(A11, &d, nullptr));
1837cf67ef9dSPierre Jolivet               PetscCall(MatGetDiagonal(A11, d));
1838cf67ef9dSPierre Jolivet               PetscCall(PetscObjectTypeCompareAny((PetscObject)A11, &flg, MATDIAGONAL, MATCONSTANTDIAGONAL, ""));
1839cf67ef9dSPierre Jolivet               if (!flg) {
1840cf67ef9dSPierre Jolivet                 PetscCall(MatCreateDiagonal(d, &D));
1841cf67ef9dSPierre Jolivet                 PetscCall(MatMultEqual(A11, D, 20, &flg));
1842cf67ef9dSPierre Jolivet                 PetscCall(MatDestroy(&D));
1843cf67ef9dSPierre Jolivet               }
1844cf67ef9dSPierre Jolivet               if (flg) PetscCall(PetscInfo(pc, "A11 block is likely diagonal so the PC will build an auxiliary Mat (which was not initially provided by the user)\n"));
1845cf67ef9dSPierre Jolivet             }
1846cf67ef9dSPierre Jolivet             if (data->Neumann != PETSC_BOOL3_TRUE && !flg && A11) {
1847cf67ef9dSPierre Jolivet               PetscReal norm;
1848cf67ef9dSPierre Jolivet 
1849cf67ef9dSPierre Jolivet               PetscCall(MatNorm(A11, NORM_INFINITY, &norm));
1850cf67ef9dSPierre Jolivet               PetscCheck(norm < PETSC_MACHINE_EPSILON * static_cast<PetscReal>(10.0), PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition geneo and -%spc_hpddm_has_neumann != true with a nonzero or non-diagonal A11 block", pcpre ? pcpre : "", pcpre ? pcpre : "");
1851cf67ef9dSPierre Jolivet               PetscCall(PetscInfo(pc, "A11 block is likely zero so the PC will build an auxiliary Mat (which was%s initially provided by the user)\n", data->aux ? "" : " not"));
1852cf67ef9dSPierre Jolivet               PetscCall(MatDestroy(&data->aux));
1853cf67ef9dSPierre Jolivet               flg = PETSC_TRUE;
1854cf67ef9dSPierre Jolivet             }
1855cf67ef9dSPierre Jolivet             if (!data->aux) { /* if A11 is near zero, e.g., Stokes equation, or diagonal, build an auxiliary (Neumann) Mat which is a (possibly slightly shifted) diagonal weighted by the inverse of the multiplicity */
185601e3c840SPierre Jolivet               PetscSF            scatter;
185713044ca3SPierre Jolivet               const PetscScalar *read;
1858cf67ef9dSPierre Jolivet               PetscScalar       *write, *diagonal = nullptr;
185913044ca3SPierre Jolivet 
186013044ca3SPierre Jolivet               PetscCall(MatDestroy(&data->aux));
186113044ca3SPierre Jolivet               PetscCall(ISGetLocalSize(data->is, &n));
1862cf67ef9dSPierre Jolivet               PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)P), n, PETSC_DECIDE, &xin));
1863cf67ef9dSPierre Jolivet               PetscCall(VecDuplicate(xin, &v));
1864cf67ef9dSPierre Jolivet               PetscCall(VecScatterCreate(xin, data->is, v, nullptr, &scatter));
186513044ca3SPierre Jolivet               PetscCall(VecSet(v, 1.0));
1866cf67ef9dSPierre Jolivet               PetscCall(VecSet(xin, 1.0));
1867cf67ef9dSPierre Jolivet               PetscCall(VecScatterBegin(scatter, v, xin, ADD_VALUES, SCATTER_REVERSE));
1868cf67ef9dSPierre Jolivet               PetscCall(VecScatterEnd(scatter, v, xin, ADD_VALUES, SCATTER_REVERSE)); /* v has the multiplicity of all unknowns on the overlap */
1869cf67ef9dSPierre Jolivet               PetscCall(PetscSFDestroy(&scatter));
1870cf67ef9dSPierre Jolivet               if (d) {
1871cf67ef9dSPierre Jolivet                 PetscCall(VecScatterCreate(d, data->is, v, nullptr, &scatter));
1872cf67ef9dSPierre Jolivet                 PetscCall(VecScatterBegin(scatter, d, v, INSERT_VALUES, SCATTER_FORWARD));
1873cf67ef9dSPierre Jolivet                 PetscCall(VecScatterEnd(scatter, d, v, INSERT_VALUES, SCATTER_FORWARD));
1874cf67ef9dSPierre Jolivet                 PetscCall(PetscSFDestroy(&scatter));
1875cf67ef9dSPierre Jolivet                 PetscCall(VecDestroy(&d));
1876cf67ef9dSPierre Jolivet                 PetscCall(PetscMalloc1(n, &diagonal));
1877cf67ef9dSPierre Jolivet                 PetscCall(VecGetArrayRead(v, &read));
1878cf67ef9dSPierre Jolivet                 PetscCallCXX(std::copy_n(read, n, diagonal));
1879cf67ef9dSPierre Jolivet                 PetscCall(VecRestoreArrayRead(v, &read));
1880cf67ef9dSPierre Jolivet               }
188113044ca3SPierre Jolivet               PetscCall(VecDestroy(&v));
188213044ca3SPierre Jolivet               PetscCall(VecCreateSeq(PETSC_COMM_SELF, n, &v));
1883cf67ef9dSPierre Jolivet               PetscCall(VecGetArrayRead(xin, &read));
188413044ca3SPierre Jolivet               PetscCall(VecGetArrayWrite(v, &write));
1885cf67ef9dSPierre Jolivet               for (PetscInt i = 0; i < n; ++i) write[i] = (!diagonal || std::abs(diagonal[i]) < PETSC_MACHINE_EPSILON) ? PETSC_SMALL / (static_cast<PetscReal>(1000.0) * read[i]) : diagonal[i] / read[i];
1886cf67ef9dSPierre Jolivet               PetscCall(PetscFree(diagonal));
1887cf67ef9dSPierre Jolivet               PetscCall(VecRestoreArrayRead(xin, &read));
188813044ca3SPierre Jolivet               PetscCall(VecRestoreArrayWrite(v, &write));
1889cf67ef9dSPierre Jolivet               PetscCall(VecDestroy(&xin));
1890c3e1b152SPierre Jolivet               PetscCall(MatCreateDiagonal(v, &data->aux));
189113044ca3SPierre Jolivet               PetscCall(VecDestroy(&v));
189213044ca3SPierre Jolivet             }
189313044ca3SPierre Jolivet             uis  = data->is;
189413044ca3SPierre Jolivet             uaux = data->aux;
189513044ca3SPierre Jolivet             PetscCall(PetscObjectReference((PetscObject)uis));
189613044ca3SPierre Jolivet             PetscCall(PetscObjectReference((PetscObject)uaux));
189713044ca3SPierre Jolivet             PetscCall(PetscStrallocpy(pcpre, &prefix));
189813044ca3SPierre Jolivet             PetscCall(PCSetOptionsPrefix(pc, nullptr));
189913044ca3SPierre Jolivet             PetscCall(PCSetType(pc, PCKSP));                                    /* replace the PC associated to the Schur complement by PCKSP */
190013044ca3SPierre Jolivet             PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &inner_ksp)); /* new KSP that will be attached to the previously set PC */
190173329a61SPierre Jolivet             pc->ops->setup = PCSetUp_KSP;
190213044ca3SPierre Jolivet             PetscCall(PetscObjectGetTabLevel((PetscObject)pc, &n));
190313044ca3SPierre Jolivet             PetscCall(PetscObjectSetTabLevel((PetscObject)inner_ksp, n + 2));
190413044ca3SPierre Jolivet             PetscCall(KSPSetOperators(inner_ksp, pc->mat, pc->pmat));
190513044ca3SPierre Jolivet             PetscCall(KSPSetOptionsPrefix(inner_ksp, std::string(std::string(prefix) + "pc_hpddm_").c_str()));
190613044ca3SPierre Jolivet             PetscCall(KSPSetSkipPCSetFromOptions(inner_ksp, PETSC_TRUE));
190713044ca3SPierre Jolivet             PetscCall(KSPSetFromOptions(inner_ksp));
190813044ca3SPierre Jolivet             PetscCall(KSPGetPC(inner_ksp, &inner));
190913044ca3SPierre Jolivet             PetscCall(PCSetOptionsPrefix(inner, nullptr));
191013044ca3SPierre Jolivet             PetscCall(PCSetType(inner, PCNONE)); /* no preconditioner since the action of M^-1 A or A M^-1 will be computed by the Amat */
191113044ca3SPierre Jolivet             PetscCall(PCKSPSetKSP(pc, inner_ksp));
191213044ca3SPierre Jolivet             PetscCall(PetscNew(&ctx));    /* context to pass data around for the inner-most PC, which will be a proper PCHPDDM */
191313044ca3SPierre Jolivet             std::get<0>(*ctx)[0] = pc_00; /* for coarse correction on the primal (e.g., velocity) space */
191413044ca3SPierre Jolivet             PetscCall(PCCreate(PetscObjectComm((PetscObject)pc), &std::get<0>(*ctx)[1]));
191513044ca3SPierre Jolivet             PetscCall(PCSetOptionsPrefix(std::get<0>(*ctx)[1], prefix));
191613044ca3SPierre Jolivet             PetscCall(PetscFree(prefix));
191713044ca3SPierre Jolivet             PetscCall(PCSetOperators(std::get<0>(*ctx)[1], pc->mat, pc->pmat));
191813044ca3SPierre Jolivet             PetscCall(PCSetType(std::get<0>(*ctx)[1], PCHPDDM));
191913044ca3SPierre Jolivet             PetscCall(PCHPDDMSetAuxiliaryMat(std::get<0>(*ctx)[1], uis, uaux, nullptr, nullptr)); /* transfer ownership of the auxiliary inputs from the inner (PCKSP) to the inner-most (PCHPDDM) PC */
1920cf67ef9dSPierre Jolivet             if (flg) static_cast<PC_HPDDM *>(std::get<0>(*ctx)[1]->data)->Neumann = PETSC_BOOL3_TRUE;
192113044ca3SPierre Jolivet             PetscCall(PCSetFromOptions(std::get<0>(*ctx)[1]));
192213044ca3SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)uis));
192313044ca3SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)uaux));
192413044ca3SPierre Jolivet             PetscCall(MatCreateShell(PetscObjectComm((PetscObject)pc), inner->mat->rmap->n, inner->mat->cmap->n, inner->mat->rmap->N, inner->mat->cmap->N, ctx, &S)); /* MatShell computing the action of M^-1 A or A M^-1 */
192513044ca3SPierre Jolivet             PetscCall(MatShellSetOperation(S, MATOP_MULT, (void (*)(void))MatMult_SchurCorrection));
192613044ca3SPierre Jolivet             PetscCall(MatShellSetOperation(S, MATOP_VIEW, (void (*)(void))MatView_SchurCorrection));
192713044ca3SPierre Jolivet             PetscCall(MatShellSetOperation(S, MATOP_DESTROY, (void (*)(void))MatDestroy_SchurCorrection));
192813044ca3SPierre Jolivet             PetscCall(KSPGetPCSide(inner_ksp, &(std::get<2>(*ctx))));
192913044ca3SPierre Jolivet             if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) {
193013044ca3SPierre Jolivet               PetscCall(KSPSetPreSolve(inner_ksp, KSPPreSolve_SchurCorrection, ctx));
193113044ca3SPierre Jolivet             } else { /* no support for PC_SYMMETRIC */
193213044ca3SPierre Jolivet               PetscCheck(std::get<2>(*ctx) == PC_RIGHT, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "PCSide %s (!= %s or %s or %s)", PCSides[std::get<2>(*ctx)], PCSides[PC_SIDE_DEFAULT], PCSides[PC_LEFT], PCSides[PC_RIGHT]);
193313044ca3SPierre Jolivet             }
193413044ca3SPierre Jolivet             PetscCall(KSPSetPostSolve(inner_ksp, KSPPostSolve_SchurCorrection, ctx));
1935715c1178SPierre Jolivet             PetscCall(PetscObjectContainerCompose((PetscObject)std::get<0>(*ctx)[1], "_PCHPDDM_Schur", ctx, nullptr));
193613044ca3SPierre Jolivet             PetscCall(PCSetUp(std::get<0>(*ctx)[1]));
193713044ca3SPierre Jolivet             PetscCall(KSPSetOperators(inner_ksp, S, S));
193813044ca3SPierre Jolivet             PetscCall(MatCreateVecs(std::get<1>(*ctx)[0], std::get<3>(*ctx), std::get<3>(*ctx) + 1));
193913044ca3SPierre Jolivet             PetscCall(VecDuplicate(std::get<3>(*ctx)[0], std::get<3>(*ctx) + 2));
194013044ca3SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)inner_ksp));
194113044ca3SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)S));
19420307214fSPierre Jolivet             for (std::vector<Vec>::iterator it = initial.begin(); it != initial.end(); ++it) PetscCall(VecDestroy(&*it));
194313044ca3SPierre Jolivet             PetscFunctionReturn(PETSC_SUCCESS);
194413044ca3SPierre Jolivet           } else { /* second call to PCSetUp() on the PC associated to the Schur complement, retrieve previously set context */
194513044ca3SPierre Jolivet             PetscCall(PetscContainerGetPointer(container, (void **)&ctx));
194613044ca3SPierre Jolivet           }
194713044ca3SPierre Jolivet         }
194813044ca3SPierre Jolivet       }
194913044ca3SPierre Jolivet     }
1950f1580f4eSBarry Smith     if (!data->is && data->N > 1) {
1951f1580f4eSBarry Smith       char type[256] = {}; /* same size as in src/ksp/pc/interface/pcset.c */
1952811e8887SPierre Jolivet 
1953f1580f4eSBarry Smith       PetscCall(PetscObjectTypeCompareAny((PetscObject)P, &flg, MATNORMAL, MATNORMALHERMITIAN, ""));
1954f1580f4eSBarry Smith       if (flg || (A->rmap->N != A->cmap->N && P->rmap->N == P->cmap->N && P->rmap->N == A->cmap->N)) {
1955f1580f4eSBarry Smith         Mat B;
1956811e8887SPierre Jolivet 
1957f1580f4eSBarry Smith         PetscCall(PCHPDDMSetAuxiliaryMatNormal_Private(pc, A, P, &B, pcpre));
1958f1580f4eSBarry Smith         if (data->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED) data->correction = PC_HPDDM_COARSE_CORRECTION_BALANCED;
1959f1580f4eSBarry Smith         PetscCall(MatDestroy(&B));
1960f1580f4eSBarry Smith       } else {
1961f1580f4eSBarry Smith         PetscCall(PetscObjectTypeCompare((PetscObject)P, MATSCHURCOMPLEMENT, &flg));
1962f1580f4eSBarry Smith         if (flg) {
1963f1580f4eSBarry Smith           Mat                 A00, P00, A01, A10, A11, B, N;
196413044ca3SPierre Jolivet           PCHPDDMSchurPreType type = PC_HPDDM_SCHUR_PRE_LEAST_SQUARES;
196513044ca3SPierre Jolivet 
196613044ca3SPierre Jolivet           PetscCall(MatSchurComplementGetSubMatrices(P, &A00, &P00, &A01, &A10, &A11));
196713044ca3SPierre Jolivet           PetscCall(PetscOptionsGetEnum(nullptr, pcpre, "-pc_hpddm_schur_precondition", PCHPDDMSchurPreTypes, (PetscEnum *)&type, &flg));
196813044ca3SPierre Jolivet           if (type == PC_HPDDM_SCHUR_PRE_LEAST_SQUARES) {
1969281f8ce6SPierre Jolivet             Mat                        B01;
19703df4cd7bSPierre Jolivet             Vec                        diagonal = nullptr;
1971f1580f4eSBarry Smith             const PetscScalar         *array;
1972f1580f4eSBarry Smith             MatSchurComplementAinvType type;
1973f1580f4eSBarry Smith 
1974281f8ce6SPierre Jolivet             PetscCall(PCHPDDMCheckSymmetry_Private(pc, A01, A10, &B01));
1975f1580f4eSBarry Smith             if (A11) {
19763df4cd7bSPierre Jolivet               PetscCall(MatCreateVecs(A11, &diagonal, nullptr));
19773df4cd7bSPierre Jolivet               PetscCall(MatGetDiagonal(A11, diagonal));
1978f1580f4eSBarry Smith             }
1979db4a47b3SPierre Jolivet             PetscCall(MatCreateVecs(P00, &v, nullptr));
1980f1580f4eSBarry Smith             PetscCall(MatSchurComplementGetAinvType(P, &type));
1981f1580f4eSBarry Smith             PetscCheck(type == MAT_SCHUR_COMPLEMENT_AINV_DIAG || type == MAT_SCHUR_COMPLEMENT_AINV_LUMP, PetscObjectComm((PetscObject)P), PETSC_ERR_SUP, "-%smat_schur_complement_ainv_type %s", ((PetscObject)P)->prefix ? ((PetscObject)P)->prefix : "", MatSchurComplementAinvTypes[type]);
1982f1580f4eSBarry Smith             if (type == MAT_SCHUR_COMPLEMENT_AINV_LUMP) {
1983f1580f4eSBarry Smith               PetscCall(MatGetRowSum(P00, v));
1984f1580f4eSBarry Smith               if (A00 == P00) PetscCall(PetscObjectReference((PetscObject)A00));
1985f1580f4eSBarry Smith               PetscCall(MatDestroy(&P00));
1986f1580f4eSBarry Smith               PetscCall(VecGetArrayRead(v, &array));
1987db4a47b3SPierre Jolivet               PetscCall(MatCreateAIJ(PetscObjectComm((PetscObject)A00), A00->rmap->n, A00->cmap->n, A00->rmap->N, A00->cmap->N, 1, nullptr, 0, nullptr, &P00));
1988f1580f4eSBarry Smith               PetscCall(MatSetOption(P00, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
1989f1580f4eSBarry Smith               for (n = A00->rmap->rstart; n < A00->rmap->rend; ++n) PetscCall(MatSetValue(P00, n, n, array[n - A00->rmap->rstart], INSERT_VALUES));
1990f1580f4eSBarry Smith               PetscCall(MatAssemblyBegin(P00, MAT_FINAL_ASSEMBLY));
1991f1580f4eSBarry Smith               PetscCall(MatAssemblyEnd(P00, MAT_FINAL_ASSEMBLY));
1992f1580f4eSBarry Smith               PetscCall(VecRestoreArrayRead(v, &array));
1993f1580f4eSBarry Smith               PetscCall(MatSchurComplementUpdateSubMatrices(P, A00, P00, A01, A10, A11)); /* replace P00 by diag(sum of each row of P00) */
1994f1580f4eSBarry Smith               PetscCall(MatDestroy(&P00));
1995f1580f4eSBarry Smith             } else PetscCall(MatGetDiagonal(P00, v));
1996f1580f4eSBarry Smith             PetscCall(VecReciprocal(v)); /* inv(diag(P00))       */
1997f1580f4eSBarry Smith             PetscCall(VecSqrtAbs(v));    /* sqrt(inv(diag(P00))) */
1998f1580f4eSBarry Smith             PetscCall(MatDuplicate(A01, MAT_COPY_VALUES, &B));
1999db4a47b3SPierre Jolivet             PetscCall(MatDiagonalScale(B, v, nullptr));
2000281f8ce6SPierre Jolivet             if (B01) PetscCall(MatDiagonalScale(B01, v, nullptr));
2001f1580f4eSBarry Smith             PetscCall(VecDestroy(&v));
2002f1580f4eSBarry Smith             PetscCall(MatCreateNormalHermitian(B, &N));
2003281f8ce6SPierre Jolivet             PetscCall(PCHPDDMSetAuxiliaryMatNormal_Private(pc, B, N, &P, pcpre, &diagonal, B01));
2004f1580f4eSBarry Smith             PetscCall(PetscObjectTypeCompare((PetscObject)data->aux, MATSEQAIJ, &flg));
2005f1580f4eSBarry Smith             if (!flg) {
2006f1580f4eSBarry Smith               PetscCall(MatDestroy(&P));
2007f1580f4eSBarry Smith               P = N;
2008f1580f4eSBarry Smith               PetscCall(PetscObjectReference((PetscObject)P));
2009feebddf4SPierre Jolivet             }
20103df4cd7bSPierre Jolivet             if (diagonal) {
20113df4cd7bSPierre Jolivet               PetscCall(MatDiagonalSet(P, diagonal, ADD_VALUES));
2012feebddf4SPierre Jolivet               PetscCall(PCSetOperators(pc, P, P)); /* replace P by A01^T inv(diag(P00)) A01 - diag(P11) */
20133df4cd7bSPierre Jolivet               PetscCall(VecDestroy(&diagonal));
2014281f8ce6SPierre Jolivet             } else PetscCall(PCSetOperators(pc, B01 ? P : N, P));  /* replace P by A01^T inv(diag(P00)) A01                         */
2015feebddf4SPierre Jolivet             pc->ops->postsolve = PCPostSolve_SchurPreLeastSquares; /*  PCFIELDSPLIT expect a KSP for (P11 - A10 inv(diag(P00)) A01) */
2016feebddf4SPierre Jolivet             PetscCall(MatDestroy(&N));                             /*  but a PC for (A10 inv(diag(P00)) A10 - P11) is setup instead */
2017feebddf4SPierre Jolivet             PetscCall(MatDestroy(&P));                             /*  so the sign of the solution must be flipped                  */
2018f1580f4eSBarry Smith             PetscCall(MatDestroy(&B));
201913044ca3SPierre Jolivet           } else
2020fd310a01SPierre Jolivet             PetscCheck(type != PC_HPDDM_SCHUR_PRE_GENEO, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s without a prior call to PCHPDDMSetAuxiliaryMat() on the A11 block%s%s", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type], pcpre ? " -" : "", pcpre ? pcpre : "");
20210307214fSPierre Jolivet           for (std::vector<Vec>::iterator it = initial.begin(); it != initial.end(); ++it) PetscCall(VecDestroy(&*it));
20223ba16761SJacob Faibussowitsch           PetscFunctionReturn(PETSC_SUCCESS);
2023f1580f4eSBarry Smith         } else {
2024db4a47b3SPierre Jolivet           PetscCall(PetscOptionsGetString(nullptr, pcpre, "-pc_hpddm_levels_1_st_pc_type", type, sizeof(type), nullptr));
2025f1580f4eSBarry Smith           PetscCall(PetscStrcmp(type, PCMAT, &algebraic));
2026b07dfdedSPierre Jolivet           PetscCheck(!algebraic || !block, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-pc_hpddm_levels_1_st_pc_type mat and -pc_hpddm_block_splitting");
20279bb5c669SPierre Jolivet           if (overlap != -1) {
20289bb5c669SPierre Jolivet             PetscCheck(!block && !algebraic, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-pc_hpddm_%s and -pc_hpddm_harmonic_overlap", block ? "block_splitting" : "levels_1_st_pc_type mat");
20299bb5c669SPierre Jolivet             PetscCheck(overlap >= 1, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_WRONG, "-pc_hpddm_harmonic_overlap %" PetscInt_FMT " < 1", overlap);
20309bb5c669SPierre Jolivet           }
20319bb5c669SPierre Jolivet           if (block || overlap != -1) algebraic = PETSC_TRUE;
2032f1580f4eSBarry Smith           if (algebraic) {
2033f1580f4eSBarry Smith             PetscCall(ISCreateStride(PETSC_COMM_SELF, P->rmap->n, P->rmap->rstart, 1, &data->is));
2034f1580f4eSBarry Smith             PetscCall(MatIncreaseOverlap(P, 1, &data->is, 1));
2035f1580f4eSBarry Smith             PetscCall(ISSort(data->is));
20369bb5c669SPierre Jolivet           } else
20379bb5c669SPierre Jolivet             PetscCall(PetscInfo(pc, "Cannot assemble a fully-algebraic coarse operator with an assembled Pmat and -%spc_hpddm_levels_1_st_pc_type != mat and -%spc_hpddm_block_splitting != true and -%spc_hpddm_harmonic_overlap < 1\n", pcpre ? pcpre : "", pcpre ? pcpre : "", pcpre ? pcpre : ""));
2038f1580f4eSBarry Smith         }
2039f1580f4eSBarry Smith       }
2040f1580f4eSBarry Smith     }
2041f1580f4eSBarry Smith   }
2042398c7888SPierre Jolivet #if PetscDefined(USE_DEBUG)
2043398c7888SPierre Jolivet   if (data->is) PetscCall(ISDuplicate(data->is, &dis));
2044398c7888SPierre Jolivet   if (data->aux) PetscCall(MatDuplicate(data->aux, MAT_COPY_VALUES, &daux));
2045398c7888SPierre Jolivet #endif
2046f1580f4eSBarry Smith   if (data->is || (ismatis && data->N > 1)) {
2047f1580f4eSBarry Smith     if (ismatis) {
2048f1580f4eSBarry Smith       std::initializer_list<std::string> list = {MATSEQBAIJ, MATSEQSBAIJ};
2049f1580f4eSBarry Smith       PetscCall(MatISGetLocalMat(P, &N));
2050f1580f4eSBarry Smith       std::initializer_list<std::string>::const_iterator it = std::find(list.begin(), list.end(), ((PetscObject)N)->type_name);
2051f1580f4eSBarry Smith       PetscCall(MatISRestoreLocalMat(P, &N));
2052f1580f4eSBarry Smith       switch (std::distance(list.begin(), it)) {
2053d71ae5a4SJacob Faibussowitsch       case 0:
2054d71ae5a4SJacob Faibussowitsch         PetscCall(MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &C));
2055d71ae5a4SJacob Faibussowitsch         break;
2056f1580f4eSBarry Smith       case 1:
2057f1580f4eSBarry Smith         /* MatCreateSubMatrices() does not work with MATSBAIJ and unsorted ISes, so convert to MPIBAIJ */
2058f1580f4eSBarry Smith         PetscCall(MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &C));
2059f1580f4eSBarry Smith         PetscCall(MatSetOption(C, MAT_SYMMETRIC, PETSC_TRUE));
2060f1580f4eSBarry Smith         break;
2061d71ae5a4SJacob Faibussowitsch       default:
2062d71ae5a4SJacob Faibussowitsch         PetscCall(MatConvert(P, MATMPIAIJ, MAT_INITIAL_MATRIX, &C));
2063f1580f4eSBarry Smith       }
2064db4a47b3SPierre Jolivet       PetscCall(MatISGetLocalToGlobalMapping(P, &l2g, nullptr));
2065f1580f4eSBarry Smith       PetscCall(PetscObjectReference((PetscObject)P));
2066f1580f4eSBarry Smith       PetscCall(KSPSetOperators(data->levels[0]->ksp, A, C));
2067f1580f4eSBarry Smith       std::swap(C, P);
2068f1580f4eSBarry Smith       PetscCall(ISLocalToGlobalMappingGetSize(l2g, &n));
2069f1580f4eSBarry Smith       PetscCall(ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &loc));
2070f1580f4eSBarry Smith       PetscCall(ISLocalToGlobalMappingApplyIS(l2g, loc, &is[0]));
2071f1580f4eSBarry Smith       PetscCall(ISDestroy(&loc));
2072f1580f4eSBarry Smith       /* the auxiliary Mat is _not_ the local Neumann matrix                                */
2073f1580f4eSBarry Smith       /* it is the local Neumann matrix augmented (with zeros) through MatIncreaseOverlap() */
2074c8ea6600SPierre Jolivet       data->Neumann = PETSC_BOOL3_FALSE;
2075f1580f4eSBarry Smith       structure     = SAME_NONZERO_PATTERN;
2076f1580f4eSBarry Smith     } else {
2077f1580f4eSBarry Smith       is[0] = data->is;
207813044ca3SPierre Jolivet       if (algebraic || ctx) subdomains = PETSC_TRUE;
2079db4a47b3SPierre Jolivet       PetscCall(PetscOptionsGetBool(nullptr, pcpre, "-pc_hpddm_define_subdomains", &subdomains, nullptr));
208013044ca3SPierre Jolivet       if (ctx) PetscCheck(subdomains, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition geneo and -%spc_hpddm_define_subdomains false", pcpre, pcpre);
2081c8ea6600SPierre Jolivet       if (PetscBool3ToBool(data->Neumann)) {
2082b07dfdedSPierre Jolivet         PetscCheck(!block, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-pc_hpddm_block_splitting and -pc_hpddm_has_neumann");
20839bb5c669SPierre Jolivet         PetscCheck(overlap == -1, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-pc_hpddm_harmonic_overlap %" PetscInt_FMT " and -pc_hpddm_has_neumann", overlap);
2084b07dfdedSPierre Jolivet         PetscCheck(!algebraic, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-pc_hpddm_levels_1_st_pc_type mat and -pc_hpddm_has_neumann");
2085f1580f4eSBarry Smith       }
2086c8ea6600SPierre Jolivet       if (PetscBool3ToBool(data->Neumann) || block) structure = SAME_NONZERO_PATTERN;
2087f1580f4eSBarry Smith       PetscCall(ISCreateStride(PetscObjectComm((PetscObject)data->is), P->rmap->n, P->rmap->rstart, 1, &loc));
2088f1580f4eSBarry Smith     }
2089f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_", pcpre ? pcpre : ""));
2090db4a47b3SPierre Jolivet     PetscCall(PetscOptionsGetEnum(nullptr, prefix, "-st_matstructure", MatStructures, (PetscEnum *)&structure, &flg)); /* if not user-provided, force its value when possible */
2091f1580f4eSBarry Smith     if (!flg && structure == SAME_NONZERO_PATTERN) {                                                                   /* cannot call STSetMatStructure() yet, insert the appropriate option in the database, parsed by STSetFromOptions() */
2092f1580f4eSBarry Smith       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-%spc_hpddm_levels_1_st_matstructure", pcpre ? pcpre : ""));
2093db4a47b3SPierre Jolivet       PetscCall(PetscOptionsSetValue(nullptr, prefix, MatStructures[structure]));
2094f1580f4eSBarry Smith     }
2095398c7888SPierre Jolivet     flg = PETSC_FALSE;
2096b07dfdedSPierre Jolivet     if (data->share) {
2097398c7888SPierre Jolivet       data->share = PETSC_FALSE; /* will be reset to PETSC_TRUE if none of the conditions below are true */
2098398c7888SPierre Jolivet       if (!subdomains) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since -%spc_hpddm_define_subdomains is not true\n", pcpre ? pcpre : ""));
2099398c7888SPierre Jolivet       else if (data->deflation) PetscCall(PetscInfo(pc, "Nothing to share since PCHPDDMSetDeflationMat() has been called\n"));
2100398c7888SPierre Jolivet       else if (ismatis) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc with a Pmat of type MATIS\n"));
2101b07dfdedSPierre Jolivet       else if (!algebraic && structure != SAME_NONZERO_PATTERN)
2102398c7888SPierre Jolivet         PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since -%spc_hpddm_levels_1_st_matstructure %s (!= %s)\n", pcpre ? pcpre : "", MatStructures[structure], MatStructures[SAME_NONZERO_PATTERN]));
2103398c7888SPierre Jolivet       else data->share = PETSC_TRUE;
2104398c7888SPierre Jolivet     }
2105398c7888SPierre Jolivet     if (!ismatis) {
2106398c7888SPierre Jolivet       if (data->share || (!PetscBool3ToBool(data->Neumann) && subdomains)) PetscCall(ISDuplicate(is[0], &unsorted));
2107398c7888SPierre Jolivet       else unsorted = is[0];
2108398c7888SPierre Jolivet     }
2109f1580f4eSBarry Smith     if (data->N > 1 && (data->aux || ismatis || algebraic)) {
2110f1580f4eSBarry Smith       PetscCheck(loadedSym, PETSC_COMM_SELF, PETSC_ERR_PLIB, "HPDDM library not loaded, cannot use more than one level");
2111f1580f4eSBarry Smith       PetscCall(MatSetOption(P, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
2112f1580f4eSBarry Smith       if (ismatis) {
2113f1580f4eSBarry Smith         /* needed by HPDDM (currently) so that the partition of unity is 0 on subdomain interfaces */
2114f1580f4eSBarry Smith         PetscCall(MatIncreaseOverlap(P, 1, is, 1));
2115f1580f4eSBarry Smith         PetscCall(ISDestroy(&data->is));
2116f1580f4eSBarry Smith         data->is = is[0];
2117f1580f4eSBarry Smith       } else {
2118d16c0b94SPierre Jolivet         if (PetscDefined(USE_DEBUG)) PetscCall(PCHPDDMCheckInclusion_Private(pc, data->is, loc, PETSC_TRUE));
21199bb5c669SPierre Jolivet         if (overlap == -1) PetscCall(PetscObjectComposeFunction((PetscObject)pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_Private_C", PCHPDDMAlgebraicAuxiliaryMat_Private));
21209bb5c669SPierre Jolivet         if (!PetscBool3ToBool(data->Neumann) && (!algebraic || overlap != -1)) {
2121f1580f4eSBarry Smith           PetscCall(PetscObjectTypeCompare((PetscObject)P, MATMPISBAIJ, &flg));
2122f1580f4eSBarry Smith           if (flg) {
2123f1580f4eSBarry Smith             /* maybe better to ISSort(is[0]), MatCreateSubMatrices(), and then MatPermute() */
2124f1580f4eSBarry Smith             /* but there is no MatPermute_SeqSBAIJ(), so as before, just use MATMPIBAIJ     */
2125f1580f4eSBarry Smith             PetscCall(MatConvert(P, MATMPIBAIJ, MAT_INITIAL_MATRIX, &uaux));
2126f1580f4eSBarry Smith             flg = PETSC_FALSE;
2127f1580f4eSBarry Smith           }
2128f1580f4eSBarry Smith         }
2129f1580f4eSBarry Smith       }
21309bb5c669SPierre Jolivet       if (algebraic && overlap == -1) {
2131f1580f4eSBarry Smith         PetscUseMethod(pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_Private_C", (Mat, IS *, Mat *[], PetscBool), (P, is, &sub, block));
2132f1580f4eSBarry Smith         if (block) {
2133f1580f4eSBarry Smith           PetscCall(PetscObjectQuery((PetscObject)sub[0], "_PCHPDDM_Neumann_Mat", (PetscObject *)&data->aux));
2134db4a47b3SPierre Jolivet           PetscCall(PetscObjectCompose((PetscObject)sub[0], "_PCHPDDM_Neumann_Mat", nullptr));
2135f1580f4eSBarry Smith         }
21369bb5c669SPierre Jolivet       } else if (!uaux || overlap != -1) {
213713044ca3SPierre Jolivet         if (!ctx) {
2138c8ea6600SPierre Jolivet           if (PetscBool3ToBool(data->Neumann)) sub = &data->aux;
21399bb5c669SPierre Jolivet           else {
2140df21ef68SPierre Jolivet             PetscBool flg;
21419bb5c669SPierre Jolivet             if (overlap != -1) {
21429bb5c669SPierre Jolivet               Harmonic              h;
21439bb5c669SPierre Jolivet               Mat                   A0, *a;                    /* with an SVD: [ A_00  A_01       ] */
21449bb5c669SPierre Jolivet               IS                    ov[2], rows, cols, stride; /*              [ A_10  A_11  A_12 ] */
214558b7e2c1SStefano Zampini               const PetscInt       *i[2], bs = P->cmap->bs;    /* with a GEVP: [ A_00  A_01       ] */
21469bb5c669SPierre Jolivet               PetscInt              n[2];                      /*              [ A_10  A_11  A_12 ] */
21479bb5c669SPierre Jolivet               std::vector<PetscInt> v[2];                      /*              [       A_21  A_22 ] */
21489bb5c669SPierre Jolivet 
21499bb5c669SPierre Jolivet               PetscCall(ISDuplicate(data->is, ov));
21509bb5c669SPierre Jolivet               if (overlap > 1) PetscCall(MatIncreaseOverlap(P, 1, ov, overlap - 1));
21519bb5c669SPierre Jolivet               PetscCall(ISDuplicate(ov[0], ov + 1));
21529bb5c669SPierre Jolivet               PetscCall(MatIncreaseOverlap(P, 1, ov + 1, 1));
21539bb5c669SPierre Jolivet               PetscCall(PetscNew(&h));
21549bb5c669SPierre Jolivet               h->ksp = nullptr;
21559bb5c669SPierre Jolivet               PetscCall(PetscCalloc1(2, &h->A));
21563a60673dSPierre Jolivet               PetscCall(PetscOptionsHasName(nullptr, prefix, "-svd_nsv", &flg));
21579bb5c669SPierre Jolivet               if (!flg) PetscCall(PetscOptionsHasName(nullptr, prefix, "-svd_relative_threshold", &flg));
21589bb5c669SPierre Jolivet               PetscCall(ISSort(ov[0]));
21599bb5c669SPierre Jolivet               if (!flg) PetscCall(ISSort(ov[1]));
216032603206SJames Wright               PetscCall(PetscCalloc1(5, &h->is));
21619bb5c669SPierre Jolivet               PetscCall(MatCreateSubMatrices(uaux ? uaux : P, 1, ov + !flg, ov + 1, MAT_INITIAL_MATRIX, &a)); /* submatrix from above, either square (!flg) or rectangular (flg) */
21629bb5c669SPierre Jolivet               for (PetscInt j = 0; j < 2; ++j) {
21639bb5c669SPierre Jolivet                 PetscCall(ISGetIndices(ov[j], i + j));
21649bb5c669SPierre Jolivet                 PetscCall(ISGetLocalSize(ov[j], n + j));
21659bb5c669SPierre Jolivet               }
21669bb5c669SPierre Jolivet               v[1].reserve((n[1] - n[0]) / bs);
21679bb5c669SPierre Jolivet               for (PetscInt j = 0; j < n[1]; j += bs) { /* indices of the (2,2) block */
21689bb5c669SPierre Jolivet                 PetscInt location;
21699bb5c669SPierre Jolivet                 PetscCall(ISLocate(ov[0], i[1][j], &location));
21709bb5c669SPierre Jolivet                 if (location < 0) v[1].emplace_back(j / bs);
21719bb5c669SPierre Jolivet               }
21729bb5c669SPierre Jolivet               if (!flg) {
21739bb5c669SPierre Jolivet                 h->A[1] = a[0];
21749bb5c669SPierre Jolivet                 PetscCall(PetscObjectReference((PetscObject)h->A[1]));
21759bb5c669SPierre Jolivet                 v[0].reserve((n[0] - P->rmap->n) / bs);
21769bb5c669SPierre Jolivet                 for (PetscInt j = 0; j < n[1]; j += bs) { /* row indices of the (1,2) block */
21779bb5c669SPierre Jolivet                   PetscInt location;
21789bb5c669SPierre Jolivet                   PetscCall(ISLocate(loc, i[1][j], &location));
21799bb5c669SPierre Jolivet                   if (location < 0) {
21809bb5c669SPierre Jolivet                     PetscCall(ISLocate(ov[0], i[1][j], &location));
21819bb5c669SPierre Jolivet                     if (location >= 0) v[0].emplace_back(j / bs);
21829bb5c669SPierre Jolivet                   }
21839bb5c669SPierre Jolivet                 }
21849bb5c669SPierre Jolivet                 PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[0].size(), v[0].data(), PETSC_USE_POINTER, &rows));
21859bb5c669SPierre Jolivet                 PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[1].size(), v[1].data(), PETSC_COPY_VALUES, h->is + 4));
21869bb5c669SPierre Jolivet                 PetscCall(MatCreateSubMatrix(a[0], rows, h->is[4], MAT_INITIAL_MATRIX, h->A)); /* A_12 submatrix from above */
21879bb5c669SPierre Jolivet                 PetscCall(ISDestroy(&rows));
21889bb5c669SPierre Jolivet                 if (uaux) PetscCall(MatConvert(a[0], MATSEQSBAIJ, MAT_INPLACE_MATRIX, a)); /* initial Pmat was MATSBAIJ, convert back to the same format since the rectangular A_12 submatrix has been created */
21899bb5c669SPierre Jolivet                 PetscCall(ISEmbed(ov[0], ov[1], PETSC_TRUE, &rows));
21909bb5c669SPierre Jolivet                 PetscCall(MatCreateSubMatrix(a[0], rows, cols = rows, MAT_INITIAL_MATRIX, &A0)); /* [ A_00  A_01 ; A_10  A_11 ] submatrix from above */
21919bb5c669SPierre Jolivet                 PetscCall(ISDestroy(&rows));
21929bb5c669SPierre Jolivet                 v[0].clear();
21939bb5c669SPierre Jolivet                 PetscCall(ISEmbed(loc, ov[1], PETSC_TRUE, h->is + 3));
21949bb5c669SPierre Jolivet                 PetscCall(ISEmbed(data->is, ov[1], PETSC_TRUE, h->is + 2));
21959bb5c669SPierre Jolivet               }
21969bb5c669SPierre Jolivet               v[0].reserve((n[0] - P->rmap->n) / bs);
21979bb5c669SPierre Jolivet               for (PetscInt j = 0; j < n[0]; j += bs) {
21989bb5c669SPierre Jolivet                 PetscInt location;
21999bb5c669SPierre Jolivet                 PetscCall(ISLocate(loc, i[0][j], &location));
22009bb5c669SPierre Jolivet                 if (location < 0) v[0].emplace_back(j / bs);
22019bb5c669SPierre Jolivet               }
22029bb5c669SPierre Jolivet               PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[0].size(), v[0].data(), PETSC_USE_POINTER, &rows));
22039bb5c669SPierre Jolivet               for (PetscInt j = 0; j < 2; ++j) PetscCall(ISRestoreIndices(ov[j], i + j));
22049bb5c669SPierre Jolivet               if (flg) {
22059bb5c669SPierre Jolivet                 IS is;
22069bb5c669SPierre Jolivet                 PetscCall(ISCreateStride(PETSC_COMM_SELF, a[0]->rmap->n, 0, 1, &is));
22079bb5c669SPierre Jolivet                 PetscCall(ISEmbed(ov[0], ov[1], PETSC_TRUE, &cols));
22089bb5c669SPierre Jolivet                 PetscCall(MatCreateSubMatrix(a[0], is, cols, MAT_INITIAL_MATRIX, &A0)); /* [ A_00  A_01 ; A_10  A_11 ] submatrix from above */
22099bb5c669SPierre Jolivet                 PetscCall(ISDestroy(&cols));
22109bb5c669SPierre Jolivet                 PetscCall(ISDestroy(&is));
22119bb5c669SPierre Jolivet                 if (uaux) PetscCall(MatConvert(A0, MATSEQSBAIJ, MAT_INPLACE_MATRIX, &A0)); /* initial Pmat was MATSBAIJ, convert back to the same format since this submatrix is square */
22129bb5c669SPierre Jolivet                 PetscCall(ISEmbed(loc, data->is, PETSC_TRUE, h->is + 2));
22139bb5c669SPierre Jolivet                 PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[1].size(), v[1].data(), PETSC_USE_POINTER, &cols));
22149bb5c669SPierre Jolivet                 PetscCall(MatCreateSubMatrix(a[0], rows, cols, MAT_INITIAL_MATRIX, h->A)); /* A_12 submatrix from above */
22159bb5c669SPierre Jolivet                 PetscCall(ISDestroy(&cols));
22169bb5c669SPierre Jolivet               }
22179bb5c669SPierre Jolivet               PetscCall(ISCreateStride(PETSC_COMM_SELF, A0->rmap->n, 0, 1, &stride));
22189bb5c669SPierre Jolivet               PetscCall(ISEmbed(rows, stride, PETSC_TRUE, h->is));
22199bb5c669SPierre Jolivet               PetscCall(ISDestroy(&stride));
22209bb5c669SPierre Jolivet               PetscCall(ISDestroy(&rows));
22219bb5c669SPierre Jolivet               PetscCall(ISEmbed(loc, ov[0], PETSC_TRUE, h->is + 1));
22229bb5c669SPierre Jolivet               if (subdomains) {
22239bb5c669SPierre Jolivet                 if (!data->levels[0]->pc) {
22249bb5c669SPierre Jolivet                   PetscCall(PCCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->pc));
22259bb5c669SPierre Jolivet                   PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_", pcpre ? pcpre : ""));
22269bb5c669SPierre Jolivet                   PetscCall(PCSetOptionsPrefix(data->levels[0]->pc, prefix));
22279bb5c669SPierre Jolivet                   PetscCall(PCSetOperators(data->levels[0]->pc, A, P));
22289bb5c669SPierre Jolivet                 }
22299bb5c669SPierre Jolivet                 PetscCall(PCSetType(data->levels[0]->pc, PCASM));
22309bb5c669SPierre Jolivet                 if (!data->levels[0]->pc->setupcalled) PetscCall(PCASMSetLocalSubdomains(data->levels[0]->pc, 1, ov + !flg, &loc));
22319bb5c669SPierre Jolivet                 PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(data->levels[0]->pc, flg ? A0 : a[0], PETSC_TRUE));
22329bb5c669SPierre Jolivet                 if (!flg) ++overlap;
22339bb5c669SPierre Jolivet                 if (data->share) {
22349bb5c669SPierre Jolivet                   PetscInt n = -1;
22359bb5c669SPierre Jolivet                   PetscTryMethod(data->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data->levels[0]->pc, &n, nullptr, &ksp));
22369bb5c669SPierre Jolivet                   PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
22379bb5c669SPierre Jolivet                   if (flg) {
22389bb5c669SPierre Jolivet                     h->ksp = ksp[0];
22399bb5c669SPierre Jolivet                     PetscCall(PetscObjectReference((PetscObject)h->ksp));
22409bb5c669SPierre Jolivet                   }
22419bb5c669SPierre Jolivet                 }
22429bb5c669SPierre Jolivet               }
22439bb5c669SPierre Jolivet               if (!h->ksp) {
22449bb5c669SPierre Jolivet                 PetscBool share = data->share;
22459bb5c669SPierre Jolivet                 PetscCall(KSPCreate(PETSC_COMM_SELF, &h->ksp));
22469bb5c669SPierre Jolivet                 PetscCall(KSPSetType(h->ksp, KSPPREONLY));
22479bb5c669SPierre Jolivet                 PetscCall(KSPSetOperators(h->ksp, A0, A0));
22489bb5c669SPierre Jolivet                 do {
22499bb5c669SPierre Jolivet                   if (!data->share) {
22509bb5c669SPierre Jolivet                     share = PETSC_FALSE;
22519bb5c669SPierre Jolivet                     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_%s", pcpre ? pcpre : "", flg ? "svd_" : "eps_"));
22529bb5c669SPierre Jolivet                     PetscCall(KSPSetOptionsPrefix(h->ksp, prefix));
22539bb5c669SPierre Jolivet                     PetscCall(KSPSetFromOptions(h->ksp));
22549bb5c669SPierre Jolivet                   } else {
22559bb5c669SPierre Jolivet                     MatSolverType type;
22569bb5c669SPierre Jolivet                     PetscCall(KSPGetPC(ksp[0], &pc));
22579bb5c669SPierre Jolivet                     PetscCall(PetscObjectTypeCompareAny((PetscObject)pc, &data->share, PCLU, PCCHOLESKY, ""));
22589bb5c669SPierre Jolivet                     if (data->share) {
22599bb5c669SPierre Jolivet                       PetscCall(PCFactorGetMatSolverType(pc, &type));
22609bb5c669SPierre Jolivet                       if (!type) {
22619bb5c669SPierre Jolivet                         if (PetscDefined(HAVE_MUMPS)) PetscCall(PCFactorSetMatSolverType(pc, MATSOLVERMUMPS));
22629bb5c669SPierre Jolivet                         else if (PetscDefined(HAVE_MKL_PARDISO)) PetscCall(PCFactorSetMatSolverType(pc, MATSOLVERMKL_PARDISO));
22639bb5c669SPierre Jolivet                         else data->share = PETSC_FALSE;
22649bb5c669SPierre Jolivet                         if (data->share) PetscCall(PCSetFromOptions(pc));
22659bb5c669SPierre Jolivet                       } else {
22669bb5c669SPierre Jolivet                         PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &data->share));
22679bb5c669SPierre Jolivet                         if (!data->share) PetscCall(PetscStrcmp(type, MATSOLVERMKL_PARDISO, &data->share));
22689bb5c669SPierre Jolivet                       }
22699bb5c669SPierre Jolivet                       if (data->share) {
22709bb5c669SPierre Jolivet                         std::tuple<KSP, IS, Vec[2]> *p;
22719bb5c669SPierre Jolivet                         PetscCall(PCFactorGetMatrix(pc, &A));
22729bb5c669SPierre Jolivet                         PetscCall(MatFactorSetSchurIS(A, h->is[4]));
22739bb5c669SPierre Jolivet                         PetscCall(KSPSetUp(ksp[0]));
22749bb5c669SPierre Jolivet                         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_eps_shell_", pcpre ? pcpre : ""));
22759bb5c669SPierre Jolivet                         PetscCall(KSPSetOptionsPrefix(h->ksp, prefix));
22769bb5c669SPierre Jolivet                         PetscCall(KSPSetFromOptions(h->ksp));
22779bb5c669SPierre Jolivet                         PetscCall(KSPGetPC(h->ksp, &pc));
22789bb5c669SPierre Jolivet                         PetscCall(PCSetType(pc, PCSHELL));
22799bb5c669SPierre Jolivet                         PetscCall(PetscNew(&p));
22809bb5c669SPierre Jolivet                         std::get<0>(*p) = ksp[0];
22819bb5c669SPierre Jolivet                         PetscCall(ISEmbed(ov[0], ov[1], PETSC_TRUE, &std::get<1>(*p)));
22829bb5c669SPierre Jolivet                         PetscCall(MatCreateVecs(A, std::get<2>(*p), std::get<2>(*p) + 1));
22839bb5c669SPierre Jolivet                         PetscCall(PCShellSetContext(pc, p));
22849bb5c669SPierre Jolivet                         PetscCall(PCShellSetApply(pc, PCApply_Schur));
22859bb5c669SPierre Jolivet                         PetscCall(PCShellSetApplyTranspose(pc, PCApply_Schur<Vec, true>));
22869bb5c669SPierre Jolivet                         PetscCall(PCShellSetMatApply(pc, PCApply_Schur<Mat>));
22879bb5c669SPierre Jolivet                         PetscCall(PCShellSetDestroy(pc, PCDestroy_Schur));
22889bb5c669SPierre Jolivet                       }
22899bb5c669SPierre Jolivet                     }
22909bb5c669SPierre Jolivet                     if (!data->share) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since neither MUMPS nor MKL PARDISO is used\n"));
22919bb5c669SPierre Jolivet                   }
22929bb5c669SPierre Jolivet                 } while (!share != !data->share); /* if data->share is initially PETSC_TRUE, but then reset to PETSC_FALSE, then go back to the beginning of the do loop */
22939bb5c669SPierre Jolivet               }
22949bb5c669SPierre Jolivet               PetscCall(ISDestroy(ov));
22959bb5c669SPierre Jolivet               PetscCall(ISDestroy(ov + 1));
22969bb5c669SPierre Jolivet               if (overlap == 1 && subdomains && flg) {
22979bb5c669SPierre Jolivet                 *subA = A0;
22989bb5c669SPierre Jolivet                 sub   = subA;
22999bb5c669SPierre Jolivet                 if (uaux) PetscCall(MatDestroy(&uaux));
23009bb5c669SPierre Jolivet               } else PetscCall(MatDestroy(&A0));
23019bb5c669SPierre Jolivet               PetscCall(MatCreateShell(PETSC_COMM_SELF, P->rmap->n, n[1] - n[0], P->rmap->n, n[1] - n[0], h, &data->aux));
2302bdcd51b8SPierre Jolivet               PetscCall(KSPSetErrorIfNotConverged(h->ksp, PETSC_TRUE)); /* bail out as early as possible to avoid (apparently) unrelated error messages */
23039bb5c669SPierre Jolivet               PetscCall(MatCreateVecs(h->ksp->pc->pmat, &h->v, nullptr));
23049bb5c669SPierre Jolivet               PetscCall(MatShellSetOperation(data->aux, MATOP_MULT, (void (*)(void))MatMult_Harmonic));
23059bb5c669SPierre Jolivet               PetscCall(MatShellSetOperation(data->aux, MATOP_MULT_TRANSPOSE, (void (*)(void))MatMultTranspose_Harmonic));
23069bb5c669SPierre Jolivet               PetscCall(MatShellSetMatProductOperation(data->aux, MATPRODUCT_AB, nullptr, MatProduct_AB_Harmonic, nullptr, MATDENSE, MATDENSE));
23079bb5c669SPierre Jolivet               PetscCall(MatShellSetOperation(data->aux, MATOP_DESTROY, (void (*)(void))MatDestroy_Harmonic));
23089bb5c669SPierre Jolivet               PetscCall(MatDestroySubMatrices(1, &a));
23099bb5c669SPierre Jolivet             }
2310df21ef68SPierre Jolivet             if (overlap != 1 || !subdomains) {
2311df21ef68SPierre Jolivet               PetscCall(MatCreateSubMatrices(uaux ? uaux : P, 1, is, is, MAT_INITIAL_MATRIX, &sub));
2312df21ef68SPierre Jolivet               if (ismatis) {
2313df21ef68SPierre Jolivet                 PetscCall(MatISGetLocalMat(C, &N));
2314df21ef68SPierre Jolivet                 PetscCall(PetscObjectTypeCompare((PetscObject)N, MATSEQSBAIJ, &flg));
2315df21ef68SPierre Jolivet                 if (flg) PetscCall(MatConvert(sub[0], MATSEQSBAIJ, MAT_INPLACE_MATRIX, sub));
2316df21ef68SPierre Jolivet                 PetscCall(MatISRestoreLocalMat(C, &N));
2317df21ef68SPierre Jolivet               }
2318df21ef68SPierre Jolivet             }
23199bb5c669SPierre Jolivet             if (uaux) {
23209bb5c669SPierre Jolivet               PetscCall(MatDestroy(&uaux));
23219bb5c669SPierre Jolivet               PetscCall(MatConvert(sub[0], MATSEQSBAIJ, MAT_INPLACE_MATRIX, sub));
23229bb5c669SPierre Jolivet             }
23239bb5c669SPierre Jolivet           }
232413044ca3SPierre Jolivet         }
2325f1580f4eSBarry Smith       } else {
2326f1580f4eSBarry Smith         PetscCall(MatCreateSubMatrices(uaux, 1, is, is, MAT_INITIAL_MATRIX, &sub));
2327f1580f4eSBarry Smith         PetscCall(MatDestroy(&uaux));
2328f1580f4eSBarry Smith         PetscCall(MatConvert(sub[0], MATSEQSBAIJ, MAT_INPLACE_MATRIX, sub));
2329f1580f4eSBarry Smith       }
2330f1580f4eSBarry Smith       /* Vec holding the partition of unity */
2331f1580f4eSBarry Smith       if (!data->levels[0]->D) {
2332f1580f4eSBarry Smith         PetscCall(ISGetLocalSize(data->is, &n));
2333f1580f4eSBarry Smith         PetscCall(VecCreateMPI(PETSC_COMM_SELF, n, PETSC_DETERMINE, &data->levels[0]->D));
2334f1580f4eSBarry Smith       }
23359bb5c669SPierre Jolivet       if (data->share && overlap == -1) {
2336f1580f4eSBarry Smith         Mat      D;
2337db4a47b3SPierre Jolivet         IS       perm = nullptr;
2338f1580f4eSBarry Smith         PetscInt size = -1;
2339811e8887SPierre Jolivet 
2340398c7888SPierre Jolivet         if (!data->levels[0]->pc) {
2341398c7888SPierre Jolivet           PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_", pcpre ? pcpre : ""));
2342398c7888SPierre Jolivet           PetscCall(PCCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->pc));
2343398c7888SPierre Jolivet           PetscCall(PCSetOptionsPrefix(data->levels[0]->pc, prefix));
2344398c7888SPierre Jolivet           PetscCall(PCSetOperators(data->levels[0]->pc, A, P));
2345398c7888SPierre Jolivet         }
2346398c7888SPierre Jolivet         PetscCall(PCSetType(data->levels[0]->pc, PCASM));
234713044ca3SPierre Jolivet         if (!ctx) {
2348398c7888SPierre Jolivet           if (!data->levels[0]->pc->setupcalled) {
2349398c7888SPierre Jolivet             IS sorted; /* PCASM will sort the input IS, duplicate it to return an unmodified (PCHPDDM) input IS */
2350398c7888SPierre Jolivet             PetscCall(ISDuplicate(is[0], &sorted));
2351398c7888SPierre Jolivet             PetscCall(PCASMSetLocalSubdomains(data->levels[0]->pc, 1, &sorted, &loc));
2352398c7888SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)sorted));
2353398c7888SPierre Jolivet           }
2354398c7888SPierre Jolivet           PetscCall(PCSetFromOptions(data->levels[0]->pc));
2355398c7888SPierre Jolivet           if (block) {
2356398c7888SPierre Jolivet             PetscCall(PCHPDDMPermute_Private(unsorted, data->is, &uis, sub[0], &C, &perm));
2357398c7888SPierre Jolivet             PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(data->levels[0]->pc, C, algebraic));
2358398c7888SPierre Jolivet           } else PetscCall(PCSetUp(data->levels[0]->pc));
2359db4a47b3SPierre Jolivet           PetscTryMethod(data->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data->levels[0]->pc, &size, nullptr, &ksp));
2360398c7888SPierre Jolivet           if (size != 1) {
2361398c7888SPierre Jolivet             data->share = PETSC_FALSE;
2362398c7888SPierre Jolivet             PetscCheck(size == -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", size);
2363398c7888SPierre Jolivet             PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since PCASMGetSubKSP() not found in fine-level PC\n"));
2364398c7888SPierre Jolivet             PetscCall(ISDestroy(&unsorted));
2365398c7888SPierre Jolivet             unsorted = is[0];
2366398c7888SPierre Jolivet           } else {
2367811e8887SPierre Jolivet             const char *matpre;
2368811e8887SPierre Jolivet             PetscBool   cmp[4];
2369811e8887SPierre Jolivet 
237013044ca3SPierre Jolivet             if (!block && !ctx) PetscCall(PCHPDDMPermute_Private(unsorted, data->is, &uis, PetscBool3ToBool(data->Neumann) ? sub[0] : data->aux, &C, &perm));
2371c8ea6600SPierre Jolivet             if (!PetscBool3ToBool(data->Neumann) && !block) {
2372f1580f4eSBarry Smith               PetscCall(MatPermute(sub[0], perm, perm, &D)); /* permute since PCASM will call ISSort() */
2373f1580f4eSBarry Smith               PetscCall(MatHeaderReplace(sub[0], &D));
2374f1580f4eSBarry Smith             }
2375f1580f4eSBarry Smith             if (data->B) { /* see PCHPDDMSetRHSMat() */
2376f1580f4eSBarry Smith               PetscCall(MatPermute(data->B, perm, perm, &D));
2377f1580f4eSBarry Smith               PetscCall(MatHeaderReplace(data->B, &D));
2378f1580f4eSBarry Smith             }
2379f1580f4eSBarry Smith             PetscCall(ISDestroy(&perm));
2380f1580f4eSBarry Smith             PetscCall(KSPGetOperators(ksp[0], subA, subA + 1));
23810307214fSPierre Jolivet             PetscCall(PetscObjectReference((PetscObject)subA[0]));
2382f1580f4eSBarry Smith             PetscCall(MatDuplicate(subA[1], MAT_SHARE_NONZERO_PATTERN, &D));
2383f1580f4eSBarry Smith             PetscCall(MatGetOptionsPrefix(subA[1], &matpre));
2384f1580f4eSBarry Smith             PetscCall(MatSetOptionsPrefix(D, matpre));
2385f1580f4eSBarry Smith             PetscCall(PetscObjectTypeCompare((PetscObject)D, MATNORMAL, cmp));
2386f1580f4eSBarry Smith             PetscCall(PetscObjectTypeCompare((PetscObject)C, MATNORMAL, cmp + 1));
2387f1580f4eSBarry Smith             if (!cmp[0]) PetscCall(PetscObjectTypeCompare((PetscObject)D, MATNORMALHERMITIAN, cmp + 2));
2388f1580f4eSBarry Smith             else cmp[2] = PETSC_FALSE;
2389f1580f4eSBarry Smith             if (!cmp[1]) PetscCall(PetscObjectTypeCompare((PetscObject)C, MATNORMALHERMITIAN, cmp + 3));
2390f1580f4eSBarry Smith             else cmp[3] = PETSC_FALSE;
2391f1580f4eSBarry Smith             PetscCheck(cmp[0] == cmp[1] && cmp[2] == cmp[3], PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_levels_1_pc_asm_sub_mat_type %s and auxiliary Mat of type %s", pcpre ? pcpre : "", ((PetscObject)D)->type_name, ((PetscObject)C)->type_name);
2392f1580f4eSBarry Smith             if (!cmp[0] && !cmp[2]) {
2393f1580f4eSBarry Smith               if (!block) PetscCall(MatAXPY(D, 1.0, C, SUBSET_NONZERO_PATTERN));
23945c7345deSPierre Jolivet               else {
2395db4a47b3SPierre Jolivet                 PetscCall(MatMissingDiagonal(D, cmp, nullptr));
23965c7345deSPierre Jolivet                 if (cmp[0]) structure = DIFFERENT_NONZERO_PATTERN; /* data->aux has no missing diagonal entry */
23975c7345deSPierre Jolivet                 PetscCall(MatAXPY(D, 1.0, data->aux, structure));
23985c7345deSPierre Jolivet               }
2399f1580f4eSBarry Smith             } else {
2400f1580f4eSBarry Smith               Mat mat[2];
2401811e8887SPierre Jolivet 
2402f1580f4eSBarry Smith               if (cmp[0]) {
2403f1580f4eSBarry Smith                 PetscCall(MatNormalGetMat(D, mat));
2404f1580f4eSBarry Smith                 PetscCall(MatNormalGetMat(C, mat + 1));
2405f1580f4eSBarry Smith               } else {
2406f1580f4eSBarry Smith                 PetscCall(MatNormalHermitianGetMat(D, mat));
2407f1580f4eSBarry Smith                 PetscCall(MatNormalHermitianGetMat(C, mat + 1));
2408f1580f4eSBarry Smith               }
2409f1580f4eSBarry Smith               PetscCall(MatAXPY(mat[0], 1.0, mat[1], SUBSET_NONZERO_PATTERN));
2410f1580f4eSBarry Smith             }
2411f1580f4eSBarry Smith             PetscCall(MatPropagateSymmetryOptions(C, D));
2412f1580f4eSBarry Smith             PetscCall(MatDestroy(&C));
2413f1580f4eSBarry Smith             C = D;
2414f1580f4eSBarry Smith             /* swap pointers so that variables stay consistent throughout PCSetUp() */
2415f1580f4eSBarry Smith             std::swap(C, data->aux);
2416f1580f4eSBarry Smith             std::swap(uis, data->is);
2417f1580f4eSBarry Smith             swap = PETSC_TRUE;
2418f1580f4eSBarry Smith           }
2419f1580f4eSBarry Smith         }
242013044ca3SPierre Jolivet       }
242113044ca3SPierre Jolivet       if (ctx) {
242213044ca3SPierre Jolivet         PC_HPDDM              *data_00 = (PC_HPDDM *)std::get<0>(*ctx)[0]->data;
242313044ca3SPierre Jolivet         PC                     s;
242400b491fbSPierre Jolivet         Mat                    A00, P00, A01 = nullptr, A10, A11, N, b[4];
242507d8d47fSPierre Jolivet         IS                     sorted, is[2], *is_00;
242613044ca3SPierre Jolivet         MatSolverType          type;
242713044ca3SPierre Jolivet         std::pair<PC, Vec[2]> *p;
242813044ca3SPierre Jolivet 
242907d8d47fSPierre Jolivet         n = -1;
243007d8d47fSPierre Jolivet         PetscTryMethod(data_00->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data_00->levels[0]->pc, &n, nullptr, &ksp));
243107d8d47fSPierre Jolivet         PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
243207d8d47fSPierre Jolivet         PetscCall(KSPGetOperators(ksp[0], subA, subA + 1));
243307d8d47fSPierre Jolivet         PetscCall(ISGetLocalSize(data_00->is, &n));
243407d8d47fSPierre Jolivet         if (n != subA[0]->rmap->n || n != subA[0]->cmap->n) {
243507d8d47fSPierre Jolivet           PetscCall(PCASMGetLocalSubdomains(data_00->levels[0]->pc, &n, &is_00, nullptr));
243607d8d47fSPierre Jolivet           PetscCall(ISGetLocalSize(*is_00, &n));
243707d8d47fSPierre Jolivet           PetscCheck(n == subA[0]->rmap->n && n == subA[0]->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition geneo and -%spc_hpddm_define_subdomains false", pcpre ? pcpre : "", ((PetscObject)pc)->prefix);
243807d8d47fSPierre Jolivet         } else is_00 = &data_00->is;
243913044ca3SPierre Jolivet         PetscCall(PCHPDDMPermute_Private(unsorted, data->is, &uis, data->aux, &C, nullptr)); /* permute since PCASM works with a sorted IS */
244013044ca3SPierre Jolivet         std::swap(C, data->aux);
244113044ca3SPierre Jolivet         std::swap(uis, data->is);
244213044ca3SPierre Jolivet         swap = PETSC_TRUE;
244313044ca3SPierre Jolivet         PetscCall(PCASMSetType(data->levels[0]->pc, PC_ASM_NONE)); /* "Neumann--Neumann" preconditioning with overlap and a Boolean partition of unity */
244413044ca3SPierre Jolivet         PetscCall(PCASMSetLocalSubdomains(data->levels[0]->pc, 1, &data->is, &loc));
244513044ca3SPierre Jolivet         PetscCall(PCSetFromOptions(data->levels[0]->pc)); /* action of eq. (15) of https://hal.science/hal-02343808v6/document (with a sign flip) */
244613044ca3SPierre Jolivet         PetscCall(MatSchurComplementGetSubMatrices(P, &A00, &P00, std::get<1>(*ctx), &A10, &A11));
244713044ca3SPierre Jolivet         std::get<1>(*ctx)[1] = A10;
244813044ca3SPierre Jolivet         PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATTRANSPOSEVIRTUAL, &flg));
244913044ca3SPierre Jolivet         if (flg) PetscCall(MatTransposeGetMat(A10, &A01));
245013044ca3SPierre Jolivet         else {
245113044ca3SPierre Jolivet           PetscBool flg;
245213044ca3SPierre Jolivet 
245313044ca3SPierre Jolivet           PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
245413044ca3SPierre Jolivet           if (flg) PetscCall(MatHermitianTransposeGetMat(A10, &A01));
245513044ca3SPierre Jolivet         }
245607d8d47fSPierre Jolivet         PetscCall(ISDuplicate(*is_00, &sorted)); /* during setup of the PC associated to the A00 block, this IS has already been sorted, but it's put back to its original state at the end of PCSetUp_HPDDM(), which may be unsorted */
245713044ca3SPierre Jolivet         PetscCall(ISSort(sorted));               /* this is to avoid changing users inputs, but it requires a new call to ISSort() here                                                                                               */
245800b491fbSPierre Jolivet         if (!A01) {
245900b491fbSPierre Jolivet           PetscCall(MatSetOption(A10, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
246000b491fbSPierre Jolivet           PetscCall(MatCreateSubMatrices(A10, 1, &data->is, &sorted, MAT_INITIAL_MATRIX, &sub));
246100b491fbSPierre Jolivet           b[2] = sub[0];
246200b491fbSPierre Jolivet           PetscCall(PetscObjectReference((PetscObject)sub[0]));
246300b491fbSPierre Jolivet           PetscCall(MatDestroySubMatrices(1, &sub));
246400b491fbSPierre Jolivet           PetscCall(PetscObjectTypeCompare((PetscObject)std::get<1>(*ctx)[0], MATTRANSPOSEVIRTUAL, &flg));
246500b491fbSPierre Jolivet           A10 = nullptr;
246600b491fbSPierre Jolivet           if (flg) PetscCall(MatTransposeGetMat(std::get<1>(*ctx)[0], &A10));
246713044ca3SPierre Jolivet           else {
246800b491fbSPierre Jolivet             PetscBool flg;
246900b491fbSPierre Jolivet 
2470c71f06a7SPierre Jolivet             PetscCall(PetscObjectTypeCompare((PetscObject)std::get<1>(*ctx)[0], MATHERMITIANTRANSPOSEVIRTUAL, &flg));
247100b491fbSPierre Jolivet             if (flg) PetscCall(MatHermitianTransposeGetMat(std::get<1>(*ctx)[0], &A10));
247213044ca3SPierre Jolivet           }
2473811e8887SPierre Jolivet           if (!A10) PetscCall(MatCreateSubMatrices(std::get<1>(*ctx)[0], 1, &sorted, &data->is, MAT_INITIAL_MATRIX, &sub));
2474811e8887SPierre Jolivet           else {
2475811e8887SPierre Jolivet             if (flg) PetscCall(MatCreateTranspose(b[2], b + 1));
2476811e8887SPierre Jolivet             else PetscCall(MatCreateHermitianTranspose(b[2], b + 1));
247700b491fbSPierre Jolivet           }
247800b491fbSPierre Jolivet         } else {
247900b491fbSPierre Jolivet           PetscCall(MatSetOption(A01, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
248000b491fbSPierre Jolivet           PetscCall(MatCreateSubMatrices(A01, 1, &sorted, &data->is, MAT_INITIAL_MATRIX, &sub));
2481811e8887SPierre Jolivet           if (flg) PetscCall(MatCreateTranspose(*sub, b + 2));
2482811e8887SPierre Jolivet           else PetscCall(MatCreateHermitianTranspose(*sub, b + 2));
2483811e8887SPierre Jolivet         }
2484811e8887SPierre Jolivet         if (A01 || !A10) {
2485811e8887SPierre Jolivet           b[1] = sub[0];
2486811e8887SPierre Jolivet           PetscCall(PetscObjectReference((PetscObject)sub[0]));
248700b491fbSPierre Jolivet         }
248800b491fbSPierre Jolivet         PetscCall(MatDestroySubMatrices(1, &sub));
248913044ca3SPierre Jolivet         PetscCall(ISDestroy(&sorted));
249000b491fbSPierre Jolivet         PetscCall(MatCreateSchurComplement(subA[0], subA[1], b[1], b[2], data->aux, &S));
249113044ca3SPierre Jolivet         PetscCall(MatSchurComplementSetKSP(S, ksp[0]));
249213044ca3SPierre Jolivet         PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(data->levels[0]->pc, S, PETSC_TRUE)); /* the subdomain Mat is already known and the input IS of PCASMSetLocalSubdomains() is already sorted */
249313044ca3SPierre Jolivet         PetscTryMethod(data->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data->levels[0]->pc, &n, nullptr, &ksp));
249413044ca3SPierre Jolivet         PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
249513044ca3SPierre Jolivet         PetscCall(KSPGetPC(ksp[0], &inner));
249613044ca3SPierre Jolivet         PetscCall(PCSetType(inner, PCSHELL)); /* compute the action of the inverse of the local Schur complement with a PCSHELL */
249713044ca3SPierre Jolivet         b[0] = subA[0];
249813044ca3SPierre Jolivet         b[3] = data->aux;
249913044ca3SPierre Jolivet         PetscCall(MatCreateNest(PETSC_COMM_SELF, 2, nullptr, 2, nullptr, b, &N)); /* instead of computing inv(A11 - A10 inv(A00) A01), compute inv([A00, A01; A10, A11]) followed by a partial solution associated to the A11 block */
250000b491fbSPierre Jolivet         PetscCall(PetscObjectDereference((PetscObject)b[1]));
250100b491fbSPierre Jolivet         PetscCall(PetscObjectDereference((PetscObject)b[2]));
250213044ca3SPierre Jolivet         PetscCall(PCCreate(PETSC_COMM_SELF, &s));
250313044ca3SPierre Jolivet         PetscCall(PCSetOptionsPrefix(s, ((PetscObject)inner)->prefix));
250413044ca3SPierre Jolivet         PetscCall(PCSetOptionsPrefix(inner, nullptr));
250513044ca3SPierre Jolivet         PetscCall(KSPSetSkipPCSetFromOptions(ksp[0], PETSC_TRUE));
250613044ca3SPierre Jolivet         PetscCall(PCSetType(s, PCLU));
250713044ca3SPierre Jolivet         if (PetscDefined(HAVE_MUMPS)) { /* only MATSOLVERMUMPS handles MATNEST, so for the others, e.g., MATSOLVERPETSC or MATSOLVERMKL_PARDISO, convert to plain MATAIJ */
250813044ca3SPierre Jolivet           PetscCall(PCFactorSetMatSolverType(s, MATSOLVERMUMPS));
250913044ca3SPierre Jolivet         }
251013044ca3SPierre Jolivet         PetscCall(PCSetFromOptions(s));
251113044ca3SPierre Jolivet         PetscCall(PCFactorGetMatSolverType(s, &type));
251213044ca3SPierre Jolivet         PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
251313044ca3SPierre Jolivet         if (flg) {
251413044ca3SPierre Jolivet           PetscCall(PCSetOperators(s, N, N));
251500b491fbSPierre Jolivet           PetscCall(PCFactorGetMatrix(s, b));
251600b491fbSPierre Jolivet           PetscCall(MatSetOptionsPrefix(*b, ((PetscObject)s)->prefix));
251724ddd604SPierre Jolivet           n = -1;
251824ddd604SPierre Jolivet           PetscCall(PetscOptionsGetInt(nullptr, ((PetscObject)s)->prefix, "-mat_mumps_icntl_26", &n, nullptr));
2519f45b553cSPierre Jolivet           if (n == 1) {                                /* allocates a square MatDense of size is[1]->map->n, so one */
2520f45b553cSPierre Jolivet             PetscCall(MatNestGetISs(N, is, nullptr));  /*  needs to be able to deactivate this path when dealing    */
2521f45b553cSPierre Jolivet             PetscCall(MatFactorSetSchurIS(*b, is[1])); /*  with a large constraint space in order to avoid OOM      */
2522f45b553cSPierre Jolivet           }
252313044ca3SPierre Jolivet         } else {
252400b491fbSPierre Jolivet           PetscCall(MatConvert(N, MATAIJ, MAT_INITIAL_MATRIX, b));
252500b491fbSPierre Jolivet           PetscCall(PCSetOperators(s, N, *b));
252600b491fbSPierre Jolivet           PetscCall(PetscObjectDereference((PetscObject)*b));
252700b491fbSPierre Jolivet           PetscCall(PCFactorGetMatrix(s, b)); /* MATSOLVERMKL_PARDISO cannot compute in PETSc (yet) a partial solution associated to the A11 block, only partial solution associated to the A00 block or full solution */
252813044ca3SPierre Jolivet         }
252913044ca3SPierre Jolivet         PetscCall(PetscNew(&p));
253013044ca3SPierre Jolivet         p->first = s;
253100b491fbSPierre Jolivet         PetscCall(MatCreateVecs(*b, p->second, p->second + 1));
253213044ca3SPierre Jolivet         PetscCall(PCShellSetContext(inner, p));
253313044ca3SPierre Jolivet         PetscCall(PCShellSetApply(inner, PCApply_Nest));
253413044ca3SPierre Jolivet         PetscCall(PCShellSetView(inner, PCView_Nest));
253513044ca3SPierre Jolivet         PetscCall(PCShellSetDestroy(inner, PCDestroy_Nest));
253613044ca3SPierre Jolivet         PetscCall(PetscObjectDereference((PetscObject)N));
253713044ca3SPierre Jolivet       }
2538f1580f4eSBarry Smith       if (!data->levels[0]->scatter) {
2539db4a47b3SPierre Jolivet         PetscCall(MatCreateVecs(P, &xin, nullptr));
2540f1580f4eSBarry Smith         if (ismatis) PetscCall(MatDestroy(&P));
2541db4a47b3SPierre Jolivet         PetscCall(VecScatterCreate(xin, data->is, data->levels[0]->D, nullptr, &data->levels[0]->scatter));
2542f1580f4eSBarry Smith         PetscCall(VecDestroy(&xin));
2543f1580f4eSBarry Smith       }
2544f1580f4eSBarry Smith       if (data->levels[0]->P) {
2545f1580f4eSBarry Smith         /* if the pattern is the same and PCSetUp() has previously succeeded, reuse HPDDM buffers and connectivity */
2546f1580f4eSBarry Smith         PetscCall(HPDDM::Schwarz<PetscScalar>::destroy(data->levels[0], pc->setupcalled < 1 || pc->flag == DIFFERENT_NONZERO_PATTERN ? PETSC_TRUE : PETSC_FALSE));
2547f1580f4eSBarry Smith       }
2548f1580f4eSBarry Smith       if (!data->levels[0]->P) data->levels[0]->P = new HPDDM::Schwarz<PetscScalar>();
2549db4a47b3SPierre Jolivet       if (data->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_SetUp[0], data->levels[0]->ksp, nullptr, nullptr, nullptr));
2550db4a47b3SPierre Jolivet       else PetscCall(PetscLogEventBegin(PC_HPDDM_Strc, data->levels[0]->ksp, nullptr, nullptr, nullptr));
2551f1580f4eSBarry Smith       /* HPDDM internal data structure */
255213044ca3SPierre Jolivet       PetscCall(data->levels[0]->P->structure(loc, data->is, !ctx ? sub[0] : nullptr, ismatis ? C : data->aux, data->levels));
2553db4a47b3SPierre Jolivet       if (!data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_Strc, data->levels[0]->ksp, nullptr, nullptr, nullptr));
2554f1580f4eSBarry Smith       /* matrix pencil of the generalized eigenvalue problem on the overlap (GenEO) */
255513044ca3SPierre Jolivet       if (!ctx) {
25569bb5c669SPierre Jolivet         if (data->deflation || overlap != -1) weighted = data->aux;
2557f1580f4eSBarry Smith         else if (!data->B) {
2558e2b46ddfSPierre Jolivet           PetscBool cmp;
2559811e8887SPierre Jolivet 
2560f1580f4eSBarry Smith           PetscCall(MatDuplicate(sub[0], MAT_COPY_VALUES, &weighted));
2561e2b46ddfSPierre Jolivet           PetscCall(PetscObjectTypeCompareAny((PetscObject)weighted, &cmp, MATNORMAL, MATNORMALHERMITIAN, ""));
2562e2b46ddfSPierre Jolivet           if (cmp) flg = PETSC_FALSE;
2563e2b46ddfSPierre Jolivet           PetscCall(MatDiagonalScale(weighted, data->levels[0]->D, data->levels[0]->D));
25645b0bb9f2SPierre Jolivet           /* neither MatDuplicate() nor MatDiagonalScale() handles the symmetry options, so propagate the options explicitly */
2565f1580f4eSBarry Smith           /* only useful for -mat_type baij -pc_hpddm_levels_1_st_pc_type cholesky (no problem with MATAIJ or MATSBAIJ)      */
2566f1580f4eSBarry Smith           PetscCall(MatPropagateSymmetryOptions(sub[0], weighted));
2567f1580f4eSBarry Smith         } else weighted = data->B;
256813044ca3SPierre Jolivet       } else weighted = nullptr;
2569f1580f4eSBarry Smith       /* SLEPc is used inside the loaded symbol */
25709bb5c669SPierre Jolivet       PetscCall((*loadedSym)(data->levels[0]->P, data->is, ismatis ? C : (algebraic && !block && overlap == -1 ? sub[0] : (!ctx ? data->aux : S)), weighted, data->B, initial, data->levels));
25719bb5c669SPierre Jolivet       if (!ctx && data->share && overlap == -1) {
2572f1580f4eSBarry Smith         Mat st[2];
2573f1580f4eSBarry Smith         PetscCall(KSPGetOperators(ksp[0], st, st + 1));
25745c7345deSPierre Jolivet         PetscCall(MatCopy(subA[0], st[0], structure));
2575f1580f4eSBarry Smith         if (subA[1] != subA[0] || st[1] != st[0]) PetscCall(MatCopy(subA[1], st[1], SAME_NONZERO_PATTERN));
25760307214fSPierre Jolivet         PetscCall(PetscObjectDereference((PetscObject)subA[0]));
2577f1580f4eSBarry Smith       }
2578db4a47b3SPierre Jolivet       if (data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_SetUp[0], data->levels[0]->ksp, nullptr, nullptr, nullptr));
2579f1580f4eSBarry Smith       if (ismatis) PetscCall(MatISGetLocalMat(C, &N));
2580f1580f4eSBarry Smith       else N = data->aux;
258113044ca3SPierre Jolivet       if (!ctx) P = sub[0];
258213044ca3SPierre Jolivet       else P = S;
2583f1580f4eSBarry Smith       /* going through the grid hierarchy */
2584f1580f4eSBarry Smith       for (n = 1; n < data->N; ++n) {
2585db4a47b3SPierre Jolivet         if (data->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_SetUp[n], data->levels[n]->ksp, nullptr, nullptr, nullptr));
2586f1580f4eSBarry Smith         /* method composed in the loaded symbol since there, SLEPc is used as well */
2587f1580f4eSBarry Smith         PetscTryMethod(data->levels[0]->ksp, "PCHPDDMSetUp_Private_C", (Mat *, Mat *, PetscInt, PetscInt *const, PC_HPDDM_Level **const), (&P, &N, n, &data->N, data->levels));
2588db4a47b3SPierre Jolivet         if (data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_SetUp[n], data->levels[n]->ksp, nullptr, nullptr, nullptr));
2589f1580f4eSBarry Smith       }
2590f1580f4eSBarry Smith       /* reset to NULL to avoid any faulty use */
2591db4a47b3SPierre Jolivet       PetscCall(PetscObjectComposeFunction((PetscObject)data->levels[0]->ksp, "PCHPDDMSetUp_Private_C", nullptr));
2592db4a47b3SPierre Jolivet       if (!ismatis) PetscCall(PetscObjectComposeFunction((PetscObject)pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_C", nullptr));
2593f1580f4eSBarry Smith       else PetscCall(PetscObjectDereference((PetscObject)C)); /* matching PetscObjectReference() above */
2594f1580f4eSBarry Smith       for (n = 0; n < data->N - 1; ++n)
2595f1580f4eSBarry Smith         if (data->levels[n]->P) {
2596f1580f4eSBarry Smith           /* HPDDM internal work buffers */
2597f1580f4eSBarry Smith           data->levels[n]->P->setBuffer();
2598f1580f4eSBarry Smith           data->levels[n]->P->super::start();
2599f1580f4eSBarry Smith         }
26009bb5c669SPierre Jolivet       if (ismatis || !subdomains) PetscCall(PCHPDDMDestroySubMatrices_Private(PetscBool3ToBool(data->Neumann), PetscBool(algebraic && !block && overlap == -1), sub));
2601db4a47b3SPierre Jolivet       if (ismatis) data->is = nullptr;
2602f1580f4eSBarry Smith       for (n = 0; n < data->N - 1 + (reused > 0); ++n) {
2603f1580f4eSBarry Smith         if (data->levels[n]->P) {
2604f1580f4eSBarry Smith           PC spc;
2605f1580f4eSBarry Smith 
2606f1580f4eSBarry Smith           /* force the PC to be PCSHELL to do the coarse grid corrections */
2607f1580f4eSBarry Smith           PetscCall(KSPSetSkipPCSetFromOptions(data->levels[n]->ksp, PETSC_TRUE));
2608f1580f4eSBarry Smith           PetscCall(KSPGetPC(data->levels[n]->ksp, &spc));
2609f1580f4eSBarry Smith           PetscCall(PCSetType(spc, PCSHELL));
2610f1580f4eSBarry Smith           PetscCall(PCShellSetContext(spc, data->levels[n]));
2611f1580f4eSBarry Smith           PetscCall(PCShellSetSetUp(spc, PCSetUp_HPDDMShell));
2612f1580f4eSBarry Smith           PetscCall(PCShellSetApply(spc, PCApply_HPDDMShell));
2613f1580f4eSBarry Smith           PetscCall(PCShellSetMatApply(spc, PCMatApply_HPDDMShell));
261413044ca3SPierre Jolivet           if (ctx && n == 0) {
261513044ca3SPierre Jolivet             Mat                               Amat, Pmat;
261613044ca3SPierre Jolivet             PetscInt                          m, M;
261701e3c840SPierre Jolivet             std::tuple<Mat, PetscSF, Vec[2]> *ctx;
261813044ca3SPierre Jolivet 
261913044ca3SPierre Jolivet             PetscCall(KSPGetOperators(data->levels[n]->ksp, nullptr, &Pmat));
262013044ca3SPierre Jolivet             PetscCall(MatGetLocalSize(Pmat, &m, nullptr));
262113044ca3SPierre Jolivet             PetscCall(MatGetSize(Pmat, &M, nullptr));
262213044ca3SPierre Jolivet             PetscCall(PetscNew(&ctx));
262313044ca3SPierre Jolivet             std::get<0>(*ctx) = S;
262413044ca3SPierre Jolivet             std::get<1>(*ctx) = data->levels[n]->scatter;
262513044ca3SPierre Jolivet             PetscCall(MatCreateShell(PetscObjectComm((PetscObject)data->levels[n]->ksp), m, m, M, M, ctx, &Amat));
262613044ca3SPierre Jolivet             PetscCall(MatShellSetOperation(Amat, MATOP_MULT, (void (*)(void))MatMult_Schur<false>));
262713044ca3SPierre Jolivet             PetscCall(MatShellSetOperation(Amat, MATOP_MULT_TRANSPOSE, (void (*)(void))MatMult_Schur<true>));
262813044ca3SPierre Jolivet             PetscCall(MatShellSetOperation(Amat, MATOP_DESTROY, (void (*)(void))MatDestroy_Schur));
262913044ca3SPierre Jolivet             PetscCall(MatCreateVecs(S, std::get<2>(*ctx), std::get<2>(*ctx) + 1));
263013044ca3SPierre Jolivet             PetscCall(KSPSetOperators(data->levels[n]->ksp, Amat, Pmat));
263113044ca3SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)Amat));
263213044ca3SPierre Jolivet           }
2633f1580f4eSBarry Smith           PetscCall(PCShellSetDestroy(spc, PCDestroy_HPDDMShell));
2634f1580f4eSBarry Smith           if (!data->levels[n]->pc) PetscCall(PCCreate(PetscObjectComm((PetscObject)data->levels[n]->ksp), &data->levels[n]->pc));
2635f1580f4eSBarry Smith           if (n < reused) {
2636f1580f4eSBarry Smith             PetscCall(PCSetReusePreconditioner(spc, PETSC_TRUE));
2637f1580f4eSBarry Smith             PetscCall(PCSetReusePreconditioner(data->levels[n]->pc, PETSC_TRUE));
2638f1580f4eSBarry Smith           }
2639f1580f4eSBarry Smith           PetscCall(PCSetUp(spc));
2640f1580f4eSBarry Smith         }
2641f1580f4eSBarry Smith       }
264213044ca3SPierre Jolivet       if (ctx) PetscCall(MatDestroy(&S));
26439bb5c669SPierre Jolivet       if (overlap == -1) PetscCall(PetscObjectComposeFunction((PetscObject)pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_Private_C", nullptr));
2644f1580f4eSBarry Smith     } else flg = reused ? PETSC_FALSE : PETSC_TRUE;
2645f1580f4eSBarry Smith     if (!ismatis && subdomains) {
2646f1580f4eSBarry Smith       if (flg) PetscCall(KSPGetPC(data->levels[0]->ksp, &inner));
2647f1580f4eSBarry Smith       else inner = data->levels[0]->pc;
2648f1580f4eSBarry Smith       if (inner) {
2649398c7888SPierre Jolivet         if (!inner->setupcalled) PetscCall(PCSetType(inner, PCASM));
2650398c7888SPierre Jolivet         PetscCall(PCSetFromOptions(inner));
2651398c7888SPierre Jolivet         PetscCall(PetscStrcmp(((PetscObject)inner)->type_name, PCASM, &flg));
2652398c7888SPierre Jolivet         if (flg) {
2653f1580f4eSBarry Smith           if (!inner->setupcalled) { /* evaluates to PETSC_FALSE when -pc_hpddm_block_splitting */
2654398c7888SPierre Jolivet             IS sorted;               /* PCASM will sort the input IS, duplicate it to return an unmodified (PCHPDDM) input IS */
2655811e8887SPierre Jolivet 
2656398c7888SPierre Jolivet             PetscCall(ISDuplicate(is[0], &sorted));
2657398c7888SPierre Jolivet             PetscCall(PCASMSetLocalSubdomains(inner, 1, &sorted, &loc));
2658398c7888SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)sorted));
2659398c7888SPierre Jolivet           }
2660c8ea6600SPierre Jolivet           if (!PetscBool3ToBool(data->Neumann) && data->N > 1) { /* subdomain matrices are already created for the eigenproblem, reuse them for the fine-level PC */
2661db4a47b3SPierre Jolivet             PetscCall(PCHPDDMPermute_Private(*is, nullptr, nullptr, sub[0], &P, nullptr));
2662398c7888SPierre Jolivet             PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(inner, P, algebraic));
2663398c7888SPierre Jolivet             PetscCall(PetscObjectDereference((PetscObject)P));
2664f1580f4eSBarry Smith           }
2665f1580f4eSBarry Smith         }
2666f1580f4eSBarry Smith       }
26679bb5c669SPierre Jolivet       if (data->N > 1) {
26689bb5c669SPierre Jolivet         if (overlap != 1) PetscCall(PCHPDDMDestroySubMatrices_Private(PetscBool3ToBool(data->Neumann), PetscBool(algebraic && !block && overlap == -1), sub));
26699bb5c669SPierre Jolivet         if (overlap == 1) PetscCall(MatDestroy(subA));
26709bb5c669SPierre Jolivet       }
2671f1580f4eSBarry Smith     }
2672f1580f4eSBarry Smith     PetscCall(ISDestroy(&loc));
2673f1580f4eSBarry Smith   } else data->N = 1 + reused; /* enforce this value to 1 + reused if there is no way to build another level */
2674f1580f4eSBarry Smith   if (requested != data->N + reused) {
2675f1580f4eSBarry Smith     PetscCall(PetscInfo(pc, "%" PetscInt_FMT " levels requested, only %" PetscInt_FMT " built + %" PetscInt_FMT " reused. Options for level(s) > %" PetscInt_FMT ", including -%spc_hpddm_coarse_ will not be taken into account\n", requested, data->N, reused,
2676f1580f4eSBarry Smith                         data->N, pcpre ? pcpre : ""));
2677f1580f4eSBarry Smith     PetscCall(PetscInfo(pc, "It is best to tune parameters, e.g., a higher value for -%spc_hpddm_levels_%" PetscInt_FMT "_eps_threshold so that at least one local deflation vector will be selected\n", pcpre ? pcpre : "", data->N));
2678f1580f4eSBarry Smith     /* cannot use PCDestroy_HPDDMShell() because PCSHELL not set for unassembled levels */
2679f1580f4eSBarry Smith     for (n = data->N - 1; n < requested - 1; ++n) {
2680f1580f4eSBarry Smith       if (data->levels[n]->P) {
2681f1580f4eSBarry Smith         PetscCall(HPDDM::Schwarz<PetscScalar>::destroy(data->levels[n], PETSC_TRUE));
2682f1580f4eSBarry Smith         PetscCall(VecDestroyVecs(1, &data->levels[n]->v[0]));
2683f1580f4eSBarry Smith         PetscCall(VecDestroyVecs(2, &data->levels[n]->v[1]));
2684f1580f4eSBarry Smith         PetscCall(MatDestroy(data->levels[n]->V));
2685f1580f4eSBarry Smith         PetscCall(MatDestroy(data->levels[n]->V + 1));
2686f1580f4eSBarry Smith         PetscCall(MatDestroy(data->levels[n]->V + 2));
2687f1580f4eSBarry Smith         PetscCall(VecDestroy(&data->levels[n]->D));
268801e3c840SPierre Jolivet         PetscCall(PetscSFDestroy(&data->levels[n]->scatter));
2689f1580f4eSBarry Smith       }
2690f1580f4eSBarry Smith     }
2691f1580f4eSBarry Smith     if (reused) {
2692f1580f4eSBarry Smith       for (n = reused; n < PETSC_PCHPDDM_MAXLEVELS && data->levels[n]; ++n) {
2693f1580f4eSBarry Smith         PetscCall(KSPDestroy(&data->levels[n]->ksp));
2694f1580f4eSBarry Smith         PetscCall(PCDestroy(&data->levels[n]->pc));
2695f1580f4eSBarry Smith       }
2696f1580f4eSBarry Smith     }
2697f1580f4eSBarry Smith     PetscCheck(!PetscDefined(USE_DEBUG), PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "%" PetscInt_FMT " levels requested, only %" PetscInt_FMT " built + %" PetscInt_FMT " reused. Options for level(s) > %" PetscInt_FMT ", 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_%" PetscInt_FMT "_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,
2698f1580f4eSBarry Smith                data->N, reused, data->N, pcpre ? pcpre : "", pcpre ? pcpre : "", data->N);
2699f1580f4eSBarry Smith   }
2700f1580f4eSBarry Smith   /* these solvers are created after PCSetFromOptions() is called */
2701f1580f4eSBarry Smith   if (pc->setfromoptionscalled) {
2702f1580f4eSBarry Smith     for (n = 0; n < data->N; ++n) {
2703f1580f4eSBarry Smith       if (data->levels[n]->ksp) PetscCall(KSPSetFromOptions(data->levels[n]->ksp));
2704f1580f4eSBarry Smith       if (data->levels[n]->pc) PetscCall(PCSetFromOptions(data->levels[n]->pc));
2705f1580f4eSBarry Smith     }
2706f1580f4eSBarry Smith     pc->setfromoptionscalled = 0;
2707f1580f4eSBarry Smith   }
2708f1580f4eSBarry Smith   data->N += reused;
2709f1580f4eSBarry Smith   if (data->share && swap) {
2710f1580f4eSBarry Smith     /* swap back pointers so that variables follow the user-provided numbering */
2711f1580f4eSBarry Smith     std::swap(C, data->aux);
2712f1580f4eSBarry Smith     std::swap(uis, data->is);
2713f1580f4eSBarry Smith     PetscCall(MatDestroy(&C));
2714f1580f4eSBarry Smith     PetscCall(ISDestroy(&uis));
2715f1580f4eSBarry Smith   }
2716398c7888SPierre Jolivet   if (algebraic) PetscCall(MatDestroy(&data->aux));
271738fb34a1SPierre Jolivet   if (unsorted && unsorted != is[0]) {
2718398c7888SPierre Jolivet     PetscCall(ISCopy(unsorted, data->is));
2719398c7888SPierre Jolivet     PetscCall(ISDestroy(&unsorted));
2720398c7888SPierre Jolivet   }
2721398c7888SPierre Jolivet #if PetscDefined(USE_DEBUG)
2722398c7888SPierre Jolivet   PetscCheck((data->is && dis) || (!data->is && !dis), PETSC_COMM_SELF, PETSC_ERR_PLIB, "An IS pointer is NULL but not the other: input IS pointer (%p) v. output IS pointer (%p)", (void *)dis, (void *)data->is);
2723398c7888SPierre Jolivet   if (data->is) {
2724398c7888SPierre Jolivet     PetscCall(ISEqualUnsorted(data->is, dis, &flg));
2725398c7888SPierre Jolivet     PetscCall(ISDestroy(&dis));
2726398c7888SPierre Jolivet     PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input IS and output IS are not equal");
2727398c7888SPierre Jolivet   }
2728398c7888SPierre Jolivet   PetscCheck((data->aux && daux) || (!data->aux && !daux), PETSC_COMM_SELF, PETSC_ERR_PLIB, "A Mat pointer is NULL but not the other: input Mat pointer (%p) v. output Mat pointer (%p)", (void *)daux, (void *)data->aux);
2729398c7888SPierre Jolivet   if (data->aux) {
2730398c7888SPierre Jolivet     PetscCall(MatMultEqual(data->aux, daux, 20, &flg));
2731398c7888SPierre Jolivet     PetscCall(MatDestroy(&daux));
2732398c7888SPierre Jolivet     PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input Mat and output Mat are not equal");
2733398c7888SPierre Jolivet   }
2734398c7888SPierre Jolivet #endif
27353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2736f1580f4eSBarry Smith }
2737f1580f4eSBarry Smith 
2738f1580f4eSBarry Smith /*@
2739f1580f4eSBarry Smith   PCHPDDMSetCoarseCorrectionType - Sets the coarse correction type.
2740f1580f4eSBarry Smith 
2741c3339decSBarry Smith   Collective
2742f1580f4eSBarry Smith 
2743f1580f4eSBarry Smith   Input Parameters:
2744f1580f4eSBarry Smith + pc   - preconditioner context
2745aa1539e9SPierre Jolivet - type - `PC_HPDDM_COARSE_CORRECTION_DEFLATED`, `PC_HPDDM_COARSE_CORRECTION_ADDITIVE`, `PC_HPDDM_COARSE_CORRECTION_BALANCED`, or `PC_HPDDM_COARSE_CORRECTION_NONE`
2746f1580f4eSBarry Smith 
2747f1580f4eSBarry Smith   Options Database Key:
2748aa1539e9SPierre Jolivet . -pc_hpddm_coarse_correction <deflated, additive, balanced, none> - type of coarse correction to apply
2749f1580f4eSBarry Smith 
2750f1580f4eSBarry Smith   Level: intermediate
2751f1580f4eSBarry Smith 
2752562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDMGetCoarseCorrectionType()`, `PCHPDDM`, `PCHPDDMCoarseCorrectionType`
2753f1580f4eSBarry Smith @*/
2754d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMSetCoarseCorrectionType(PC pc, PCHPDDMCoarseCorrectionType type)
2755d71ae5a4SJacob Faibussowitsch {
2756f1580f4eSBarry Smith   PetscFunctionBegin;
2757f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2758f1580f4eSBarry Smith   PetscValidLogicalCollectiveEnum(pc, type, 2);
2759f1580f4eSBarry Smith   PetscTryMethod(pc, "PCHPDDMSetCoarseCorrectionType_C", (PC, PCHPDDMCoarseCorrectionType), (pc, type));
27603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2761f1580f4eSBarry Smith }
2762f1580f4eSBarry Smith 
2763f1580f4eSBarry Smith /*@
2764f1580f4eSBarry Smith   PCHPDDMGetCoarseCorrectionType - Gets the coarse correction type.
2765f1580f4eSBarry Smith 
2766f1580f4eSBarry Smith   Input Parameter:
2767f1580f4eSBarry Smith . pc - preconditioner context
2768f1580f4eSBarry Smith 
2769f1580f4eSBarry Smith   Output Parameter:
2770aa1539e9SPierre Jolivet . type - `PC_HPDDM_COARSE_CORRECTION_DEFLATED`, `PC_HPDDM_COARSE_CORRECTION_ADDITIVE`, `PC_HPDDM_COARSE_CORRECTION_BALANCED`, or `PC_HPDDM_COARSE_CORRECTION_NONE`
2771f1580f4eSBarry Smith 
2772f1580f4eSBarry Smith   Level: intermediate
2773f1580f4eSBarry Smith 
2774562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDMSetCoarseCorrectionType()`, `PCHPDDM`, `PCHPDDMCoarseCorrectionType`
2775f1580f4eSBarry Smith @*/
2776d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMGetCoarseCorrectionType(PC pc, PCHPDDMCoarseCorrectionType *type)
2777d71ae5a4SJacob Faibussowitsch {
2778f1580f4eSBarry Smith   PetscFunctionBegin;
2779f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2780f1580f4eSBarry Smith   if (type) {
27814f572ea9SToby Isaac     PetscAssertPointer(type, 2);
2782f1580f4eSBarry Smith     PetscUseMethod(pc, "PCHPDDMGetCoarseCorrectionType_C", (PC, PCHPDDMCoarseCorrectionType *), (pc, type));
2783f1580f4eSBarry Smith   }
27843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2785f1580f4eSBarry Smith }
2786f1580f4eSBarry Smith 
2787d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMSetCoarseCorrectionType_HPDDM(PC pc, PCHPDDMCoarseCorrectionType type)
2788d71ae5a4SJacob Faibussowitsch {
2789f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
2790f1580f4eSBarry Smith 
2791f1580f4eSBarry Smith   PetscFunctionBegin;
2792f1580f4eSBarry Smith   data->correction = type;
27933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2794f1580f4eSBarry Smith }
2795f1580f4eSBarry Smith 
2796d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMGetCoarseCorrectionType_HPDDM(PC pc, PCHPDDMCoarseCorrectionType *type)
2797d71ae5a4SJacob Faibussowitsch {
2798f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
2799f1580f4eSBarry Smith 
2800f1580f4eSBarry Smith   PetscFunctionBegin;
2801f1580f4eSBarry Smith   *type = data->correction;
28023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2803f1580f4eSBarry Smith }
2804f1580f4eSBarry Smith 
2805f1580f4eSBarry Smith /*@
2806e31fc274SPierre Jolivet   PCHPDDMSetSTShareSubKSP - Sets whether the `KSP` in SLEPc `ST` and the fine-level subdomain solver should be shared.
2807e31fc274SPierre Jolivet 
2808e31fc274SPierre Jolivet   Input Parameters:
2809e31fc274SPierre Jolivet + pc    - preconditioner context
2810e31fc274SPierre Jolivet - share - whether the `KSP` should be shared or not
2811e31fc274SPierre Jolivet 
2812e31fc274SPierre Jolivet   Note:
2813e31fc274SPierre Jolivet   This is not the same as `PCSetReusePreconditioner()`. Given certain conditions (visible using -info), a symbolic factorization can be skipped
2814e31fc274SPierre Jolivet   when using a subdomain `PCType` such as `PCLU` or `PCCHOLESKY`.
2815e31fc274SPierre Jolivet 
2816e31fc274SPierre Jolivet   Level: advanced
2817e31fc274SPierre Jolivet 
2818562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMGetSTShareSubKSP()`
2819e31fc274SPierre Jolivet @*/
2820e31fc274SPierre Jolivet PetscErrorCode PCHPDDMSetSTShareSubKSP(PC pc, PetscBool share)
2821e31fc274SPierre Jolivet {
2822e31fc274SPierre Jolivet   PetscFunctionBegin;
2823e31fc274SPierre Jolivet   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2824e31fc274SPierre Jolivet   PetscTryMethod(pc, "PCHPDDMSetSTShareSubKSP_C", (PC, PetscBool), (pc, share));
28253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2826e31fc274SPierre Jolivet }
2827e31fc274SPierre Jolivet 
2828e31fc274SPierre Jolivet /*@
2829f1580f4eSBarry Smith   PCHPDDMGetSTShareSubKSP - Gets whether the `KSP` in SLEPc `ST` and the fine-level subdomain solver is shared.
2830f1580f4eSBarry Smith 
2831f1580f4eSBarry Smith   Input Parameter:
2832f1580f4eSBarry Smith . pc - preconditioner context
2833f1580f4eSBarry Smith 
2834f1580f4eSBarry Smith   Output Parameter:
2835f1580f4eSBarry Smith . share - whether the `KSP` is shared or not
2836f1580f4eSBarry Smith 
2837f1580f4eSBarry Smith   Note:
2838f1580f4eSBarry Smith   This is not the same as `PCGetReusePreconditioner()`. The return value is unlikely to be true, but when it is, a symbolic factorization can be skipped
2839f1580f4eSBarry Smith   when using a subdomain `PCType` such as `PCLU` or `PCCHOLESKY`.
2840f1580f4eSBarry Smith 
2841f1580f4eSBarry Smith   Level: advanced
2842f1580f4eSBarry Smith 
2843562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMSetSTShareSubKSP()`
2844f1580f4eSBarry Smith @*/
2845d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMGetSTShareSubKSP(PC pc, PetscBool *share)
2846d71ae5a4SJacob Faibussowitsch {
2847f1580f4eSBarry Smith   PetscFunctionBegin;
2848f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2849f1580f4eSBarry Smith   if (share) {
28504f572ea9SToby Isaac     PetscAssertPointer(share, 2);
2851f1580f4eSBarry Smith     PetscUseMethod(pc, "PCHPDDMGetSTShareSubKSP_C", (PC, PetscBool *), (pc, share));
2852f1580f4eSBarry Smith   }
28533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2854f1580f4eSBarry Smith }
2855f1580f4eSBarry Smith 
2856e31fc274SPierre Jolivet static PetscErrorCode PCHPDDMSetSTShareSubKSP_HPDDM(PC pc, PetscBool share)
2857e31fc274SPierre Jolivet {
2858e31fc274SPierre Jolivet   PC_HPDDM *data = (PC_HPDDM *)pc->data;
2859e31fc274SPierre Jolivet 
2860e31fc274SPierre Jolivet   PetscFunctionBegin;
2861e31fc274SPierre Jolivet   data->share = share;
28623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2863e31fc274SPierre Jolivet }
2864e31fc274SPierre Jolivet 
2865d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMGetSTShareSubKSP_HPDDM(PC pc, PetscBool *share)
2866d71ae5a4SJacob Faibussowitsch {
2867f1580f4eSBarry Smith   PC_HPDDM *data = (PC_HPDDM *)pc->data;
2868f1580f4eSBarry Smith 
2869f1580f4eSBarry Smith   PetscFunctionBegin;
2870f1580f4eSBarry Smith   *share = data->share;
28713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2872f1580f4eSBarry Smith }
2873f1580f4eSBarry Smith 
2874f1580f4eSBarry Smith /*@
2875f1580f4eSBarry Smith   PCHPDDMSetDeflationMat - Sets the deflation space used to assemble a coarser operator.
2876f1580f4eSBarry Smith 
2877f1580f4eSBarry Smith   Input Parameters:
2878f1580f4eSBarry Smith + pc - preconditioner context
2879f1580f4eSBarry Smith . is - index set of the local deflation matrix
2880f1580f4eSBarry Smith - U  - deflation sequential matrix stored as a `MATSEQDENSE`
2881f1580f4eSBarry Smith 
2882f1580f4eSBarry Smith   Level: advanced
2883f1580f4eSBarry Smith 
2884562efe2eSBarry Smith .seealso: [](ch_ksp), `PCHPDDM`, `PCDeflationSetSpace()`, `PCMGSetRestriction()`
2885f1580f4eSBarry Smith @*/
2886d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMSetDeflationMat(PC pc, IS is, Mat U)
2887d71ae5a4SJacob Faibussowitsch {
2888f1580f4eSBarry Smith   PetscFunctionBegin;
2889f1580f4eSBarry Smith   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2890f1580f4eSBarry Smith   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
2891f1580f4eSBarry Smith   PetscValidHeaderSpecific(U, MAT_CLASSID, 3);
2892e31fc274SPierre Jolivet   PetscTryMethod(pc, "PCHPDDMSetDeflationMat_C", (PC, IS, Mat), (pc, is, U));
28933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2894f1580f4eSBarry Smith }
2895f1580f4eSBarry Smith 
2896d71ae5a4SJacob Faibussowitsch static PetscErrorCode PCHPDDMSetDeflationMat_HPDDM(PC pc, IS is, Mat U)
2897d71ae5a4SJacob Faibussowitsch {
2898f1580f4eSBarry Smith   PetscFunctionBegin;
2899f1580f4eSBarry Smith   PetscCall(PCHPDDMSetAuxiliaryMat_Private(pc, is, U, PETSC_TRUE));
29003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2901f1580f4eSBarry Smith }
2902f1580f4eSBarry Smith 
2903d71ae5a4SJacob Faibussowitsch PetscErrorCode HPDDMLoadDL_Private(PetscBool *found)
2904d71ae5a4SJacob Faibussowitsch {
2905605ad303SPierre Jolivet   PetscBool flg;
2906f1580f4eSBarry Smith   char      lib[PETSC_MAX_PATH_LEN], dlib[PETSC_MAX_PATH_LEN], dir[PETSC_MAX_PATH_LEN];
2907f1580f4eSBarry Smith 
2908f1580f4eSBarry Smith   PetscFunctionBegin;
29094f572ea9SToby Isaac   PetscAssertPointer(found, 1);
2910c6a7a370SJeremy L Thompson   PetscCall(PetscStrncpy(dir, "${PETSC_LIB_DIR}", sizeof(dir)));
2911db4a47b3SPierre Jolivet   PetscCall(PetscOptionsGetString(nullptr, nullptr, "-hpddm_dir", dir, sizeof(dir), nullptr));
2912f1580f4eSBarry Smith   PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/libhpddm_petsc", dir));
2913f1580f4eSBarry Smith   PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
2914605ad303SPierre Jolivet #if defined(SLEPC_LIB_DIR) /* this variable is passed during SLEPc ./configure when PETSc has not been configured   */
2915605ad303SPierre Jolivet   if (!*found) {           /* with --download-hpddm since slepcconf.h is not yet built (and thus can't be included) */
2916c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(dir, HPDDM_STR(SLEPC_LIB_DIR), sizeof(dir)));
2917f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/libhpddm_petsc", dir));
2918f1580f4eSBarry Smith     PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
2919f1580f4eSBarry Smith   }
2920f1580f4eSBarry Smith #endif
2921605ad303SPierre Jolivet   if (!*found) { /* probable options for this to evaluate to PETSC_TRUE: system inconsistency (libhpddm_petsc moved by user?) or PETSc configured without --download-slepc */
2922605ad303SPierre Jolivet     PetscCall(PetscOptionsGetenv(PETSC_COMM_SELF, "SLEPC_DIR", dir, sizeof(dir), &flg));
2923605ad303SPierre Jolivet     if (flg) { /* if both PETSc and SLEPc are configured with --download-hpddm but PETSc has been configured without --download-slepc, one must ensure that libslepc is loaded before libhpddm_petsc */
2924605ad303SPierre Jolivet       PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/lib/libslepc", dir));
2925605ad303SPierre Jolivet       PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
2926605ad303SPierre Jolivet       PetscCheck(*found, PETSC_COMM_SELF, PETSC_ERR_PLIB, "%s not found but SLEPC_DIR=%s", lib, dir);
2927605ad303SPierre Jolivet       PetscCall(PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, dlib));
2928605ad303SPierre Jolivet       PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/lib/libhpddm_petsc", dir)); /* libhpddm_petsc is always in the same directory as libslepc */
2929605ad303SPierre Jolivet       PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
2930605ad303SPierre Jolivet     }
2931605ad303SPierre Jolivet   }
2932f1580f4eSBarry Smith   PetscCheck(*found, PETSC_COMM_SELF, PETSC_ERR_PLIB, "%s not found", lib);
2933f1580f4eSBarry Smith   PetscCall(PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, dlib));
29343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2935f1580f4eSBarry Smith }
2936f1580f4eSBarry Smith 
2937f1580f4eSBarry Smith /*MC
2938f1580f4eSBarry Smith    PCHPDDM - Interface with the HPDDM library.
2939f1580f4eSBarry Smith 
29401d27aa22SBarry Smith    This `PC` may be used to build multilevel spectral domain decomposition methods based on the GenEO framework {cite}`spillane2011robust` {cite}`al2021multilevel`.
29411d27aa22SBarry Smith    It may be viewed as an alternative to spectral
29421d27aa22SBarry Smith    AMGe or `PCBDDC` with adaptive selection of constraints. The interface is explained in details in {cite}`jolivetromanzampini2020`
2943f1580f4eSBarry Smith 
2944e7593814SPierre Jolivet    The matrix used for building the preconditioner (Pmat) may be unassembled (`MATIS`), assembled (`MATAIJ`, `MATBAIJ`, or `MATSBAIJ`), hierarchical (`MATHTOOL`), `MATNORMAL`, `MATNORMALHERMITIAN`, or `MATSCHURCOMPLEMENT` (when `PCHPDDM` is used as part of an outer `PCFIELDSPLIT`).
2945f1580f4eSBarry Smith 
2946f1580f4eSBarry Smith    For multilevel preconditioning, when using an assembled or hierarchical Pmat, one must provide an auxiliary local `Mat` (unassembled local operator for GenEO) using
2947f1580f4eSBarry Smith    `PCHPDDMSetAuxiliaryMat()`. Calling this routine is not needed when using a `MATIS` Pmat, assembly is done internally using `MatConvert()`.
2948f1580f4eSBarry Smith 
2949f1580f4eSBarry Smith    Options Database Keys:
2950f1580f4eSBarry Smith +   -pc_hpddm_define_subdomains <true, default=false>    - on the finest level, calls `PCASMSetLocalSubdomains()` with the `IS` supplied in `PCHPDDMSetAuxiliaryMat()`
2951f1580f4eSBarry Smith                                                          (not relevant with an unassembled Pmat)
2952f1580f4eSBarry Smith .   -pc_hpddm_has_neumann <true, default=false>          - on the finest level, informs the `PC` that the local Neumann matrix is supplied in `PCHPDDMSetAuxiliaryMat()`
2953f1580f4eSBarry Smith -   -pc_hpddm_coarse_correction <type, default=deflated> - determines the `PCHPDDMCoarseCorrectionType` when calling `PCApply()`
2954f1580f4eSBarry Smith 
295538bf2a8cSPierre Jolivet    Options for subdomain solvers, subdomain eigensolvers (for computing deflation vectors), and the coarse solver can be set using the following options database prefixes.
2956f1580f4eSBarry Smith .vb
2957f1580f4eSBarry Smith       -pc_hpddm_levels_%d_pc_
2958f1580f4eSBarry Smith       -pc_hpddm_levels_%d_ksp_
2959f1580f4eSBarry Smith       -pc_hpddm_levels_%d_eps_
2960f1580f4eSBarry Smith       -pc_hpddm_levels_%d_p
29614ec2a359SPierre Jolivet       -pc_hpddm_levels_%d_mat_type
2962f1580f4eSBarry Smith       -pc_hpddm_coarse_
2963f1580f4eSBarry Smith       -pc_hpddm_coarse_p
29644ec2a359SPierre Jolivet       -pc_hpddm_coarse_mat_type
29652ce66baaSPierre Jolivet       -pc_hpddm_coarse_mat_filter
2966f1580f4eSBarry Smith .ve
2967f1580f4eSBarry Smith 
296838bf2a8cSPierre Jolivet    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
2969f1580f4eSBarry Smith     -pc_hpddm_coarse_p 2 -pc_hpddm_coarse_mat_type baij will use 10 deflation vectors per subdomain on the fine "level 1",
2970f1580f4eSBarry Smith     aggregate the fine subdomains into 4 "level 2" subdomains, then use 10 deflation vectors per subdomain on "level 2",
29717eb095acSPierre Jolivet     and assemble the coarse matrix (of dimension 4 x 10 = 40) on two processes as a `MATBAIJ` (default is `MATSBAIJ`).
2972f1580f4eSBarry Smith 
2973f1580f4eSBarry Smith    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.
2974f1580f4eSBarry Smith 
29751d27aa22SBarry Smith    Level: intermediate
29761d27aa22SBarry Smith 
29771d27aa22SBarry Smith    Notes:
29781d27aa22SBarry Smith    This preconditioner requires that PETSc is built with SLEPc (``--download-slepc``).
29791d27aa22SBarry Smith 
29801d27aa22SBarry Smith    By default, the underlying concurrent eigenproblems
29811d27aa22SBarry Smith    are solved using SLEPc shift-and-invert spectral transformation. This is usually what gives the best performance for GenEO, cf.
29821d27aa22SBarry Smith    {cite}`spillane2011robust` {cite}`jolivet2013scalabledd`. As
298338bf2a8cSPierre Jolivet    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_nev 10
298438bf2a8cSPierre Jolivet    -pc_hpddm_levels_1_st_type sinvert. There are furthermore three options related to the (subdomain-wise local) eigensolver that are not described in
298538bf2a8cSPierre Jolivet    SLEPc documentation since they are specific to `PCHPDDM`.
298638bf2a8cSPierre Jolivet .vb
298738bf2a8cSPierre Jolivet       -pc_hpddm_levels_1_st_share_sub_ksp
298838bf2a8cSPierre Jolivet       -pc_hpddm_levels_%d_eps_threshold
298938bf2a8cSPierre Jolivet       -pc_hpddm_levels_1_eps_use_inertia
299038bf2a8cSPierre Jolivet .ve
299138bf2a8cSPierre Jolivet 
299238bf2a8cSPierre Jolivet    The first option from the list only applies to the fine-level eigensolver, see `PCHPDDMSetSTShareSubKSP()`. The second option from the list is
299338bf2a8cSPierre Jolivet    used to filter eigenmodes retrieved after convergence of `EPSSolve()` at "level N" such that eigenvectors used to define a "level N+1" coarse
299438bf2a8cSPierre Jolivet    correction are associated to eigenvalues whose magnitude are lower or equal than -pc_hpddm_levels_N_eps_threshold. When using an `EPS` which cannot
299538bf2a8cSPierre Jolivet    determine a priori the proper -pc_hpddm_levels_N_eps_nev such that all wanted eigenmodes are retrieved, it is possible to get an estimation of the
299638bf2a8cSPierre Jolivet    correct value using the third option from the list, -pc_hpddm_levels_1_eps_use_inertia, see `MatGetInertia()`. In that case, there is no need
299738bf2a8cSPierre Jolivet    to supply -pc_hpddm_levels_1_eps_nev. This last option also only applies to the fine-level (N = 1) eigensolver.
2998f1580f4eSBarry Smith 
29991d27aa22SBarry Smith    See also {cite}`dolean2015introduction`, {cite}`al2022robust`, {cite}`al2022robustpd`, and {cite}`nataf2022recent`
3000f1580f4eSBarry Smith 
3001562efe2eSBarry Smith .seealso: [](ch_ksp), `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHPDDMSetAuxiliaryMat()`, `MATIS`, `PCBDDC`, `PCDEFLATION`, `PCTELESCOPE`, `PCASM`,
3002e31fc274SPierre Jolivet           `PCHPDDMSetCoarseCorrectionType()`, `PCHPDDMHasNeumannMat()`, `PCHPDDMSetRHSMat()`, `PCHPDDMSetDeflationMat()`, `PCHPDDMSetSTShareSubKSP()`,
3003e31fc274SPierre Jolivet           `PCHPDDMGetSTShareSubKSP()`, `PCHPDDMGetCoarseCorrectionType()`, `PCHPDDMGetComplexities()`
3004f1580f4eSBarry Smith M*/
3005d71ae5a4SJacob Faibussowitsch PETSC_EXTERN PetscErrorCode PCCreate_HPDDM(PC pc)
3006d71ae5a4SJacob Faibussowitsch {
3007f1580f4eSBarry Smith   PC_HPDDM *data;
3008f1580f4eSBarry Smith   PetscBool found;
3009f1580f4eSBarry Smith 
3010f1580f4eSBarry Smith   PetscFunctionBegin;
3011f1580f4eSBarry Smith   if (!loadedSym) {
3012f1580f4eSBarry Smith     PetscCall(HPDDMLoadDL_Private(&found));
3013db4a47b3SPierre Jolivet     if (found) PetscCall(PetscDLLibrarySym(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, nullptr, "PCHPDDM_Internal", (void **)&loadedSym));
3014f1580f4eSBarry Smith   }
3015f1580f4eSBarry Smith   PetscCheck(loadedSym, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCHPDDM_Internal symbol not found in loaded libhpddm_petsc");
30164dfa11a4SJacob Faibussowitsch   PetscCall(PetscNew(&data));
3017f1580f4eSBarry Smith   pc->data                = data;
3018c8ea6600SPierre Jolivet   data->Neumann           = PETSC_BOOL3_UNKNOWN;
3019f1580f4eSBarry Smith   pc->ops->reset          = PCReset_HPDDM;
3020f1580f4eSBarry Smith   pc->ops->destroy        = PCDestroy_HPDDM;
3021f1580f4eSBarry Smith   pc->ops->setfromoptions = PCSetFromOptions_HPDDM;
3022f1580f4eSBarry Smith   pc->ops->setup          = PCSetUp_HPDDM;
3023f1580f4eSBarry Smith   pc->ops->apply          = PCApply_HPDDM;
3024f1580f4eSBarry Smith   pc->ops->matapply       = PCMatApply_HPDDM;
3025f1580f4eSBarry Smith   pc->ops->view           = PCView_HPDDM;
3026f1580f4eSBarry Smith   pc->ops->presolve       = PCPreSolve_HPDDM;
3027f1580f4eSBarry Smith 
3028f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetAuxiliaryMat_C", PCHPDDMSetAuxiliaryMat_HPDDM));
3029f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMHasNeumannMat_C", PCHPDDMHasNeumannMat_HPDDM));
3030f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetRHSMat_C", PCHPDDMSetRHSMat_HPDDM));
3031f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetCoarseCorrectionType_C", PCHPDDMSetCoarseCorrectionType_HPDDM));
3032f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetCoarseCorrectionType_C", PCHPDDMGetCoarseCorrectionType_HPDDM));
3033e31fc274SPierre Jolivet   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetSTShareSubKSP_C", PCHPDDMSetSTShareSubKSP_HPDDM));
3034f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetSTShareSubKSP_C", PCHPDDMGetSTShareSubKSP_HPDDM));
3035f1580f4eSBarry Smith   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetDeflationMat_C", PCHPDDMSetDeflationMat_HPDDM));
30363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3037f1580f4eSBarry Smith }
3038f1580f4eSBarry Smith 
3039f1580f4eSBarry Smith /*@C
3040f1580f4eSBarry Smith   PCHPDDMInitializePackage - This function initializes everything in the `PCHPDDM` package. It is called from `PCInitializePackage()`.
3041f1580f4eSBarry Smith 
3042f1580f4eSBarry Smith   Level: developer
3043f1580f4eSBarry Smith 
3044562efe2eSBarry Smith .seealso: [](ch_ksp), `PetscInitialize()`
3045f1580f4eSBarry Smith @*/
3046d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMInitializePackage(void)
3047d71ae5a4SJacob Faibussowitsch {
3048f1580f4eSBarry Smith   char ename[32];
3049f1580f4eSBarry Smith 
3050f1580f4eSBarry Smith   PetscFunctionBegin;
30513ba16761SJacob Faibussowitsch   if (PCHPDDMPackageInitialized) PetscFunctionReturn(PETSC_SUCCESS);
3052f1580f4eSBarry Smith   PCHPDDMPackageInitialized = PETSC_TRUE;
3053f1580f4eSBarry Smith   PetscCall(PetscRegisterFinalize(PCHPDDMFinalizePackage));
3054f1580f4eSBarry Smith   /* general events registered once during package initialization */
3055f1580f4eSBarry Smith   /* some of these events are not triggered in libpetsc,          */
3056f1580f4eSBarry Smith   /* but rather directly in libhpddm_petsc,                       */
3057f1580f4eSBarry Smith   /* which is in charge of performing the following operations    */
3058f1580f4eSBarry Smith 
3059f1580f4eSBarry Smith   /* domain decomposition structure from Pmat sparsity pattern    */
3060f1580f4eSBarry Smith   PetscCall(PetscLogEventRegister("PCHPDDMStrc", PC_CLASSID, &PC_HPDDM_Strc));
3061f1580f4eSBarry Smith   /* Galerkin product, redistribution, and setup (not triggered in libpetsc)                */
3062f1580f4eSBarry Smith   PetscCall(PetscLogEventRegister("PCHPDDMPtAP", PC_CLASSID, &PC_HPDDM_PtAP));
3063f1580f4eSBarry Smith   /* Galerkin product with summation, redistribution, and setup (not triggered in libpetsc) */
3064f1580f4eSBarry Smith   PetscCall(PetscLogEventRegister("PCHPDDMPtBP", PC_CLASSID, &PC_HPDDM_PtBP));
3065f1580f4eSBarry Smith   /* next level construction using PtAP and PtBP (not triggered in libpetsc)                */
3066f1580f4eSBarry Smith   PetscCall(PetscLogEventRegister("PCHPDDMNext", PC_CLASSID, &PC_HPDDM_Next));
3067f1580f4eSBarry Smith   static_assert(PETSC_PCHPDDM_MAXLEVELS <= 9, "PETSC_PCHPDDM_MAXLEVELS value is too high");
3068811e8887SPierre Jolivet   for (PetscInt i = 1; i < PETSC_PCHPDDM_MAXLEVELS; ++i) {
3069f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(ename, sizeof(ename), "PCHPDDMSetUp L%1" PetscInt_FMT, i));
3070f1580f4eSBarry Smith     /* events during a PCSetUp() at level #i _except_ the assembly */
3071f1580f4eSBarry Smith     /* of the Galerkin operator of the coarser level #(i + 1)      */
3072f1580f4eSBarry Smith     PetscCall(PetscLogEventRegister(ename, PC_CLASSID, &PC_HPDDM_SetUp[i - 1]));
3073f1580f4eSBarry Smith     PetscCall(PetscSNPrintf(ename, sizeof(ename), "PCHPDDMSolve L%1" PetscInt_FMT, i));
3074f1580f4eSBarry Smith     /* events during a PCApply() at level #i _except_              */
3075f1580f4eSBarry Smith     /* the KSPSolve() of the coarser level #(i + 1)                */
3076f1580f4eSBarry Smith     PetscCall(PetscLogEventRegister(ename, PC_CLASSID, &PC_HPDDM_Solve[i - 1]));
3077f1580f4eSBarry Smith   }
30783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3079f1580f4eSBarry Smith }
3080f1580f4eSBarry Smith 
3081f1580f4eSBarry Smith /*@C
3082f1580f4eSBarry Smith   PCHPDDMFinalizePackage - This function frees everything from the `PCHPDDM` package. It is called from `PetscFinalize()`.
3083f1580f4eSBarry Smith 
3084f1580f4eSBarry Smith   Level: developer
3085f1580f4eSBarry Smith 
3086562efe2eSBarry Smith .seealso: [](ch_ksp), `PetscFinalize()`
3087f1580f4eSBarry Smith @*/
3088d71ae5a4SJacob Faibussowitsch PetscErrorCode PCHPDDMFinalizePackage(void)
3089d71ae5a4SJacob Faibussowitsch {
3090f1580f4eSBarry Smith   PetscFunctionBegin;
3091f1580f4eSBarry Smith   PCHPDDMPackageInitialized = PETSC_FALSE;
30923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3093f1580f4eSBarry Smith }
30949bb5c669SPierre Jolivet 
30959bb5c669SPierre Jolivet static PetscErrorCode MatMult_Harmonic(Mat A, Vec x, Vec y)
30969bb5c669SPierre Jolivet {
30979bb5c669SPierre Jolivet   Harmonic h; /* [ A_00  A_01       ], furthermore, A_00 = [ A_loc,loc  A_loc,ovl ], thus, A_01 = [         ] */
30989bb5c669SPierre Jolivet               /* [ A_10  A_11  A_12 ]                      [ A_ovl,loc  A_ovl,ovl ]               [ A_ovl,1 ] */
30999bb5c669SPierre Jolivet   Vec sub;    /*  y = A x = R_loc R_0 [ A_00  A_01 ]^-1                                   R_loc = [  I_loc  ] */
31009bb5c669SPierre Jolivet               /*                      [ A_10  A_11 ]    R_1^T A_12 x                              [         ] */
31019bb5c669SPierre Jolivet   PetscFunctionBegin;
31029bb5c669SPierre Jolivet   PetscCall(MatShellGetContext(A, &h));
31039bb5c669SPierre Jolivet   PetscCall(VecSet(h->v, 0.0));
31049bb5c669SPierre Jolivet   PetscCall(VecGetSubVector(h->v, h->is[0], &sub));
31059bb5c669SPierre Jolivet   PetscCall(MatMult(h->A[0], x, sub));
31069bb5c669SPierre Jolivet   PetscCall(VecRestoreSubVector(h->v, h->is[0], &sub));
31079bb5c669SPierre Jolivet   PetscCall(KSPSolve(h->ksp, h->v, h->v));
31089bb5c669SPierre Jolivet   PetscCall(VecISCopy(h->v, h->is[1], SCATTER_REVERSE, y));
31099bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
31109bb5c669SPierre Jolivet }
31119bb5c669SPierre Jolivet 
31129bb5c669SPierre Jolivet static PetscErrorCode MatMultTranspose_Harmonic(Mat A, Vec y, Vec x)
31139bb5c669SPierre Jolivet {
31149bb5c669SPierre Jolivet   Harmonic h;   /* x = A^T y =            [ A_00  A_01 ]^-T R_0^T R_loc^T y */
31159bb5c669SPierre Jolivet   Vec      sub; /*             A_12^T R_1 [ A_10  A_11 ]                    */
31169bb5c669SPierre Jolivet 
31179bb5c669SPierre Jolivet   PetscFunctionBegin;
31189bb5c669SPierre Jolivet   PetscCall(MatShellGetContext(A, &h));
31199bb5c669SPierre Jolivet   PetscCall(VecSet(h->v, 0.0));
31209bb5c669SPierre Jolivet   PetscCall(VecISCopy(h->v, h->is[1], SCATTER_FORWARD, y));
31219bb5c669SPierre Jolivet   PetscCall(KSPSolveTranspose(h->ksp, h->v, h->v));
31229bb5c669SPierre Jolivet   PetscCall(VecGetSubVector(h->v, h->is[0], &sub));
31239bb5c669SPierre Jolivet   PetscCall(MatMultTranspose(h->A[0], sub, x));
31249bb5c669SPierre Jolivet   PetscCall(VecRestoreSubVector(h->v, h->is[0], &sub));
31259bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
31269bb5c669SPierre Jolivet }
31279bb5c669SPierre Jolivet 
31289bb5c669SPierre Jolivet static PetscErrorCode MatProduct_AB_Harmonic(Mat S, Mat X, Mat Y, void *)
31299bb5c669SPierre Jolivet {
31309bb5c669SPierre Jolivet   Harmonic h;
31319bb5c669SPierre Jolivet   Mat      A, B;
31329bb5c669SPierre Jolivet   Vec      a, b;
31339bb5c669SPierre Jolivet 
31349bb5c669SPierre Jolivet   PetscFunctionBegin;
31359bb5c669SPierre Jolivet   PetscCall(MatShellGetContext(S, &h));
3136fb842aefSJose E. Roman   PetscCall(MatMatMult(h->A[0], X, MAT_INITIAL_MATRIX, PETSC_CURRENT, &A));
31379bb5c669SPierre Jolivet   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, h->ksp->pc->mat->rmap->n, A->cmap->n, nullptr, &B));
31389bb5c669SPierre Jolivet   for (PetscInt i = 0; i < A->cmap->n; ++i) {
31399bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecRead(A, i, &a));
31409bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecWrite(B, i, &b));
31419bb5c669SPierre Jolivet     PetscCall(VecISCopy(b, h->is[0], SCATTER_FORWARD, a));
31429bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecWrite(B, i, &b));
31439bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecRead(A, i, &a));
31449bb5c669SPierre Jolivet   }
31459bb5c669SPierre Jolivet   PetscCall(MatDestroy(&A));
31469bb5c669SPierre Jolivet   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, h->ksp->pc->mat->rmap->n, B->cmap->n, nullptr, &A));
31479bb5c669SPierre Jolivet   PetscCall(KSPMatSolve(h->ksp, B, A));
31489bb5c669SPierre Jolivet   PetscCall(MatDestroy(&B));
31499bb5c669SPierre Jolivet   for (PetscInt i = 0; i < A->cmap->n; ++i) {
31509bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecRead(A, i, &a));
31519bb5c669SPierre Jolivet     PetscCall(MatDenseGetColumnVecWrite(Y, i, &b));
31529bb5c669SPierre Jolivet     PetscCall(VecISCopy(a, h->is[1], SCATTER_REVERSE, b));
31539bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecWrite(Y, i, &b));
31549bb5c669SPierre Jolivet     PetscCall(MatDenseRestoreColumnVecRead(A, i, &a));
31559bb5c669SPierre Jolivet   }
31569bb5c669SPierre Jolivet   PetscCall(MatDestroy(&A));
31579bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
31589bb5c669SPierre Jolivet }
31599bb5c669SPierre Jolivet 
31609bb5c669SPierre Jolivet static PetscErrorCode MatDestroy_Harmonic(Mat A)
31619bb5c669SPierre Jolivet {
31629bb5c669SPierre Jolivet   Harmonic h;
31639bb5c669SPierre Jolivet 
31649bb5c669SPierre Jolivet   PetscFunctionBegin;
31659bb5c669SPierre Jolivet   PetscCall(MatShellGetContext(A, &h));
316632603206SJames Wright   for (PetscInt i = 0; i < 5; ++i) PetscCall(ISDestroy(h->is + i));
31679bb5c669SPierre Jolivet   PetscCall(PetscFree(h->is));
31689bb5c669SPierre Jolivet   PetscCall(VecDestroy(&h->v));
31699bb5c669SPierre Jolivet   for (PetscInt i = 0; i < 2; ++i) PetscCall(MatDestroy(h->A + i));
31709bb5c669SPierre Jolivet   PetscCall(PetscFree(h->A));
31719bb5c669SPierre Jolivet   PetscCall(KSPDestroy(&h->ksp));
31729bb5c669SPierre Jolivet   PetscCall(PetscFree(h));
31739bb5c669SPierre Jolivet   PetscFunctionReturn(PETSC_SUCCESS);
31749bb5c669SPierre Jolivet }
3175