xref: /petsc/src/ksp/pc/impls/hypre/hypre.c (revision bcee047adeeb73090d7e36cc71e39fc287cdbb97)
1 /*
2    Provides an interface to the LLNL package hypre
3 */
4 
5 #include <petscpkg_version.h>
6 #include <petsc/private/pcimpl.h> /*I "petscpc.h" I*/
7 /* this include is needed ONLY to allow access to the private data inside the Mat object specific to hypre */
8 #include <petsc/private/matimpl.h>
9 #include <petsc/private/vecimpl.h>
10 #include <../src/vec/vec/impls/hypre/vhyp.h>
11 #include <../src/mat/impls/hypre/mhypre.h>
12 #include <../src/dm/impls/da/hypre/mhyp.h>
13 #include <_hypre_parcsr_ls.h>
14 #include <petscmathypre.h>
15 
16 #if defined(PETSC_HAVE_HYPRE_DEVICE)
17   #include <petsc/private/deviceimpl.h>
18 #endif
19 
20 static PetscBool  cite            = PETSC_FALSE;
21 static const char hypreCitation[] = "@manual{hypre-web-page,\n  title  = {{\\sl hypre}: High Performance Preconditioners},\n  organization = {Lawrence Livermore National Laboratory},\n  note  = "
22                                     "{\\url{https://www.llnl.gov/casc/hypre}}\n}\n";
23 
24 /*
25    Private context (data structure) for the  preconditioner.
26 */
27 typedef struct {
28   HYPRE_Solver hsolver;
29   Mat          hpmat; /* MatHYPRE */
30 
31   HYPRE_Int (*destroy)(HYPRE_Solver);
32   HYPRE_Int (*solve)(HYPRE_Solver, HYPRE_ParCSRMatrix, HYPRE_ParVector, HYPRE_ParVector);
33   HYPRE_Int (*setup)(HYPRE_Solver, HYPRE_ParCSRMatrix, HYPRE_ParVector, HYPRE_ParVector);
34 
35   MPI_Comm comm_hypre;
36   char    *hypre_type;
37 
38   /* options for Pilut and BoomerAMG*/
39   PetscInt  maxiter;
40   PetscReal tol;
41 
42   /* options for Pilut */
43   PetscInt factorrowsize;
44 
45   /* options for ParaSails */
46   PetscInt  nlevels;
47   PetscReal threshold;
48   PetscReal filter;
49   PetscReal loadbal;
50   PetscInt  logging;
51   PetscInt  ruse;
52   PetscInt  symt;
53 
54   /* options for BoomerAMG */
55   PetscBool printstatistics;
56 
57   /* options for BoomerAMG */
58   PetscInt  cycletype;
59   PetscInt  maxlevels;
60   PetscReal strongthreshold;
61   PetscReal maxrowsum;
62   PetscInt  gridsweeps[3];
63   PetscInt  coarsentype;
64   PetscInt  measuretype;
65   PetscInt  smoothtype;
66   PetscInt  smoothnumlevels;
67   PetscInt  eu_level;         /* Number of levels for ILU(k) in Euclid */
68   PetscReal eu_droptolerance; /* Drop tolerance for ILU(k) in Euclid */
69   PetscInt  eu_bj;            /* Defines use of Block Jacobi ILU in Euclid */
70   PetscInt  relaxtype[3];
71   PetscReal relaxweight;
72   PetscReal outerrelaxweight;
73   PetscInt  relaxorder;
74   PetscReal truncfactor;
75   PetscBool applyrichardson;
76   PetscInt  pmax;
77   PetscInt  interptype;
78   PetscInt  maxc;
79   PetscInt  minc;
80 #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0)
81   char *spgemm_type; // this is a global hypre parameter but is closely associated with BoomerAMG
82 #endif
83   /* GPU */
84   PetscBool keeptranspose;
85   PetscInt  rap2;
86   PetscInt  mod_rap2;
87 
88   /* AIR */
89   PetscInt  Rtype;
90   PetscReal Rstrongthreshold;
91   PetscReal Rfilterthreshold;
92   PetscInt  Adroptype;
93   PetscReal Adroptol;
94 
95   PetscInt  agg_nl;
96   PetscInt  agg_interptype;
97   PetscInt  agg_num_paths;
98   PetscBool nodal_relax;
99   PetscInt  nodal_relax_levels;
100 
101   PetscInt  nodal_coarsening;
102   PetscInt  nodal_coarsening_diag;
103   PetscInt  vec_interp_variant;
104   PetscInt  vec_interp_qmax;
105   PetscBool vec_interp_smooth;
106   PetscInt  interp_refine;
107 
108   /* NearNullSpace support */
109   VecHYPRE_IJVector *hmnull;
110   HYPRE_ParVector   *phmnull;
111   PetscInt           n_hmnull;
112   Vec                hmnull_constant;
113 
114   /* options for AS (Auxiliary Space preconditioners) */
115   PetscInt  as_print;
116   PetscInt  as_max_iter;
117   PetscReal as_tol;
118   PetscInt  as_relax_type;
119   PetscInt  as_relax_times;
120   PetscReal as_relax_weight;
121   PetscReal as_omega;
122   PetscInt  as_amg_alpha_opts[5]; /* AMG coarsen type, agg_levels, relax_type, interp_type, Pmax for vector Poisson (AMS) or Curl problem (ADS) */
123   PetscReal as_amg_alpha_theta;   /* AMG strength for vector Poisson (AMS) or Curl problem (ADS) */
124   PetscInt  as_amg_beta_opts[5];  /* AMG coarsen type, agg_levels, relax_type, interp_type, Pmax for scalar Poisson (AMS) or vector Poisson (ADS) */
125   PetscReal as_amg_beta_theta;    /* AMG strength for scalar Poisson (AMS) or vector Poisson (ADS)  */
126   PetscInt  ams_cycle_type;
127   PetscInt  ads_cycle_type;
128 
129   /* additional data */
130   Mat G;             /* MatHYPRE */
131   Mat C;             /* MatHYPRE */
132   Mat alpha_Poisson; /* MatHYPRE */
133   Mat beta_Poisson;  /* MatHYPRE */
134 
135   /* extra information for AMS */
136   PetscInt          dim; /* geometrical dimension */
137   VecHYPRE_IJVector coords[3];
138   VecHYPRE_IJVector constants[3];
139   VecHYPRE_IJVector interior;
140   Mat               RT_PiFull, RT_Pi[3];
141   Mat               ND_PiFull, ND_Pi[3];
142   PetscBool         ams_beta_is_zero;
143   PetscBool         ams_beta_is_zero_part;
144   PetscInt          ams_proj_freq;
145 } PC_HYPRE;
146 
147 PetscErrorCode PCHYPREGetSolver(PC pc, HYPRE_Solver *hsolver)
148 {
149   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
150 
151   PetscFunctionBegin;
152   *hsolver = jac->hsolver;
153   PetscFunctionReturn(PETSC_SUCCESS);
154 }
155 
156 /*
157   Matrices with AIJ format are created IN PLACE with using (I,J,data) from BoomerAMG. Since the data format in hypre_ParCSRMatrix
158   is different from that used in PETSc, the original hypre_ParCSRMatrix can not be used any more after call this routine.
159   It is used in PCHMG. Other users should avoid using this function.
160 */
161 static PetscErrorCode PCGetCoarseOperators_BoomerAMG(PC pc, PetscInt *nlevels, Mat *operators[])
162 {
163   PC_HYPRE            *jac  = (PC_HYPRE *)pc->data;
164   PetscBool            same = PETSC_FALSE;
165   PetscInt             num_levels, l;
166   Mat                 *mattmp;
167   hypre_ParCSRMatrix **A_array;
168 
169   PetscFunctionBegin;
170   PetscCall(PetscStrcmp(jac->hypre_type, "boomeramg", &same));
171   PetscCheck(same, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_NOTSAMETYPE, "Hypre type is not BoomerAMG ");
172   num_levels = hypre_ParAMGDataNumLevels((hypre_ParAMGData *)(jac->hsolver));
173   PetscCall(PetscMalloc1(num_levels, &mattmp));
174   A_array = hypre_ParAMGDataAArray((hypre_ParAMGData *)(jac->hsolver));
175   for (l = 1; l < num_levels; l++) {
176     PetscCall(MatCreateFromParCSR(A_array[l], MATAIJ, PETSC_OWN_POINTER, &(mattmp[num_levels - 1 - l])));
177     /* We want to own the data, and HYPRE can not touch this matrix any more */
178     A_array[l] = NULL;
179   }
180   *nlevels   = num_levels;
181   *operators = mattmp;
182   PetscFunctionReturn(PETSC_SUCCESS);
183 }
184 
185 /*
186   Matrices with AIJ format are created IN PLACE with using (I,J,data) from BoomerAMG. Since the data format in hypre_ParCSRMatrix
187   is different from that used in PETSc, the original hypre_ParCSRMatrix can not be used any more after call this routine.
188   It is used in PCHMG. Other users should avoid using this function.
189 */
190 static PetscErrorCode PCGetInterpolations_BoomerAMG(PC pc, PetscInt *nlevels, Mat *interpolations[])
191 {
192   PC_HYPRE            *jac  = (PC_HYPRE *)pc->data;
193   PetscBool            same = PETSC_FALSE;
194   PetscInt             num_levels, l;
195   Mat                 *mattmp;
196   hypre_ParCSRMatrix **P_array;
197 
198   PetscFunctionBegin;
199   PetscCall(PetscStrcmp(jac->hypre_type, "boomeramg", &same));
200   PetscCheck(same, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_NOTSAMETYPE, "Hypre type is not BoomerAMG ");
201   num_levels = hypre_ParAMGDataNumLevels((hypre_ParAMGData *)(jac->hsolver));
202   PetscCall(PetscMalloc1(num_levels, &mattmp));
203   P_array = hypre_ParAMGDataPArray((hypre_ParAMGData *)(jac->hsolver));
204   for (l = 1; l < num_levels; l++) {
205     PetscCall(MatCreateFromParCSR(P_array[num_levels - 1 - l], MATAIJ, PETSC_OWN_POINTER, &(mattmp[l - 1])));
206     /* We want to own the data, and HYPRE can not touch this matrix any more */
207     P_array[num_levels - 1 - l] = NULL;
208   }
209   *nlevels        = num_levels;
210   *interpolations = mattmp;
211   PetscFunctionReturn(PETSC_SUCCESS);
212 }
213 
214 /* Resets (frees) Hypre's representation of the near null space */
215 static PetscErrorCode PCHYPREResetNearNullSpace_Private(PC pc)
216 {
217   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
218   PetscInt  i;
219 
220   PetscFunctionBegin;
221   for (i = 0; i < jac->n_hmnull; i++) PetscCall(VecHYPRE_IJVectorDestroy(&jac->hmnull[i]));
222   PetscCall(PetscFree(jac->hmnull));
223   PetscCall(PetscFree(jac->phmnull));
224   PetscCall(VecDestroy(&jac->hmnull_constant));
225   jac->n_hmnull = 0;
226   PetscFunctionReturn(PETSC_SUCCESS);
227 }
228 
229 static PetscErrorCode PCSetUp_HYPRE(PC pc)
230 {
231   PC_HYPRE          *jac = (PC_HYPRE *)pc->data;
232   Mat_HYPRE         *hjac;
233   HYPRE_ParCSRMatrix hmat;
234   HYPRE_ParVector    bv, xv;
235   PetscBool          ishypre;
236 
237   PetscFunctionBegin;
238   /* default type is boomerAMG */
239   if (!jac->hypre_type) PetscCall(PCHYPRESetType(pc, "boomeramg"));
240 
241   /* get hypre matrix */
242   if (pc->flag == DIFFERENT_NONZERO_PATTERN) PetscCall(MatDestroy(&jac->hpmat));
243   PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRE, &ishypre));
244   if (!ishypre) {
245     /* Temporary fix since we do not support MAT_REUSE_MATRIX with HYPRE device */
246 #if defined(PETSC_HAVE_HYPRE_DEVICE)
247     PetscBool iscuda, iship, iskokkos;
248 
249     PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &iscuda, MATSEQAIJCUSPARSE, MATMPIAIJCUSPARSE, ""));
250     PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &iship, MATSEQAIJHIPSPARSE, MATMPIAIJHIPSPARSE, ""));
251     PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &iskokkos, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, ""));
252     if (iscuda || iship || iskokkos) PetscCall(MatDestroy(&jac->hpmat));
253 #endif
254     PetscCall(MatConvert(pc->pmat, MATHYPRE, jac->hpmat ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX, &jac->hpmat));
255   } else {
256     PetscCall(PetscObjectReference((PetscObject)pc->pmat));
257     PetscCall(MatDestroy(&jac->hpmat));
258     jac->hpmat = pc->pmat;
259   }
260 
261   /* allow debug */
262   PetscCall(MatViewFromOptions(jac->hpmat, NULL, "-pc_hypre_mat_view"));
263   hjac = (Mat_HYPRE *)(jac->hpmat->data);
264 
265   /* special case for BoomerAMG */
266   if (jac->setup == HYPRE_BoomerAMGSetup) {
267     MatNullSpace mnull;
268     PetscBool    has_const;
269     PetscInt     bs, nvec, i;
270     const Vec   *vecs;
271 
272     PetscCall(MatGetBlockSize(pc->pmat, &bs));
273     if (bs > 1) PetscCallExternal(HYPRE_BoomerAMGSetNumFunctions, jac->hsolver, bs);
274     PetscCall(MatGetNearNullSpace(pc->mat, &mnull));
275     if (mnull) {
276       PetscCall(PCHYPREResetNearNullSpace_Private(pc));
277       PetscCall(MatNullSpaceGetVecs(mnull, &has_const, &nvec, &vecs));
278       PetscCall(PetscMalloc1(nvec + 1, &jac->hmnull));
279       PetscCall(PetscMalloc1(nvec + 1, &jac->phmnull));
280       for (i = 0; i < nvec; i++) {
281         PetscCall(VecHYPRE_IJVectorCreate(vecs[i]->map, &jac->hmnull[i]));
282         PetscCall(VecHYPRE_IJVectorCopy(vecs[i], jac->hmnull[i]));
283         PetscCallExternal(HYPRE_IJVectorGetObject, jac->hmnull[i]->ij, (void **)&jac->phmnull[i]);
284       }
285       if (has_const) {
286         PetscCall(MatCreateVecs(pc->pmat, &jac->hmnull_constant, NULL));
287         PetscCall(VecSet(jac->hmnull_constant, 1));
288         PetscCall(VecNormalize(jac->hmnull_constant, NULL));
289         PetscCall(VecHYPRE_IJVectorCreate(jac->hmnull_constant->map, &jac->hmnull[nvec]));
290         PetscCall(VecHYPRE_IJVectorCopy(jac->hmnull_constant, jac->hmnull[nvec]));
291         PetscCallExternal(HYPRE_IJVectorGetObject, jac->hmnull[nvec]->ij, (void **)&jac->phmnull[nvec]);
292         nvec++;
293       }
294       PetscCallExternal(HYPRE_BoomerAMGSetInterpVectors, jac->hsolver, nvec, jac->phmnull);
295       jac->n_hmnull = nvec;
296     }
297   }
298 
299   /* special case for AMS */
300   if (jac->setup == HYPRE_AMSSetup) {
301     Mat_HYPRE         *hm;
302     HYPRE_ParCSRMatrix parcsr;
303     if (!jac->coords[0] && !jac->constants[0] && !(jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1]))) {
304       SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE AMS preconditioner needs either the coordinate vectors via PCSetCoordinates() or the edge constant vectors via PCHYPRESetEdgeConstantVectors() or the interpolation matrix via PCHYPRESetInterpolations()");
305     }
306     if (jac->dim) PetscCallExternal(HYPRE_AMSSetDimension, jac->hsolver, jac->dim);
307     if (jac->constants[0]) {
308       HYPRE_ParVector ozz, zoz, zzo = NULL;
309       PetscCallExternal(HYPRE_IJVectorGetObject, jac->constants[0]->ij, (void **)(&ozz));
310       PetscCallExternal(HYPRE_IJVectorGetObject, jac->constants[1]->ij, (void **)(&zoz));
311       if (jac->constants[2]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->constants[2]->ij, (void **)(&zzo));
312       PetscCallExternal(HYPRE_AMSSetEdgeConstantVectors, jac->hsolver, ozz, zoz, zzo);
313     }
314     if (jac->coords[0]) {
315       HYPRE_ParVector coords[3];
316       coords[0] = NULL;
317       coords[1] = NULL;
318       coords[2] = NULL;
319       if (jac->coords[0]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[0]->ij, (void **)(&coords[0]));
320       if (jac->coords[1]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[1]->ij, (void **)(&coords[1]));
321       if (jac->coords[2]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[2]->ij, (void **)(&coords[2]));
322       PetscCallExternal(HYPRE_AMSSetCoordinateVectors, jac->hsolver, coords[0], coords[1], coords[2]);
323     }
324     PetscCheck(jac->G, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE AMS preconditioner needs the discrete gradient operator via PCHYPRESetDiscreteGradient");
325     hm = (Mat_HYPRE *)(jac->G->data);
326     PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr));
327     PetscCallExternal(HYPRE_AMSSetDiscreteGradient, jac->hsolver, parcsr);
328     if (jac->alpha_Poisson) {
329       hm = (Mat_HYPRE *)(jac->alpha_Poisson->data);
330       PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr));
331       PetscCallExternal(HYPRE_AMSSetAlphaPoissonMatrix, jac->hsolver, parcsr);
332     }
333     if (jac->ams_beta_is_zero) {
334       PetscCallExternal(HYPRE_AMSSetBetaPoissonMatrix, jac->hsolver, NULL);
335     } else if (jac->beta_Poisson) {
336       hm = (Mat_HYPRE *)(jac->beta_Poisson->data);
337       PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr));
338       PetscCallExternal(HYPRE_AMSSetBetaPoissonMatrix, jac->hsolver, parcsr);
339     } else if (jac->ams_beta_is_zero_part) {
340       if (jac->interior) {
341         HYPRE_ParVector interior = NULL;
342         PetscCallExternal(HYPRE_IJVectorGetObject, jac->interior->ij, (void **)(&interior));
343         PetscCallExternal(HYPRE_AMSSetInteriorNodes, jac->hsolver, interior);
344       } else {
345         jac->ams_beta_is_zero_part = PETSC_FALSE;
346       }
347     }
348     if (jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1])) {
349       PetscInt           i;
350       HYPRE_ParCSRMatrix nd_parcsrfull, nd_parcsr[3];
351       if (jac->ND_PiFull) {
352         hm = (Mat_HYPRE *)(jac->ND_PiFull->data);
353         PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsrfull));
354       } else {
355         nd_parcsrfull = NULL;
356       }
357       for (i = 0; i < 3; ++i) {
358         if (jac->ND_Pi[i]) {
359           hm = (Mat_HYPRE *)(jac->ND_Pi[i]->data);
360           PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsr[i]));
361         } else {
362           nd_parcsr[i] = NULL;
363         }
364       }
365       PetscCallExternal(HYPRE_AMSSetInterpolations, jac->hsolver, nd_parcsrfull, nd_parcsr[0], nd_parcsr[1], nd_parcsr[2]);
366     }
367   }
368   /* special case for ADS */
369   if (jac->setup == HYPRE_ADSSetup) {
370     Mat_HYPRE         *hm;
371     HYPRE_ParCSRMatrix parcsr;
372     if (!jac->coords[0] && !((jac->RT_PiFull || (jac->RT_Pi[0] && jac->RT_Pi[1])) && (jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1])))) {
373       SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner needs either the coordinate vectors via PCSetCoordinates() or the interpolation matrices via PCHYPRESetInterpolations");
374     } else PetscCheck(jac->coords[1] && jac->coords[2], PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner has been designed for three dimensional problems! For two dimensional problems, use HYPRE AMS instead");
375     PetscCheck(jac->G, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner needs the discrete gradient operator via PCHYPRESetDiscreteGradient");
376     PetscCheck(jac->C, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER, "HYPRE ADS preconditioner needs the discrete curl operator via PCHYPRESetDiscreteGradient");
377     if (jac->coords[0]) {
378       HYPRE_ParVector coords[3];
379       coords[0] = NULL;
380       coords[1] = NULL;
381       coords[2] = NULL;
382       if (jac->coords[0]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[0]->ij, (void **)(&coords[0]));
383       if (jac->coords[1]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[1]->ij, (void **)(&coords[1]));
384       if (jac->coords[2]) PetscCallExternal(HYPRE_IJVectorGetObject, jac->coords[2]->ij, (void **)(&coords[2]));
385       PetscCallExternal(HYPRE_ADSSetCoordinateVectors, jac->hsolver, coords[0], coords[1], coords[2]);
386     }
387     hm = (Mat_HYPRE *)(jac->G->data);
388     PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr));
389     PetscCallExternal(HYPRE_ADSSetDiscreteGradient, jac->hsolver, parcsr);
390     hm = (Mat_HYPRE *)(jac->C->data);
391     PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&parcsr));
392     PetscCallExternal(HYPRE_ADSSetDiscreteCurl, jac->hsolver, parcsr);
393     if ((jac->RT_PiFull || (jac->RT_Pi[0] && jac->RT_Pi[1])) && (jac->ND_PiFull || (jac->ND_Pi[0] && jac->ND_Pi[1]))) {
394       PetscInt           i;
395       HYPRE_ParCSRMatrix rt_parcsrfull, rt_parcsr[3];
396       HYPRE_ParCSRMatrix nd_parcsrfull, nd_parcsr[3];
397       if (jac->RT_PiFull) {
398         hm = (Mat_HYPRE *)(jac->RT_PiFull->data);
399         PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&rt_parcsrfull));
400       } else {
401         rt_parcsrfull = NULL;
402       }
403       for (i = 0; i < 3; ++i) {
404         if (jac->RT_Pi[i]) {
405           hm = (Mat_HYPRE *)(jac->RT_Pi[i]->data);
406           PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&rt_parcsr[i]));
407         } else {
408           rt_parcsr[i] = NULL;
409         }
410       }
411       if (jac->ND_PiFull) {
412         hm = (Mat_HYPRE *)(jac->ND_PiFull->data);
413         PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsrfull));
414       } else {
415         nd_parcsrfull = NULL;
416       }
417       for (i = 0; i < 3; ++i) {
418         if (jac->ND_Pi[i]) {
419           hm = (Mat_HYPRE *)(jac->ND_Pi[i]->data);
420           PetscCallExternal(HYPRE_IJMatrixGetObject, hm->ij, (void **)(&nd_parcsr[i]));
421         } else {
422           nd_parcsr[i] = NULL;
423         }
424       }
425       PetscCallExternal(HYPRE_ADSSetInterpolations, jac->hsolver, rt_parcsrfull, rt_parcsr[0], rt_parcsr[1], rt_parcsr[2], nd_parcsrfull, nd_parcsr[0], nd_parcsr[1], nd_parcsr[2]);
426     }
427   }
428   PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&hmat);
429   PetscCallExternal(HYPRE_IJVectorGetObject, hjac->b->ij, (void **)&bv);
430   PetscCallExternal(HYPRE_IJVectorGetObject, hjac->x->ij, (void **)&xv);
431   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
432   PetscCallExternal(jac->setup, jac->hsolver, hmat, bv, xv);
433   PetscCall(PetscFPTrapPop());
434   PetscFunctionReturn(PETSC_SUCCESS);
435 }
436 
437 static PetscErrorCode PCApply_HYPRE(PC pc, Vec b, Vec x)
438 {
439   PC_HYPRE          *jac  = (PC_HYPRE *)pc->data;
440   Mat_HYPRE         *hjac = (Mat_HYPRE *)(jac->hpmat->data);
441   HYPRE_ParCSRMatrix hmat;
442   HYPRE_ParVector    jbv, jxv;
443 
444   PetscFunctionBegin;
445   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
446   if (!jac->applyrichardson) PetscCall(VecSet(x, 0.0));
447   PetscCall(VecHYPRE_IJVectorPushVecRead(hjac->b, b));
448   if (jac->applyrichardson) PetscCall(VecHYPRE_IJVectorPushVec(hjac->x, x));
449   else PetscCall(VecHYPRE_IJVectorPushVecWrite(hjac->x, x));
450   PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&hmat);
451   PetscCallExternal(HYPRE_IJVectorGetObject, hjac->b->ij, (void **)&jbv);
452   PetscCallExternal(HYPRE_IJVectorGetObject, hjac->x->ij, (void **)&jxv);
453   PetscStackCallExternalVoid(
454     "Hypre solve", do {
455       HYPRE_Int hierr = (*jac->solve)(jac->hsolver, hmat, jbv, jxv);
456       if (hierr) {
457         PetscCheck(hierr == HYPRE_ERROR_CONV, PETSC_COMM_SELF, PETSC_ERR_LIB, "Error in HYPRE solver, error code %d", (int)hierr);
458         HYPRE_ClearAllErrors();
459       }
460     } while (0));
461 
462   if (jac->setup == HYPRE_AMSSetup && jac->ams_beta_is_zero_part) PetscCallExternal(HYPRE_AMSProjectOutGradients, jac->hsolver, jxv);
463   PetscCall(VecHYPRE_IJVectorPopVec(hjac->x));
464   PetscCall(VecHYPRE_IJVectorPopVec(hjac->b));
465   PetscFunctionReturn(PETSC_SUCCESS);
466 }
467 
468 static PetscErrorCode PCMatApply_HYPRE_BoomerAMG(PC pc, Mat B, Mat X)
469 {
470   PC_HYPRE           *jac  = (PC_HYPRE *)pc->data;
471   Mat_HYPRE          *hjac = (Mat_HYPRE *)(jac->hpmat->data);
472   hypre_ParCSRMatrix *par_matrix;
473   HYPRE_ParVector     hb, hx;
474   const PetscScalar  *b;
475   PetscScalar        *x;
476   PetscInt            m, N, lda;
477   hypre_Vector       *x_local;
478   PetscMemType        type;
479 
480   PetscFunctionBegin;
481   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
482   PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&par_matrix);
483   PetscCall(MatGetLocalSize(B, &m, NULL));
484   PetscCall(MatGetSize(B, NULL, &N));
485   PetscCallExternal(HYPRE_ParMultiVectorCreate, hypre_ParCSRMatrixComm(par_matrix), hypre_ParCSRMatrixGlobalNumRows(par_matrix), hypre_ParCSRMatrixRowStarts(par_matrix), N, &hb);
486   PetscCallExternal(HYPRE_ParMultiVectorCreate, hypre_ParCSRMatrixComm(par_matrix), hypre_ParCSRMatrixGlobalNumRows(par_matrix), hypre_ParCSRMatrixRowStarts(par_matrix), N, &hx);
487   PetscCall(MatZeroEntries(X));
488   PetscCall(MatDenseGetArrayReadAndMemType(B, &b, &type));
489   PetscCall(MatDenseGetLDA(B, &lda));
490   PetscCheck(lda == m, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot use a LDA different than the number of local rows: % " PetscInt_FMT " != % " PetscInt_FMT, lda, m);
491   PetscCall(MatDenseGetLDA(X, &lda));
492   PetscCheck(lda == m, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot use a LDA different than the number of local rows: % " PetscInt_FMT " != % " PetscInt_FMT, lda, m);
493   x_local = hypre_ParVectorLocalVector(hb);
494   PetscCallExternal(hypre_SeqVectorSetDataOwner, x_local, 0);
495   hypre_VectorData(x_local) = (HYPRE_Complex *)b;
496   PetscCall(MatDenseGetArrayWriteAndMemType(X, &x, NULL));
497   x_local = hypre_ParVectorLocalVector(hx);
498   PetscCallExternal(hypre_SeqVectorSetDataOwner, x_local, 0);
499   hypre_VectorData(x_local) = (HYPRE_Complex *)x;
500   PetscCallExternal(hypre_ParVectorInitialize_v2, hb, type == PETSC_MEMTYPE_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE);
501   PetscCallExternal(hypre_ParVectorInitialize_v2, hx, type == PETSC_MEMTYPE_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE);
502   PetscStackCallExternalVoid(
503     "Hypre solve", do {
504       HYPRE_Int hierr = (*jac->solve)(jac->hsolver, par_matrix, hb, hx);
505       if (hierr) {
506         PetscCheck(hierr == HYPRE_ERROR_CONV, PETSC_COMM_SELF, PETSC_ERR_LIB, "Error in HYPRE solver, error code %d", (int)hierr);
507         HYPRE_ClearAllErrors();
508       }
509     } while (0));
510   PetscCallExternal(HYPRE_ParVectorDestroy, hb);
511   PetscCallExternal(HYPRE_ParVectorDestroy, hx);
512   PetscCall(MatDenseRestoreArrayReadAndMemType(B, &b));
513   PetscCall(MatDenseRestoreArrayWriteAndMemType(X, &x));
514   PetscFunctionReturn(PETSC_SUCCESS);
515 }
516 
517 static PetscErrorCode PCReset_HYPRE(PC pc)
518 {
519   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
520 
521   PetscFunctionBegin;
522   PetscCall(MatDestroy(&jac->hpmat));
523   PetscCall(MatDestroy(&jac->G));
524   PetscCall(MatDestroy(&jac->C));
525   PetscCall(MatDestroy(&jac->alpha_Poisson));
526   PetscCall(MatDestroy(&jac->beta_Poisson));
527   PetscCall(MatDestroy(&jac->RT_PiFull));
528   PetscCall(MatDestroy(&jac->RT_Pi[0]));
529   PetscCall(MatDestroy(&jac->RT_Pi[1]));
530   PetscCall(MatDestroy(&jac->RT_Pi[2]));
531   PetscCall(MatDestroy(&jac->ND_PiFull));
532   PetscCall(MatDestroy(&jac->ND_Pi[0]));
533   PetscCall(MatDestroy(&jac->ND_Pi[1]));
534   PetscCall(MatDestroy(&jac->ND_Pi[2]));
535   PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[0]));
536   PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[1]));
537   PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[2]));
538   PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[0]));
539   PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[1]));
540   PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[2]));
541   PetscCall(VecHYPRE_IJVectorDestroy(&jac->interior));
542   PetscCall(PCHYPREResetNearNullSpace_Private(pc));
543   jac->ams_beta_is_zero      = PETSC_FALSE;
544   jac->ams_beta_is_zero_part = PETSC_FALSE;
545   jac->dim                   = 0;
546   PetscFunctionReturn(PETSC_SUCCESS);
547 }
548 
549 static PetscErrorCode PCDestroy_HYPRE(PC pc)
550 {
551   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
552 
553   PetscFunctionBegin;
554   PetscCall(PCReset_HYPRE(pc));
555   if (jac->destroy) PetscCallExternal(jac->destroy, jac->hsolver);
556   PetscCall(PetscFree(jac->hypre_type));
557 #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0)
558   PetscCall(PetscFree(jac->spgemm_type));
559 #endif
560   if (jac->comm_hypre != MPI_COMM_NULL) PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre));
561   PetscCall(PetscFree(pc->data));
562 
563   PetscCall(PetscObjectChangeTypeName((PetscObject)pc, 0));
564   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetType_C", NULL));
565   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREGetType_C", NULL));
566   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteGradient_C", NULL));
567   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteCurl_C", NULL));
568   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetInterpolations_C", NULL));
569   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetConstantEdgeVectors_C", NULL));
570   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetPoissonMatrix_C", NULL));
571   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetEdgeConstantVectors_C", NULL));
572   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREAMSSetInteriorNodes_C", NULL));
573   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetInterpolations_C", NULL));
574   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetCoarseOperators_C", NULL));
575   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinSetMatProductAlgorithm_C", NULL));
576   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinGetMatProductAlgorithm_C", NULL));
577   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", NULL));
578   PetscFunctionReturn(PETSC_SUCCESS);
579 }
580 
581 static PetscErrorCode PCSetFromOptions_HYPRE_Pilut(PC pc, PetscOptionItems *PetscOptionsObject)
582 {
583   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
584   PetscBool flag;
585 
586   PetscFunctionBegin;
587   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE Pilut Options");
588   PetscCall(PetscOptionsInt("-pc_hypre_pilut_maxiter", "Number of iterations", "None", jac->maxiter, &jac->maxiter, &flag));
589   if (flag) PetscCallExternal(HYPRE_ParCSRPilutSetMaxIter, jac->hsolver, jac->maxiter);
590   PetscCall(PetscOptionsReal("-pc_hypre_pilut_tol", "Drop tolerance", "None", jac->tol, &jac->tol, &flag));
591   if (flag) PetscCallExternal(HYPRE_ParCSRPilutSetDropTolerance, jac->hsolver, jac->tol);
592   PetscCall(PetscOptionsInt("-pc_hypre_pilut_factorrowsize", "FactorRowSize", "None", jac->factorrowsize, &jac->factorrowsize, &flag));
593   if (flag) PetscCallExternal(HYPRE_ParCSRPilutSetFactorRowSize, jac->hsolver, jac->factorrowsize);
594   PetscOptionsHeadEnd();
595   PetscFunctionReturn(PETSC_SUCCESS);
596 }
597 
598 static PetscErrorCode PCView_HYPRE_Pilut(PC pc, PetscViewer viewer)
599 {
600   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
601   PetscBool iascii;
602 
603   PetscFunctionBegin;
604   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
605   if (iascii) {
606     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE Pilut preconditioning\n"));
607     if (jac->maxiter != PETSC_DEFAULT) {
608       PetscCall(PetscViewerASCIIPrintf(viewer, "    maximum number of iterations %" PetscInt_FMT "\n", jac->maxiter));
609     } else {
610       PetscCall(PetscViewerASCIIPrintf(viewer, "    default maximum number of iterations \n"));
611     }
612     if (jac->tol != PETSC_DEFAULT) {
613       PetscCall(PetscViewerASCIIPrintf(viewer, "    drop tolerance %g\n", (double)jac->tol));
614     } else {
615       PetscCall(PetscViewerASCIIPrintf(viewer, "    default drop tolerance \n"));
616     }
617     if (jac->factorrowsize != PETSC_DEFAULT) {
618       PetscCall(PetscViewerASCIIPrintf(viewer, "    factor row size %" PetscInt_FMT "\n", jac->factorrowsize));
619     } else {
620       PetscCall(PetscViewerASCIIPrintf(viewer, "    default factor row size \n"));
621     }
622   }
623   PetscFunctionReturn(PETSC_SUCCESS);
624 }
625 
626 static PetscErrorCode PCSetFromOptions_HYPRE_Euclid(PC pc, PetscOptionItems *PetscOptionsObject)
627 {
628   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
629   PetscBool flag, eu_bj = jac->eu_bj ? PETSC_TRUE : PETSC_FALSE;
630 
631   PetscFunctionBegin;
632   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE Euclid Options");
633   PetscCall(PetscOptionsInt("-pc_hypre_euclid_level", "Factorization levels", "None", jac->eu_level, &jac->eu_level, &flag));
634   if (flag) PetscCallExternal(HYPRE_EuclidSetLevel, jac->hsolver, jac->eu_level);
635 
636   PetscCall(PetscOptionsReal("-pc_hypre_euclid_droptolerance", "Drop tolerance for ILU(k) in Euclid", "None", jac->eu_droptolerance, &jac->eu_droptolerance, &flag));
637   if (flag) {
638     PetscMPIInt size;
639 
640     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size));
641     PetscCheck(size == 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "hypre's Euclid does not support a parallel drop tolerance");
642     PetscCallExternal(HYPRE_EuclidSetILUT, jac->hsolver, jac->eu_droptolerance);
643   }
644 
645   PetscCall(PetscOptionsBool("-pc_hypre_euclid_bj", "Use Block Jacobi for ILU in Euclid", "None", eu_bj, &eu_bj, &flag));
646   if (flag) {
647     jac->eu_bj = eu_bj ? 1 : 0;
648     PetscCallExternal(HYPRE_EuclidSetBJ, jac->hsolver, jac->eu_bj);
649   }
650   PetscOptionsHeadEnd();
651   PetscFunctionReturn(PETSC_SUCCESS);
652 }
653 
654 static PetscErrorCode PCView_HYPRE_Euclid(PC pc, PetscViewer viewer)
655 {
656   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
657   PetscBool iascii;
658 
659   PetscFunctionBegin;
660   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
661   if (iascii) {
662     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE Euclid preconditioning\n"));
663     if (jac->eu_level != PETSC_DEFAULT) {
664       PetscCall(PetscViewerASCIIPrintf(viewer, "    factorization levels %" PetscInt_FMT "\n", jac->eu_level));
665     } else {
666       PetscCall(PetscViewerASCIIPrintf(viewer, "    default factorization levels \n"));
667     }
668     PetscCall(PetscViewerASCIIPrintf(viewer, "    drop tolerance %g\n", (double)jac->eu_droptolerance));
669     PetscCall(PetscViewerASCIIPrintf(viewer, "    use Block-Jacobi? %" PetscInt_FMT "\n", jac->eu_bj));
670   }
671   PetscFunctionReturn(PETSC_SUCCESS);
672 }
673 
674 static PetscErrorCode PCApplyTranspose_HYPRE_BoomerAMG(PC pc, Vec b, Vec x)
675 {
676   PC_HYPRE          *jac  = (PC_HYPRE *)pc->data;
677   Mat_HYPRE         *hjac = (Mat_HYPRE *)(jac->hpmat->data);
678   HYPRE_ParCSRMatrix hmat;
679   HYPRE_ParVector    jbv, jxv;
680 
681   PetscFunctionBegin;
682   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
683   PetscCall(VecSet(x, 0.0));
684   PetscCall(VecHYPRE_IJVectorPushVecRead(hjac->x, b));
685   PetscCall(VecHYPRE_IJVectorPushVecWrite(hjac->b, x));
686 
687   PetscCallExternal(HYPRE_IJMatrixGetObject, hjac->ij, (void **)&hmat);
688   PetscCallExternal(HYPRE_IJVectorGetObject, hjac->b->ij, (void **)&jbv);
689   PetscCallExternal(HYPRE_IJVectorGetObject, hjac->x->ij, (void **)&jxv);
690 
691   PetscStackCallExternalVoid(
692     "Hypre Transpose solve", do {
693       HYPRE_Int hierr = HYPRE_BoomerAMGSolveT(jac->hsolver, hmat, jbv, jxv);
694       if (hierr) {
695         /* error code of 1 in BoomerAMG merely means convergence not achieved */
696         PetscCheck(hierr == 1, PETSC_COMM_SELF, PETSC_ERR_LIB, "Error in HYPRE solver, error code %d", (int)hierr);
697         HYPRE_ClearAllErrors();
698       }
699     } while (0));
700 
701   PetscCall(VecHYPRE_IJVectorPopVec(hjac->x));
702   PetscCall(VecHYPRE_IJVectorPopVec(hjac->b));
703   PetscFunctionReturn(PETSC_SUCCESS);
704 }
705 
706 static PetscErrorCode PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG(PC pc, const char name[])
707 {
708   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
709   PetscBool flag;
710 
711 #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0)
712   PetscFunctionBegin;
713   if (jac->spgemm_type) {
714     PetscCall(PetscStrcmp(jac->spgemm_type, name, &flag));
715     PetscCheck(flag, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Cannot reset the HYPRE SpGEMM (really we can)");
716     PetscFunctionReturn(PETSC_SUCCESS);
717   } else {
718     PetscCall(PetscStrallocpy(name, &jac->spgemm_type));
719   }
720   PetscCall(PetscStrcmp("cusparse", jac->spgemm_type, &flag));
721   if (flag) {
722     PetscCallExternal(HYPRE_SetSpGemmUseCusparse, 1);
723     PetscFunctionReturn(PETSC_SUCCESS);
724   }
725   PetscCall(PetscStrcmp("hypre", jac->spgemm_type, &flag));
726   if (flag) {
727     PetscCallExternal(HYPRE_SetSpGemmUseCusparse, 0);
728     PetscFunctionReturn(PETSC_SUCCESS);
729   }
730   jac->spgemm_type = NULL;
731   SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown HYPRE SpGEMM type %s; Choices are cusparse, hypre", name);
732 #endif
733 }
734 
735 static PetscErrorCode PCMGGalerkinGetMatProductAlgorithm_HYPRE_BoomerAMG(PC pc, const char *spgemm[])
736 {
737   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
738 
739   PetscFunctionBegin;
740   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
741 #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0)
742   *spgemm = jac->spgemm_type;
743 #endif
744   PetscFunctionReturn(PETSC_SUCCESS);
745 }
746 
747 static const char *HYPREBoomerAMGCycleType[]   = {"", "V", "W"};
748 static const char *HYPREBoomerAMGCoarsenType[] = {"CLJP", "Ruge-Stueben", "", "modifiedRuge-Stueben", "", "", "Falgout", "", "PMIS", "", "HMIS"};
749 static const char *HYPREBoomerAMGMeasureType[] = {"local", "global"};
750 /* The following corresponds to HYPRE_BoomerAMGSetRelaxType which has many missing numbers in the enum */
751 static const char *HYPREBoomerAMGSmoothType[] = {"Schwarz-smoothers", "Pilut", "ParaSails", "Euclid"};
752 static const char *HYPREBoomerAMGRelaxType[] = {"Jacobi", "sequential-Gauss-Seidel", "seqboundary-Gauss-Seidel", "SOR/Jacobi", "backward-SOR/Jacobi", "" /* [5] hybrid chaotic Gauss-Seidel (works only with OpenMP) */, "symmetric-SOR/Jacobi", "" /* 7 */, "l1scaled-SOR/Jacobi", "Gaussian-elimination", "" /* 10 */, "" /* 11 */, "" /* 12 */, "l1-Gauss-Seidel" /* nonsymmetric */, "backward-l1-Gauss-Seidel" /* nonsymmetric */, "CG" /* non-stationary */, "Chebyshev", "FCF-Jacobi", "l1scaled-Jacobi"};
753 static const char    *HYPREBoomerAMGInterpType[] = {"classical", "", "", "direct", "multipass", "multipass-wts", "ext+i", "ext+i-cc", "standard", "standard-wts", "block", "block-wtd", "FF", "FF1", "ext", "ad-wts", "ext-mm", "ext+i-mm", "ext+e-mm"};
754 static PetscErrorCode PCSetFromOptions_HYPRE_BoomerAMG(PC pc, PetscOptionItems *PetscOptionsObject)
755 {
756   PC_HYPRE   *jac = (PC_HYPRE *)pc->data;
757   PetscInt    bs, n, indx, level;
758   PetscBool   flg, tmp_truth;
759   double      tmpdbl, twodbl[2];
760   const char *symtlist[]           = {"nonsymmetric", "SPD", "nonsymmetric,SPD"};
761   const char *PCHYPRESpgemmTypes[] = {"cusparse", "hypre"};
762 
763   PetscFunctionBegin;
764   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE BoomerAMG Options");
765   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_cycle_type", "Cycle type", "None", HYPREBoomerAMGCycleType + 1, 2, HYPREBoomerAMGCycleType[jac->cycletype], &indx, &flg));
766   if (flg) {
767     jac->cycletype = indx + 1;
768     PetscCallExternal(HYPRE_BoomerAMGSetCycleType, jac->hsolver, jac->cycletype);
769   }
770   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_max_levels", "Number of levels (of grids) allowed", "None", jac->maxlevels, &jac->maxlevels, &flg));
771   if (flg) {
772     PetscCheck(jac->maxlevels >= 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Number of levels %" PetscInt_FMT " must be at least two", jac->maxlevels);
773     PetscCallExternal(HYPRE_BoomerAMGSetMaxLevels, jac->hsolver, jac->maxlevels);
774   }
775   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_max_iter", "Maximum iterations used PER hypre call", "None", jac->maxiter, &jac->maxiter, &flg));
776   if (flg) {
777     PetscCheck(jac->maxiter >= 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Number of iterations %" PetscInt_FMT " must be at least one", jac->maxiter);
778     PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, jac->maxiter);
779   }
780   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_tol", "Convergence tolerance PER hypre call (0.0 = use a fixed number of iterations)", "None", jac->tol, &jac->tol, &flg));
781   if (flg) {
782     PetscCheck(jac->tol >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Tolerance %g must be greater than or equal to zero", (double)jac->tol);
783     PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, jac->tol);
784   }
785   bs = 1;
786   if (pc->pmat) PetscCall(MatGetBlockSize(pc->pmat, &bs));
787   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_numfunctions", "Number of functions", "HYPRE_BoomerAMGSetNumFunctions", bs, &bs, &flg));
788   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetNumFunctions, jac->hsolver, bs);
789 
790   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_truncfactor", "Truncation factor for interpolation (0=no truncation)", "None", jac->truncfactor, &jac->truncfactor, &flg));
791   if (flg) {
792     PetscCheck(jac->truncfactor >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Truncation factor %g must be great than or equal zero", (double)jac->truncfactor);
793     PetscCallExternal(HYPRE_BoomerAMGSetTruncFactor, jac->hsolver, jac->truncfactor);
794   }
795 
796   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_P_max", "Max elements per row for interpolation operator (0=unlimited)", "None", jac->pmax, &jac->pmax, &flg));
797   if (flg) {
798     PetscCheck(jac->pmax >= 0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "P_max %" PetscInt_FMT " must be greater than or equal to zero", jac->pmax);
799     PetscCallExternal(HYPRE_BoomerAMGSetPMaxElmts, jac->hsolver, jac->pmax);
800   }
801 
802   PetscCall(PetscOptionsRangeInt("-pc_hypre_boomeramg_agg_nl", "Number of levels of aggressive coarsening", "None", jac->agg_nl, &jac->agg_nl, &flg, 0, jac->maxlevels));
803   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetAggNumLevels, jac->hsolver, jac->agg_nl);
804 
805   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_agg_num_paths", "Number of paths for aggressive coarsening", "None", jac->agg_num_paths, &jac->agg_num_paths, &flg));
806   if (flg) {
807     PetscCheck(jac->agg_num_paths >= 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Number of paths %" PetscInt_FMT " must be greater than or equal to 1", jac->agg_num_paths);
808     PetscCallExternal(HYPRE_BoomerAMGSetNumPaths, jac->hsolver, jac->agg_num_paths);
809   }
810 
811   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_strong_threshold", "Threshold for being strongly connected", "None", jac->strongthreshold, &jac->strongthreshold, &flg));
812   if (flg) {
813     PetscCheck(jac->strongthreshold >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Strong threshold %g must be great than or equal zero", (double)jac->strongthreshold);
814     PetscCallExternal(HYPRE_BoomerAMGSetStrongThreshold, jac->hsolver, jac->strongthreshold);
815   }
816   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_max_row_sum", "Maximum row sum", "None", jac->maxrowsum, &jac->maxrowsum, &flg));
817   if (flg) {
818     PetscCheck(jac->maxrowsum >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Maximum row sum %g must be greater than zero", (double)jac->maxrowsum);
819     PetscCheck(jac->maxrowsum <= 1.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Maximum row sum %g must be less than or equal one", (double)jac->maxrowsum);
820     PetscCallExternal(HYPRE_BoomerAMGSetMaxRowSum, jac->hsolver, jac->maxrowsum);
821   }
822 
823   /* Grid sweeps */
824   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_all", "Number of sweeps for the up and down grid levels", "None", jac->gridsweeps[0], &indx, &flg));
825   if (flg) {
826     PetscCallExternal(HYPRE_BoomerAMGSetNumSweeps, jac->hsolver, indx);
827     /* modify the jac structure so we can view the updated options with PC_View */
828     jac->gridsweeps[0] = indx;
829     jac->gridsweeps[1] = indx;
830     /*defaults coarse to 1 */
831     jac->gridsweeps[2] = 1;
832   }
833   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_nodal_coarsen", "Use a nodal based coarsening 1-6", "HYPRE_BoomerAMGSetNodal", jac->nodal_coarsening, &jac->nodal_coarsening, &flg));
834   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetNodal, jac->hsolver, jac->nodal_coarsening);
835   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_nodal_coarsen_diag", "Diagonal in strength matrix for nodal based coarsening 0-2", "HYPRE_BoomerAMGSetNodalDiag", jac->nodal_coarsening_diag, &jac->nodal_coarsening_diag, &flg));
836   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetNodalDiag, jac->hsolver, jac->nodal_coarsening_diag);
837   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_vec_interp_variant", "Variant of algorithm 1-3", "HYPRE_BoomerAMGSetInterpVecVariant", jac->vec_interp_variant, &jac->vec_interp_variant, &flg));
838   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetInterpVecVariant, jac->hsolver, jac->vec_interp_variant);
839   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_vec_interp_qmax", "Max elements per row for each Q", "HYPRE_BoomerAMGSetInterpVecQMax", jac->vec_interp_qmax, &jac->vec_interp_qmax, &flg));
840   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetInterpVecQMax, jac->hsolver, jac->vec_interp_qmax);
841   PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_vec_interp_smooth", "Whether to smooth the interpolation vectors", "HYPRE_BoomerAMGSetSmoothInterpVectors", jac->vec_interp_smooth, &jac->vec_interp_smooth, &flg));
842   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetSmoothInterpVectors, jac->hsolver, jac->vec_interp_smooth);
843   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_interp_refine", "Preprocess the interpolation matrix through iterative weight refinement", "HYPRE_BoomerAMGSetInterpRefine", jac->interp_refine, &jac->interp_refine, &flg));
844   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetInterpRefine, jac->hsolver, jac->interp_refine);
845   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_down", "Number of sweeps for the down cycles", "None", jac->gridsweeps[0], &indx, &flg));
846   if (flg) {
847     PetscCallExternal(HYPRE_BoomerAMGSetCycleNumSweeps, jac->hsolver, indx, 1);
848     jac->gridsweeps[0] = indx;
849   }
850   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_up", "Number of sweeps for the up cycles", "None", jac->gridsweeps[1], &indx, &flg));
851   if (flg) {
852     PetscCallExternal(HYPRE_BoomerAMGSetCycleNumSweeps, jac->hsolver, indx, 2);
853     jac->gridsweeps[1] = indx;
854   }
855   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_grid_sweeps_coarse", "Number of sweeps for the coarse level", "None", jac->gridsweeps[2], &indx, &flg));
856   if (flg) {
857     PetscCallExternal(HYPRE_BoomerAMGSetCycleNumSweeps, jac->hsolver, indx, 3);
858     jac->gridsweeps[2] = indx;
859   }
860 
861   /* Smooth type */
862   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_smooth_type", "Enable more complex smoothers", "None", HYPREBoomerAMGSmoothType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGSmoothType), HYPREBoomerAMGSmoothType[0], &indx, &flg));
863   if (flg) {
864     jac->smoothtype = indx;
865     PetscCallExternal(HYPRE_BoomerAMGSetSmoothType, jac->hsolver, indx + 6);
866     jac->smoothnumlevels = 25;
867     PetscCallExternal(HYPRE_BoomerAMGSetSmoothNumLevels, jac->hsolver, 25);
868   }
869 
870   /* Number of smoothing levels */
871   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_smooth_num_levels", "Number of levels on which more complex smoothers are used", "None", 25, &indx, &flg));
872   if (flg && (jac->smoothtype != -1)) {
873     jac->smoothnumlevels = indx;
874     PetscCallExternal(HYPRE_BoomerAMGSetSmoothNumLevels, jac->hsolver, indx);
875   }
876 
877   /* Number of levels for ILU(k) for Euclid */
878   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_eu_level", "Number of levels for ILU(k) in Euclid smoother", "None", 0, &indx, &flg));
879   if (flg && (jac->smoothtype == 3)) {
880     jac->eu_level = indx;
881     PetscCallExternal(HYPRE_BoomerAMGSetEuLevel, jac->hsolver, indx);
882   }
883 
884   /* Filter for ILU(k) for Euclid */
885   double droptolerance;
886   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_eu_droptolerance", "Drop tolerance for ILU(k) in Euclid smoother", "None", 0, &droptolerance, &flg));
887   if (flg && (jac->smoothtype == 3)) {
888     jac->eu_droptolerance = droptolerance;
889     PetscCallExternal(HYPRE_BoomerAMGSetEuLevel, jac->hsolver, droptolerance);
890   }
891 
892   /* Use Block Jacobi ILUT for Euclid */
893   PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_eu_bj", "Use Block Jacobi for ILU in Euclid smoother?", "None", PETSC_FALSE, &tmp_truth, &flg));
894   if (flg && (jac->smoothtype == 3)) {
895     jac->eu_bj = tmp_truth;
896     PetscCallExternal(HYPRE_BoomerAMGSetEuBJ, jac->hsolver, jac->eu_bj);
897   }
898 
899   /* Relax type */
900   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_all", "Relax type for the up and down cycles", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[6], &indx, &flg));
901   if (flg) {
902     jac->relaxtype[0] = jac->relaxtype[1] = indx;
903     PetscCallExternal(HYPRE_BoomerAMGSetRelaxType, jac->hsolver, indx);
904     /* by default, coarse type set to 9 */
905     jac->relaxtype[2] = 9;
906     PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, 9, 3);
907   }
908   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_down", "Relax type for the down cycles", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[6], &indx, &flg));
909   if (flg) {
910     jac->relaxtype[0] = indx;
911     PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, indx, 1);
912   }
913   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_up", "Relax type for the up cycles", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[6], &indx, &flg));
914   if (flg) {
915     jac->relaxtype[1] = indx;
916     PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, indx, 2);
917   }
918   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_relax_type_coarse", "Relax type on coarse grid", "None", HYPREBoomerAMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGRelaxType), HYPREBoomerAMGRelaxType[9], &indx, &flg));
919   if (flg) {
920     jac->relaxtype[2] = indx;
921     PetscCallExternal(HYPRE_BoomerAMGSetCycleRelaxType, jac->hsolver, indx, 3);
922   }
923 
924   /* Relaxation Weight */
925   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_relax_weight_all", "Relaxation weight for all levels (0 = hypre estimates, -k = determined with k CG steps)", "None", jac->relaxweight, &tmpdbl, &flg));
926   if (flg) {
927     PetscCallExternal(HYPRE_BoomerAMGSetRelaxWt, jac->hsolver, tmpdbl);
928     jac->relaxweight = tmpdbl;
929   }
930 
931   n         = 2;
932   twodbl[0] = twodbl[1] = 1.0;
933   PetscCall(PetscOptionsRealArray("-pc_hypre_boomeramg_relax_weight_level", "Set the relaxation weight for a particular level (weight,level)", "None", twodbl, &n, &flg));
934   if (flg) {
935     PetscCheck(n == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Relax weight level: you must provide 2 values separated by a comma (and no space), you provided %" PetscInt_FMT, n);
936     indx = (int)PetscAbsReal(twodbl[1]);
937     PetscCallExternal(HYPRE_BoomerAMGSetLevelRelaxWt, jac->hsolver, twodbl[0], indx);
938   }
939 
940   /* Outer relaxation Weight */
941   PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_outer_relax_weight_all", "Outer relaxation weight for all levels (-k = determined with k CG steps)", "None", jac->outerrelaxweight, &tmpdbl, &flg));
942   if (flg) {
943     PetscCallExternal(HYPRE_BoomerAMGSetOuterWt, jac->hsolver, tmpdbl);
944     jac->outerrelaxweight = tmpdbl;
945   }
946 
947   n         = 2;
948   twodbl[0] = twodbl[1] = 1.0;
949   PetscCall(PetscOptionsRealArray("-pc_hypre_boomeramg_outer_relax_weight_level", "Set the outer relaxation weight for a particular level (weight,level)", "None", twodbl, &n, &flg));
950   if (flg) {
951     PetscCheck(n == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Relax weight outer level: You must provide 2 values separated by a comma (and no space), you provided %" PetscInt_FMT, n);
952     indx = (int)PetscAbsReal(twodbl[1]);
953     PetscCallExternal(HYPRE_BoomerAMGSetLevelOuterWt, jac->hsolver, twodbl[0], indx);
954   }
955 
956   /* the Relax Order */
957   PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_no_CF", "Do not use CF-relaxation", "None", PETSC_FALSE, &tmp_truth, &flg));
958 
959   if (flg && tmp_truth) {
960     jac->relaxorder = 0;
961     PetscCallExternal(HYPRE_BoomerAMGSetRelaxOrder, jac->hsolver, jac->relaxorder);
962   }
963   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_measure_type", "Measure type", "None", HYPREBoomerAMGMeasureType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGMeasureType), HYPREBoomerAMGMeasureType[0], &indx, &flg));
964   if (flg) {
965     jac->measuretype = indx;
966     PetscCallExternal(HYPRE_BoomerAMGSetMeasureType, jac->hsolver, jac->measuretype);
967   }
968   /* update list length 3/07 */
969   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_coarsen_type", "Coarsen type", "None", HYPREBoomerAMGCoarsenType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGCoarsenType), HYPREBoomerAMGCoarsenType[6], &indx, &flg));
970   if (flg) {
971     jac->coarsentype = indx;
972     PetscCallExternal(HYPRE_BoomerAMGSetCoarsenType, jac->hsolver, jac->coarsentype);
973   }
974 
975   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_max_coarse_size", "Maximum size of coarsest grid", "None", jac->maxc, &jac->maxc, &flg));
976   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetMaxCoarseSize, jac->hsolver, jac->maxc);
977   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_min_coarse_size", "Minimum size of coarsest grid", "None", jac->minc, &jac->minc, &flg));
978   if (flg) PetscCallExternal(HYPRE_BoomerAMGSetMinCoarseSize, jac->hsolver, jac->minc);
979 #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0)
980   // global parameter but is closely associated with BoomerAMG
981   PetscCall(PetscOptionsEList("-pc_mg_galerkin_mat_product_algorithm", "Type of SpGEMM to use in hypre (only for now)", "PCMGGalerkinSetMatProductAlgorithm", PCHYPRESpgemmTypes, PETSC_STATIC_ARRAY_LENGTH(PCHYPRESpgemmTypes), PCHYPRESpgemmTypes[0], &indx, &flg));
982   #if defined(PETSC_HAVE_HYPRE_DEVICE)
983   if (!flg) indx = 0;
984   PetscCall(PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG(pc, PCHYPRESpgemmTypes[indx]));
985   #else
986   PetscCall(PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG(pc, "hypre"));
987   #endif
988 #endif
989   /* AIR */
990 #if PETSC_PKG_HYPRE_VERSION_GE(2, 18, 0)
991   PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_restriction_type", "Type of AIR method (distance 1 or 2, 0 means no AIR)", "None", jac->Rtype, &jac->Rtype, NULL));
992   PetscCallExternal(HYPRE_BoomerAMGSetRestriction, jac->hsolver, jac->Rtype);
993   if (jac->Rtype) {
994     jac->interptype = 100; /* no way we can pass this with strings... Set it as default as in MFEM, then users can still customize it back to a different one */
995 
996     PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_strongthresholdR", "Threshold for R", "None", jac->Rstrongthreshold, &jac->Rstrongthreshold, NULL));
997     PetscCallExternal(HYPRE_BoomerAMGSetStrongThresholdR, jac->hsolver, jac->Rstrongthreshold);
998 
999     PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_filterthresholdR", "Filter threshold for R", "None", jac->Rfilterthreshold, &jac->Rfilterthreshold, NULL));
1000     PetscCallExternal(HYPRE_BoomerAMGSetFilterThresholdR, jac->hsolver, jac->Rfilterthreshold);
1001 
1002     PetscCall(PetscOptionsReal("-pc_hypre_boomeramg_Adroptol", "Defines the drop tolerance for the A-matrices from the 2nd level of AMG", "None", jac->Adroptol, &jac->Adroptol, NULL));
1003     PetscCallExternal(HYPRE_BoomerAMGSetADropTol, jac->hsolver, jac->Adroptol);
1004 
1005     PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_Adroptype", "Drops the entries that are not on the diagonal and smaller than its row norm: type 1: 1-norm, 2: 2-norm, -1: infinity norm", "None", jac->Adroptype, &jac->Adroptype, NULL));
1006     PetscCallExternal(HYPRE_BoomerAMGSetADropType, jac->hsolver, jac->Adroptype);
1007   }
1008 #endif
1009 
1010 #if PETSC_PKG_HYPRE_VERSION_LE(9, 9, 9)
1011   PetscCheck(!jac->Rtype || !jac->agg_nl, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "-pc_hypre_boomeramg_restriction_type (%" PetscInt_FMT ") and -pc_hypre_boomeramg_agg_nl (%" PetscInt_FMT ")", jac->Rtype, jac->agg_nl);
1012 #endif
1013 
1014   /* new 3/07 */
1015   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_interp_type", "Interpolation type", "None", HYPREBoomerAMGInterpType, PETSC_STATIC_ARRAY_LENGTH(HYPREBoomerAMGInterpType), HYPREBoomerAMGInterpType[0], &indx, &flg));
1016   if (flg || jac->Rtype) {
1017     if (flg) jac->interptype = indx;
1018     PetscCallExternal(HYPRE_BoomerAMGSetInterpType, jac->hsolver, jac->interptype);
1019   }
1020 
1021   PetscCall(PetscOptionsName("-pc_hypre_boomeramg_print_statistics", "Print statistics", "None", &flg));
1022   if (flg) {
1023     level = 3;
1024     PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_print_statistics", "Print statistics", "None", level, &level, NULL));
1025 
1026     jac->printstatistics = PETSC_TRUE;
1027     PetscCallExternal(HYPRE_BoomerAMGSetPrintLevel, jac->hsolver, level);
1028   }
1029 
1030   PetscCall(PetscOptionsName("-pc_hypre_boomeramg_print_debug", "Print debug information", "None", &flg));
1031   if (flg) {
1032     level = 3;
1033     PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_print_debug", "Print debug information", "None", level, &level, NULL));
1034 
1035     jac->printstatistics = PETSC_TRUE;
1036     PetscCallExternal(HYPRE_BoomerAMGSetDebugFlag, jac->hsolver, level);
1037   }
1038 
1039   PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_nodal_relaxation", "Nodal relaxation via Schwarz", "None", PETSC_FALSE, &tmp_truth, &flg));
1040   if (flg && tmp_truth) {
1041     PetscInt tmp_int;
1042     PetscCall(PetscOptionsInt("-pc_hypre_boomeramg_nodal_relaxation", "Nodal relaxation via Schwarz", "None", jac->nodal_relax_levels, &tmp_int, &flg));
1043     if (flg) jac->nodal_relax_levels = tmp_int;
1044     PetscCallExternal(HYPRE_BoomerAMGSetSmoothType, jac->hsolver, 6);
1045     PetscCallExternal(HYPRE_BoomerAMGSetDomainType, jac->hsolver, 1);
1046     PetscCallExternal(HYPRE_BoomerAMGSetOverlap, jac->hsolver, 0);
1047     PetscCallExternal(HYPRE_BoomerAMGSetSmoothNumLevels, jac->hsolver, jac->nodal_relax_levels);
1048   }
1049 
1050   PetscCall(PetscOptionsBool("-pc_hypre_boomeramg_keeptranspose", "Avoid transpose matvecs in preconditioner application", "None", jac->keeptranspose, &jac->keeptranspose, NULL));
1051   PetscCallExternal(HYPRE_BoomerAMGSetKeepTranspose, jac->hsolver, jac->keeptranspose ? 1 : 0);
1052 
1053   /* options for ParaSails solvers */
1054   PetscCall(PetscOptionsEList("-pc_hypre_boomeramg_parasails_sym", "Symmetry of matrix and preconditioner", "None", symtlist, PETSC_STATIC_ARRAY_LENGTH(symtlist), symtlist[0], &indx, &flg));
1055   if (flg) {
1056     jac->symt = indx;
1057     PetscCallExternal(HYPRE_BoomerAMGSetSym, jac->hsolver, jac->symt);
1058   }
1059 
1060   PetscOptionsHeadEnd();
1061   PetscFunctionReturn(PETSC_SUCCESS);
1062 }
1063 
1064 static PetscErrorCode PCApplyRichardson_HYPRE_BoomerAMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason)
1065 {
1066   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1067   HYPRE_Int oits;
1068 
1069   PetscFunctionBegin;
1070   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
1071   PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, its * jac->maxiter);
1072   PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, rtol);
1073   jac->applyrichardson = PETSC_TRUE;
1074   PetscCall(PCApply_HYPRE(pc, b, y));
1075   jac->applyrichardson = PETSC_FALSE;
1076   PetscCallExternal(HYPRE_BoomerAMGGetNumIterations, jac->hsolver, &oits);
1077   *outits = oits;
1078   if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS;
1079   else *reason = PCRICHARDSON_CONVERGED_RTOL;
1080   PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, jac->tol);
1081   PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, jac->maxiter);
1082   PetscFunctionReturn(PETSC_SUCCESS);
1083 }
1084 
1085 static PetscErrorCode PCView_HYPRE_BoomerAMG(PC pc, PetscViewer viewer)
1086 {
1087   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1088   PetscBool iascii;
1089 
1090   PetscFunctionBegin;
1091   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
1092   if (iascii) {
1093     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE BoomerAMG preconditioning\n"));
1094     PetscCall(PetscViewerASCIIPrintf(viewer, "    Cycle type %s\n", HYPREBoomerAMGCycleType[jac->cycletype]));
1095     PetscCall(PetscViewerASCIIPrintf(viewer, "    Maximum number of levels %" PetscInt_FMT "\n", jac->maxlevels));
1096     PetscCall(PetscViewerASCIIPrintf(viewer, "    Maximum number of iterations PER hypre call %" PetscInt_FMT "\n", jac->maxiter));
1097     PetscCall(PetscViewerASCIIPrintf(viewer, "    Convergence tolerance PER hypre call %g\n", (double)jac->tol));
1098     PetscCall(PetscViewerASCIIPrintf(viewer, "    Threshold for strong coupling %g\n", (double)jac->strongthreshold));
1099     PetscCall(PetscViewerASCIIPrintf(viewer, "    Interpolation truncation factor %g\n", (double)jac->truncfactor));
1100     PetscCall(PetscViewerASCIIPrintf(viewer, "    Interpolation: max elements per row %" PetscInt_FMT "\n", jac->pmax));
1101     if (jac->interp_refine) PetscCall(PetscViewerASCIIPrintf(viewer, "    Interpolation: number of steps of weighted refinement %" PetscInt_FMT "\n", jac->interp_refine));
1102     PetscCall(PetscViewerASCIIPrintf(viewer, "    Number of levels of aggressive coarsening %" PetscInt_FMT "\n", jac->agg_nl));
1103     PetscCall(PetscViewerASCIIPrintf(viewer, "    Number of paths for aggressive coarsening %" PetscInt_FMT "\n", jac->agg_num_paths));
1104 
1105     PetscCall(PetscViewerASCIIPrintf(viewer, "    Maximum row sums %g\n", (double)jac->maxrowsum));
1106 
1107     PetscCall(PetscViewerASCIIPrintf(viewer, "    Sweeps down         %" PetscInt_FMT "\n", jac->gridsweeps[0]));
1108     PetscCall(PetscViewerASCIIPrintf(viewer, "    Sweeps up           %" PetscInt_FMT "\n", jac->gridsweeps[1]));
1109     PetscCall(PetscViewerASCIIPrintf(viewer, "    Sweeps on coarse    %" PetscInt_FMT "\n", jac->gridsweeps[2]));
1110 
1111     PetscCall(PetscViewerASCIIPrintf(viewer, "    Relax down          %s\n", HYPREBoomerAMGRelaxType[jac->relaxtype[0]]));
1112     PetscCall(PetscViewerASCIIPrintf(viewer, "    Relax up            %s\n", HYPREBoomerAMGRelaxType[jac->relaxtype[1]]));
1113     PetscCall(PetscViewerASCIIPrintf(viewer, "    Relax on coarse     %s\n", HYPREBoomerAMGRelaxType[jac->relaxtype[2]]));
1114 
1115     PetscCall(PetscViewerASCIIPrintf(viewer, "    Relax weight  (all)      %g\n", (double)jac->relaxweight));
1116     PetscCall(PetscViewerASCIIPrintf(viewer, "    Outer relax weight (all) %g\n", (double)jac->outerrelaxweight));
1117 
1118     if (jac->relaxorder) {
1119       PetscCall(PetscViewerASCIIPrintf(viewer, "    Using CF-relaxation\n"));
1120     } else {
1121       PetscCall(PetscViewerASCIIPrintf(viewer, "    Not using CF-relaxation\n"));
1122     }
1123     if (jac->smoothtype != -1) {
1124       PetscCall(PetscViewerASCIIPrintf(viewer, "    Smooth type          %s\n", HYPREBoomerAMGSmoothType[jac->smoothtype]));
1125       PetscCall(PetscViewerASCIIPrintf(viewer, "    Smooth num levels    %" PetscInt_FMT "\n", jac->smoothnumlevels));
1126     } else {
1127       PetscCall(PetscViewerASCIIPrintf(viewer, "    Not using more complex smoothers.\n"));
1128     }
1129     if (jac->smoothtype == 3) {
1130       PetscCall(PetscViewerASCIIPrintf(viewer, "    Euclid ILU(k) levels %" PetscInt_FMT "\n", jac->eu_level));
1131       PetscCall(PetscViewerASCIIPrintf(viewer, "    Euclid ILU(k) drop tolerance %g\n", (double)jac->eu_droptolerance));
1132       PetscCall(PetscViewerASCIIPrintf(viewer, "    Euclid ILU use Block-Jacobi? %" PetscInt_FMT "\n", jac->eu_bj));
1133     }
1134     PetscCall(PetscViewerASCIIPrintf(viewer, "    Measure type        %s\n", HYPREBoomerAMGMeasureType[jac->measuretype]));
1135     PetscCall(PetscViewerASCIIPrintf(viewer, "    Coarsen type        %s\n", HYPREBoomerAMGCoarsenType[jac->coarsentype]));
1136     PetscCall(PetscViewerASCIIPrintf(viewer, "    Interpolation type  %s\n", jac->interptype != 100 ? HYPREBoomerAMGInterpType[jac->interptype] : "1pt"));
1137     if (jac->nodal_coarsening) PetscCall(PetscViewerASCIIPrintf(viewer, "    Using nodal coarsening with HYPRE_BOOMERAMGSetNodal() %" PetscInt_FMT "\n", jac->nodal_coarsening));
1138     if (jac->vec_interp_variant) {
1139       PetscCall(PetscViewerASCIIPrintf(viewer, "    HYPRE_BoomerAMGSetInterpVecVariant() %" PetscInt_FMT "\n", jac->vec_interp_variant));
1140       PetscCall(PetscViewerASCIIPrintf(viewer, "    HYPRE_BoomerAMGSetInterpVecQMax() %" PetscInt_FMT "\n", jac->vec_interp_qmax));
1141       PetscCall(PetscViewerASCIIPrintf(viewer, "    HYPRE_BoomerAMGSetSmoothInterpVectors() %d\n", jac->vec_interp_smooth));
1142     }
1143     if (jac->nodal_relax) PetscCall(PetscViewerASCIIPrintf(viewer, "    Using nodal relaxation via Schwarz smoothing on levels %" PetscInt_FMT "\n", jac->nodal_relax_levels));
1144 #if PETSC_PKG_HYPRE_VERSION_GE(2, 23, 0)
1145     PetscCall(PetscViewerASCIIPrintf(viewer, "    SpGEMM type         %s\n", jac->spgemm_type));
1146 #else
1147     PetscCall(PetscViewerASCIIPrintf(viewer, "    SpGEMM type         %s\n", "hypre"));
1148 #endif
1149     /* AIR */
1150     if (jac->Rtype) {
1151       PetscCall(PetscViewerASCIIPrintf(viewer, "    Using approximate ideal restriction type %" PetscInt_FMT "\n", jac->Rtype));
1152       PetscCall(PetscViewerASCIIPrintf(viewer, "      Threshold for R %g\n", (double)jac->Rstrongthreshold));
1153       PetscCall(PetscViewerASCIIPrintf(viewer, "      Filter for R %g\n", (double)jac->Rfilterthreshold));
1154       PetscCall(PetscViewerASCIIPrintf(viewer, "      A drop tolerance %g\n", (double)jac->Adroptol));
1155       PetscCall(PetscViewerASCIIPrintf(viewer, "      A drop type %" PetscInt_FMT "\n", jac->Adroptype));
1156     }
1157   }
1158   PetscFunctionReturn(PETSC_SUCCESS);
1159 }
1160 
1161 static PetscErrorCode PCSetFromOptions_HYPRE_ParaSails(PC pc, PetscOptionItems *PetscOptionsObject)
1162 {
1163   PC_HYPRE   *jac = (PC_HYPRE *)pc->data;
1164   PetscInt    indx;
1165   PetscBool   flag;
1166   const char *symtlist[] = {"nonsymmetric", "SPD", "nonsymmetric,SPD"};
1167 
1168   PetscFunctionBegin;
1169   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE ParaSails Options");
1170   PetscCall(PetscOptionsInt("-pc_hypre_parasails_nlevels", "Number of number of levels", "None", jac->nlevels, &jac->nlevels, 0));
1171   PetscCall(PetscOptionsReal("-pc_hypre_parasails_thresh", "Threshold", "None", jac->threshold, &jac->threshold, &flag));
1172   if (flag) PetscCallExternal(HYPRE_ParaSailsSetParams, jac->hsolver, jac->threshold, jac->nlevels);
1173 
1174   PetscCall(PetscOptionsReal("-pc_hypre_parasails_filter", "filter", "None", jac->filter, &jac->filter, &flag));
1175   if (flag) PetscCallExternal(HYPRE_ParaSailsSetFilter, jac->hsolver, jac->filter);
1176 
1177   PetscCall(PetscOptionsReal("-pc_hypre_parasails_loadbal", "Load balance", "None", jac->loadbal, &jac->loadbal, &flag));
1178   if (flag) PetscCallExternal(HYPRE_ParaSailsSetLoadbal, jac->hsolver, jac->loadbal);
1179 
1180   PetscCall(PetscOptionsBool("-pc_hypre_parasails_logging", "Print info to screen", "None", (PetscBool)jac->logging, (PetscBool *)&jac->logging, &flag));
1181   if (flag) PetscCallExternal(HYPRE_ParaSailsSetLogging, jac->hsolver, jac->logging);
1182 
1183   PetscCall(PetscOptionsBool("-pc_hypre_parasails_reuse", "Reuse nonzero pattern in preconditioner", "None", (PetscBool)jac->ruse, (PetscBool *)&jac->ruse, &flag));
1184   if (flag) PetscCallExternal(HYPRE_ParaSailsSetReuse, jac->hsolver, jac->ruse);
1185 
1186   PetscCall(PetscOptionsEList("-pc_hypre_parasails_sym", "Symmetry of matrix and preconditioner", "None", symtlist, PETSC_STATIC_ARRAY_LENGTH(symtlist), symtlist[0], &indx, &flag));
1187   if (flag) {
1188     jac->symt = indx;
1189     PetscCallExternal(HYPRE_ParaSailsSetSym, jac->hsolver, jac->symt);
1190   }
1191 
1192   PetscOptionsHeadEnd();
1193   PetscFunctionReturn(PETSC_SUCCESS);
1194 }
1195 
1196 static PetscErrorCode PCView_HYPRE_ParaSails(PC pc, PetscViewer viewer)
1197 {
1198   PC_HYPRE   *jac = (PC_HYPRE *)pc->data;
1199   PetscBool   iascii;
1200   const char *symt = 0;
1201 
1202   PetscFunctionBegin;
1203   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
1204   if (iascii) {
1205     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE ParaSails preconditioning\n"));
1206     PetscCall(PetscViewerASCIIPrintf(viewer, "    nlevels %" PetscInt_FMT "\n", jac->nlevels));
1207     PetscCall(PetscViewerASCIIPrintf(viewer, "    threshold %g\n", (double)jac->threshold));
1208     PetscCall(PetscViewerASCIIPrintf(viewer, "    filter %g\n", (double)jac->filter));
1209     PetscCall(PetscViewerASCIIPrintf(viewer, "    load balance %g\n", (double)jac->loadbal));
1210     PetscCall(PetscViewerASCIIPrintf(viewer, "    reuse nonzero structure %s\n", PetscBools[jac->ruse]));
1211     PetscCall(PetscViewerASCIIPrintf(viewer, "    print info to screen %s\n", PetscBools[jac->logging]));
1212     if (!jac->symt) symt = "nonsymmetric matrix and preconditioner";
1213     else if (jac->symt == 1) symt = "SPD matrix and preconditioner";
1214     else if (jac->symt == 2) symt = "nonsymmetric matrix but SPD preconditioner";
1215     else SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "Unknown HYPRE ParaSails symmetric option %" PetscInt_FMT, jac->symt);
1216     PetscCall(PetscViewerASCIIPrintf(viewer, "    %s\n", symt));
1217   }
1218   PetscFunctionReturn(PETSC_SUCCESS);
1219 }
1220 
1221 static PetscErrorCode PCSetFromOptions_HYPRE_AMS(PC pc, PetscOptionItems *PetscOptionsObject)
1222 {
1223   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1224   PetscInt  n;
1225   PetscBool flag, flag2, flag3, flag4;
1226 
1227   PetscFunctionBegin;
1228   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE AMS Options");
1229   PetscCall(PetscOptionsInt("-pc_hypre_ams_print_level", "Debugging output level for AMS", "None", jac->as_print, &jac->as_print, &flag));
1230   if (flag) PetscCallExternal(HYPRE_AMSSetPrintLevel, jac->hsolver, jac->as_print);
1231   PetscCall(PetscOptionsInt("-pc_hypre_ams_max_iter", "Maximum number of AMS multigrid iterations within PCApply", "None", jac->as_max_iter, &jac->as_max_iter, &flag));
1232   if (flag) PetscCallExternal(HYPRE_AMSSetMaxIter, jac->hsolver, jac->as_max_iter);
1233   PetscCall(PetscOptionsInt("-pc_hypre_ams_cycle_type", "Cycle type for AMS multigrid", "None", jac->ams_cycle_type, &jac->ams_cycle_type, &flag));
1234   if (flag) PetscCallExternal(HYPRE_AMSSetCycleType, jac->hsolver, jac->ams_cycle_type);
1235   PetscCall(PetscOptionsReal("-pc_hypre_ams_tol", "Error tolerance for AMS multigrid", "None", jac->as_tol, &jac->as_tol, &flag));
1236   if (flag) PetscCallExternal(HYPRE_AMSSetTol, jac->hsolver, jac->as_tol);
1237   PetscCall(PetscOptionsInt("-pc_hypre_ams_relax_type", "Relaxation type for AMS smoother", "None", jac->as_relax_type, &jac->as_relax_type, &flag));
1238   PetscCall(PetscOptionsInt("-pc_hypre_ams_relax_times", "Number of relaxation steps for AMS smoother", "None", jac->as_relax_times, &jac->as_relax_times, &flag2));
1239   PetscCall(PetscOptionsReal("-pc_hypre_ams_relax_weight", "Relaxation weight for AMS smoother", "None", jac->as_relax_weight, &jac->as_relax_weight, &flag3));
1240   PetscCall(PetscOptionsReal("-pc_hypre_ams_omega", "SSOR coefficient for AMS smoother", "None", jac->as_omega, &jac->as_omega, &flag4));
1241   if (flag || flag2 || flag3 || flag4) PetscCallExternal(HYPRE_AMSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega);
1242   PetscCall(PetscOptionsReal("-pc_hypre_ams_amg_alpha_theta", "Threshold for strong coupling of vector Poisson AMG solver", "None", jac->as_amg_alpha_theta, &jac->as_amg_alpha_theta, &flag));
1243   n = 5;
1244   PetscCall(PetscOptionsIntArray("-pc_hypre_ams_amg_alpha_options", "AMG options for vector Poisson", "None", jac->as_amg_alpha_opts, &n, &flag2));
1245   if (flag || flag2) {
1246     PetscCallExternal(HYPRE_AMSSetAlphaAMGOptions, jac->hsolver, jac->as_amg_alpha_opts[0], /* AMG coarsen type */
1247                       jac->as_amg_alpha_opts[1],                                            /* AMG agg_levels */
1248                       jac->as_amg_alpha_opts[2],                                            /* AMG relax_type */
1249                       jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3],                   /* AMG interp_type */
1250                       jac->as_amg_alpha_opts[4]);                                           /* AMG Pmax */
1251   }
1252   PetscCall(PetscOptionsReal("-pc_hypre_ams_amg_beta_theta", "Threshold for strong coupling of scalar Poisson AMG solver", "None", jac->as_amg_beta_theta, &jac->as_amg_beta_theta, &flag));
1253   n = 5;
1254   PetscCall(PetscOptionsIntArray("-pc_hypre_ams_amg_beta_options", "AMG options for scalar Poisson solver", "None", jac->as_amg_beta_opts, &n, &flag2));
1255   if (flag || flag2) {
1256     PetscCallExternal(HYPRE_AMSSetBetaAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */
1257                       jac->as_amg_beta_opts[1],                                           /* AMG agg_levels */
1258                       jac->as_amg_beta_opts[2],                                           /* AMG relax_type */
1259                       jac->as_amg_beta_theta, jac->as_amg_beta_opts[3],                   /* AMG interp_type */
1260                       jac->as_amg_beta_opts[4]);                                          /* AMG Pmax */
1261   }
1262   PetscCall(PetscOptionsInt("-pc_hypre_ams_projection_frequency", "Frequency at which a projection onto the compatible subspace for problems with zero conductivity regions is performed", "None", jac->ams_proj_freq, &jac->ams_proj_freq, &flag));
1263   if (flag) { /* override HYPRE's default only if the options is used */
1264     PetscCallExternal(HYPRE_AMSSetProjectionFrequency, jac->hsolver, jac->ams_proj_freq);
1265   }
1266   PetscOptionsHeadEnd();
1267   PetscFunctionReturn(PETSC_SUCCESS);
1268 }
1269 
1270 static PetscErrorCode PCView_HYPRE_AMS(PC pc, PetscViewer viewer)
1271 {
1272   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1273   PetscBool iascii;
1274 
1275   PetscFunctionBegin;
1276   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
1277   if (iascii) {
1278     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE AMS preconditioning\n"));
1279     PetscCall(PetscViewerASCIIPrintf(viewer, "    subspace iterations per application %" PetscInt_FMT "\n", jac->as_max_iter));
1280     PetscCall(PetscViewerASCIIPrintf(viewer, "    subspace cycle type %" PetscInt_FMT "\n", jac->ams_cycle_type));
1281     PetscCall(PetscViewerASCIIPrintf(viewer, "    subspace iteration tolerance %g\n", (double)jac->as_tol));
1282     PetscCall(PetscViewerASCIIPrintf(viewer, "    smoother type %" PetscInt_FMT "\n", jac->as_relax_type));
1283     PetscCall(PetscViewerASCIIPrintf(viewer, "    number of smoothing steps %" PetscInt_FMT "\n", jac->as_relax_times));
1284     PetscCall(PetscViewerASCIIPrintf(viewer, "    smoother weight %g\n", (double)jac->as_relax_weight));
1285     PetscCall(PetscViewerASCIIPrintf(viewer, "    smoother omega %g\n", (double)jac->as_omega));
1286     if (jac->alpha_Poisson) {
1287       PetscCall(PetscViewerASCIIPrintf(viewer, "    vector Poisson solver (passed in by user)\n"));
1288     } else {
1289       PetscCall(PetscViewerASCIIPrintf(viewer, "    vector Poisson solver (computed) \n"));
1290     }
1291     PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG coarsening type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[0]));
1292     PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[1]));
1293     PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG relaxation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[2]));
1294     PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG interpolation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[3]));
1295     PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[4]));
1296     PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG strength threshold %g\n", (double)jac->as_amg_alpha_theta));
1297     if (!jac->ams_beta_is_zero) {
1298       if (jac->beta_Poisson) {
1299         PetscCall(PetscViewerASCIIPrintf(viewer, "    scalar Poisson solver (passed in by user)\n"));
1300       } else {
1301         PetscCall(PetscViewerASCIIPrintf(viewer, "    scalar Poisson solver (computed) \n"));
1302       }
1303       PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG coarsening type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[0]));
1304       PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_beta_opts[1]));
1305       PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG relaxation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[2]));
1306       PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG interpolation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[3]));
1307       PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_beta_opts[4]));
1308       PetscCall(PetscViewerASCIIPrintf(viewer, "        boomerAMG strength threshold %g\n", (double)jac->as_amg_beta_theta));
1309       if (jac->ams_beta_is_zero_part) PetscCall(PetscViewerASCIIPrintf(viewer, "        compatible subspace projection frequency %" PetscInt_FMT " (-1 HYPRE uses default)\n", jac->ams_proj_freq));
1310     } else {
1311       PetscCall(PetscViewerASCIIPrintf(viewer, "    scalar Poisson solver not used (zero-conductivity everywhere) \n"));
1312     }
1313   }
1314   PetscFunctionReturn(PETSC_SUCCESS);
1315 }
1316 
1317 static PetscErrorCode PCSetFromOptions_HYPRE_ADS(PC pc, PetscOptionItems *PetscOptionsObject)
1318 {
1319   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1320   PetscInt  n;
1321   PetscBool flag, flag2, flag3, flag4;
1322 
1323   PetscFunctionBegin;
1324   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE ADS Options");
1325   PetscCall(PetscOptionsInt("-pc_hypre_ads_print_level", "Debugging output level for ADS", "None", jac->as_print, &jac->as_print, &flag));
1326   if (flag) PetscCallExternal(HYPRE_ADSSetPrintLevel, jac->hsolver, jac->as_print);
1327   PetscCall(PetscOptionsInt("-pc_hypre_ads_max_iter", "Maximum number of ADS multigrid iterations within PCApply", "None", jac->as_max_iter, &jac->as_max_iter, &flag));
1328   if (flag) PetscCallExternal(HYPRE_ADSSetMaxIter, jac->hsolver, jac->as_max_iter);
1329   PetscCall(PetscOptionsInt("-pc_hypre_ads_cycle_type", "Cycle type for ADS multigrid", "None", jac->ads_cycle_type, &jac->ads_cycle_type, &flag));
1330   if (flag) PetscCallExternal(HYPRE_ADSSetCycleType, jac->hsolver, jac->ads_cycle_type);
1331   PetscCall(PetscOptionsReal("-pc_hypre_ads_tol", "Error tolerance for ADS multigrid", "None", jac->as_tol, &jac->as_tol, &flag));
1332   if (flag) PetscCallExternal(HYPRE_ADSSetTol, jac->hsolver, jac->as_tol);
1333   PetscCall(PetscOptionsInt("-pc_hypre_ads_relax_type", "Relaxation type for ADS smoother", "None", jac->as_relax_type, &jac->as_relax_type, &flag));
1334   PetscCall(PetscOptionsInt("-pc_hypre_ads_relax_times", "Number of relaxation steps for ADS smoother", "None", jac->as_relax_times, &jac->as_relax_times, &flag2));
1335   PetscCall(PetscOptionsReal("-pc_hypre_ads_relax_weight", "Relaxation weight for ADS smoother", "None", jac->as_relax_weight, &jac->as_relax_weight, &flag3));
1336   PetscCall(PetscOptionsReal("-pc_hypre_ads_omega", "SSOR coefficient for ADS smoother", "None", jac->as_omega, &jac->as_omega, &flag4));
1337   if (flag || flag2 || flag3 || flag4) PetscCallExternal(HYPRE_ADSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega);
1338   PetscCall(PetscOptionsReal("-pc_hypre_ads_ams_theta", "Threshold for strong coupling of AMS solver inside ADS", "None", jac->as_amg_alpha_theta, &jac->as_amg_alpha_theta, &flag));
1339   n = 5;
1340   PetscCall(PetscOptionsIntArray("-pc_hypre_ads_ams_options", "AMG options for AMS solver inside ADS", "None", jac->as_amg_alpha_opts, &n, &flag2));
1341   PetscCall(PetscOptionsInt("-pc_hypre_ads_ams_cycle_type", "Cycle type for AMS solver inside ADS", "None", jac->ams_cycle_type, &jac->ams_cycle_type, &flag3));
1342   if (flag || flag2 || flag3) {
1343     PetscCallExternal(HYPRE_ADSSetAMSOptions, jac->hsolver, jac->ams_cycle_type, /* AMS cycle type */
1344                       jac->as_amg_alpha_opts[0],                                 /* AMG coarsen type */
1345                       jac->as_amg_alpha_opts[1],                                 /* AMG agg_levels */
1346                       jac->as_amg_alpha_opts[2],                                 /* AMG relax_type */
1347                       jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3],        /* AMG interp_type */
1348                       jac->as_amg_alpha_opts[4]);                                /* AMG Pmax */
1349   }
1350   PetscCall(PetscOptionsReal("-pc_hypre_ads_amg_theta", "Threshold for strong coupling of vector AMG solver inside ADS", "None", jac->as_amg_beta_theta, &jac->as_amg_beta_theta, &flag));
1351   n = 5;
1352   PetscCall(PetscOptionsIntArray("-pc_hypre_ads_amg_options", "AMG options for vector AMG solver inside ADS", "None", jac->as_amg_beta_opts, &n, &flag2));
1353   if (flag || flag2) {
1354     PetscCallExternal(HYPRE_ADSSetAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */
1355                       jac->as_amg_beta_opts[1],                                       /* AMG agg_levels */
1356                       jac->as_amg_beta_opts[2],                                       /* AMG relax_type */
1357                       jac->as_amg_beta_theta, jac->as_amg_beta_opts[3],               /* AMG interp_type */
1358                       jac->as_amg_beta_opts[4]);                                      /* AMG Pmax */
1359   }
1360   PetscOptionsHeadEnd();
1361   PetscFunctionReturn(PETSC_SUCCESS);
1362 }
1363 
1364 static PetscErrorCode PCView_HYPRE_ADS(PC pc, PetscViewer viewer)
1365 {
1366   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1367   PetscBool iascii;
1368 
1369   PetscFunctionBegin;
1370   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
1371   if (iascii) {
1372     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE ADS preconditioning\n"));
1373     PetscCall(PetscViewerASCIIPrintf(viewer, "    subspace iterations per application %" PetscInt_FMT "\n", jac->as_max_iter));
1374     PetscCall(PetscViewerASCIIPrintf(viewer, "    subspace cycle type %" PetscInt_FMT "\n", jac->ads_cycle_type));
1375     PetscCall(PetscViewerASCIIPrintf(viewer, "    subspace iteration tolerance %g\n", (double)jac->as_tol));
1376     PetscCall(PetscViewerASCIIPrintf(viewer, "    smoother type %" PetscInt_FMT "\n", jac->as_relax_type));
1377     PetscCall(PetscViewerASCIIPrintf(viewer, "    number of smoothing steps %" PetscInt_FMT "\n", jac->as_relax_times));
1378     PetscCall(PetscViewerASCIIPrintf(viewer, "    smoother weight %g\n", (double)jac->as_relax_weight));
1379     PetscCall(PetscViewerASCIIPrintf(viewer, "    smoother omega %g\n", (double)jac->as_omega));
1380     PetscCall(PetscViewerASCIIPrintf(viewer, "    AMS solver using boomerAMG\n"));
1381     PetscCall(PetscViewerASCIIPrintf(viewer, "        subspace cycle type %" PetscInt_FMT "\n", jac->ams_cycle_type));
1382     PetscCall(PetscViewerASCIIPrintf(viewer, "        coarsening type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[0]));
1383     PetscCall(PetscViewerASCIIPrintf(viewer, "        levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[1]));
1384     PetscCall(PetscViewerASCIIPrintf(viewer, "        relaxation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[2]));
1385     PetscCall(PetscViewerASCIIPrintf(viewer, "        interpolation type %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[3]));
1386     PetscCall(PetscViewerASCIIPrintf(viewer, "        max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_alpha_opts[4]));
1387     PetscCall(PetscViewerASCIIPrintf(viewer, "        strength threshold %g\n", (double)jac->as_amg_alpha_theta));
1388     PetscCall(PetscViewerASCIIPrintf(viewer, "    vector Poisson solver using boomerAMG\n"));
1389     PetscCall(PetscViewerASCIIPrintf(viewer, "        coarsening type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[0]));
1390     PetscCall(PetscViewerASCIIPrintf(viewer, "        levels of aggressive coarsening %" PetscInt_FMT "\n", jac->as_amg_beta_opts[1]));
1391     PetscCall(PetscViewerASCIIPrintf(viewer, "        relaxation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[2]));
1392     PetscCall(PetscViewerASCIIPrintf(viewer, "        interpolation type %" PetscInt_FMT "\n", jac->as_amg_beta_opts[3]));
1393     PetscCall(PetscViewerASCIIPrintf(viewer, "        max nonzero elements in interpolation rows %" PetscInt_FMT "\n", jac->as_amg_beta_opts[4]));
1394     PetscCall(PetscViewerASCIIPrintf(viewer, "        strength threshold %g\n", (double)jac->as_amg_beta_theta));
1395   }
1396   PetscFunctionReturn(PETSC_SUCCESS);
1397 }
1398 
1399 static PetscErrorCode PCHYPRESetDiscreteGradient_HYPRE(PC pc, Mat G)
1400 {
1401   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1402   PetscBool ishypre;
1403 
1404   PetscFunctionBegin;
1405   PetscCall(PetscObjectTypeCompare((PetscObject)G, MATHYPRE, &ishypre));
1406   if (ishypre) {
1407     PetscCall(PetscObjectReference((PetscObject)G));
1408     PetscCall(MatDestroy(&jac->G));
1409     jac->G = G;
1410   } else {
1411     PetscCall(MatDestroy(&jac->G));
1412     PetscCall(MatConvert(G, MATHYPRE, MAT_INITIAL_MATRIX, &jac->G));
1413   }
1414   PetscFunctionReturn(PETSC_SUCCESS);
1415 }
1416 
1417 /*@
1418    PCHYPRESetDiscreteGradient - Set discrete gradient matrix for `PCHYPRE` type of ams or ads
1419 
1420    Collective
1421 
1422    Input Parameters:
1423 +  pc - the preconditioning context
1424 -  G - the discrete gradient
1425 
1426    Level: intermediate
1427 
1428    Notes:
1429     G should have as many rows as the number of edges and as many columns as the number of vertices in the mesh
1430 
1431     Each row of G has 2 nonzeros, with column indexes being the global indexes of edge's endpoints: matrix entries are +1 and -1 depending on edge orientation
1432 
1433    Developer Note:
1434    This automatically converts the matrix to `MATHYPRE` if it is not already of that type
1435 
1436 .seealso: `PCHYPRE`, `PCHYPRESetDiscreteCurl()`
1437 @*/
1438 PetscErrorCode PCHYPRESetDiscreteGradient(PC pc, Mat G)
1439 {
1440   PetscFunctionBegin;
1441   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1442   PetscValidHeaderSpecific(G, MAT_CLASSID, 2);
1443   PetscCheckSameComm(pc, 1, G, 2);
1444   PetscTryMethod(pc, "PCHYPRESetDiscreteGradient_C", (PC, Mat), (pc, G));
1445   PetscFunctionReturn(PETSC_SUCCESS);
1446 }
1447 
1448 static PetscErrorCode PCHYPRESetDiscreteCurl_HYPRE(PC pc, Mat C)
1449 {
1450   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1451   PetscBool ishypre;
1452 
1453   PetscFunctionBegin;
1454   PetscCall(PetscObjectTypeCompare((PetscObject)C, MATHYPRE, &ishypre));
1455   if (ishypre) {
1456     PetscCall(PetscObjectReference((PetscObject)C));
1457     PetscCall(MatDestroy(&jac->C));
1458     jac->C = C;
1459   } else {
1460     PetscCall(MatDestroy(&jac->C));
1461     PetscCall(MatConvert(C, MATHYPRE, MAT_INITIAL_MATRIX, &jac->C));
1462   }
1463   PetscFunctionReturn(PETSC_SUCCESS);
1464 }
1465 
1466 /*@
1467    PCHYPRESetDiscreteCurl - Set discrete curl matrx for `PCHYPRE` type of ads
1468 
1469    Collective
1470 
1471    Input Parameters:
1472 +  pc - the preconditioning context
1473 -  C - the discrete curl
1474 
1475    Level: intermediate
1476 
1477    Notes:
1478     C should have as many rows as the number of faces and as many columns as the number of edges in the mesh
1479 
1480     Each row of G has as many nonzeros as the number of edges of a face, with column indexes being the global indexes of the corresponding edge: matrix entries are +1 and -1 depending on edge orientation with respect to the face orientation
1481 
1482    Developer Note:
1483    This automatically converts the matrix to `MATHYPRE` if it is not already of that type
1484 
1485    If this is only for  `PCHYPRE` type of ads it should be called `PCHYPREADSSetDiscreteCurl()`
1486 
1487 .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`
1488 @*/
1489 PetscErrorCode PCHYPRESetDiscreteCurl(PC pc, Mat C)
1490 {
1491   PetscFunctionBegin;
1492   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1493   PetscValidHeaderSpecific(C, MAT_CLASSID, 2);
1494   PetscCheckSameComm(pc, 1, C, 2);
1495   PetscTryMethod(pc, "PCHYPRESetDiscreteCurl_C", (PC, Mat), (pc, C));
1496   PetscFunctionReturn(PETSC_SUCCESS);
1497 }
1498 
1499 static PetscErrorCode PCHYPRESetInterpolations_HYPRE(PC pc, PetscInt dim, Mat RT_PiFull, Mat RT_Pi[], Mat ND_PiFull, Mat ND_Pi[])
1500 {
1501   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1502   PetscBool ishypre;
1503   PetscInt  i;
1504   PetscFunctionBegin;
1505 
1506   PetscCall(MatDestroy(&jac->RT_PiFull));
1507   PetscCall(MatDestroy(&jac->ND_PiFull));
1508   for (i = 0; i < 3; ++i) {
1509     PetscCall(MatDestroy(&jac->RT_Pi[i]));
1510     PetscCall(MatDestroy(&jac->ND_Pi[i]));
1511   }
1512 
1513   jac->dim = dim;
1514   if (RT_PiFull) {
1515     PetscCall(PetscObjectTypeCompare((PetscObject)RT_PiFull, MATHYPRE, &ishypre));
1516     if (ishypre) {
1517       PetscCall(PetscObjectReference((PetscObject)RT_PiFull));
1518       jac->RT_PiFull = RT_PiFull;
1519     } else {
1520       PetscCall(MatConvert(RT_PiFull, MATHYPRE, MAT_INITIAL_MATRIX, &jac->RT_PiFull));
1521     }
1522   }
1523   if (RT_Pi) {
1524     for (i = 0; i < dim; ++i) {
1525       if (RT_Pi[i]) {
1526         PetscCall(PetscObjectTypeCompare((PetscObject)RT_Pi[i], MATHYPRE, &ishypre));
1527         if (ishypre) {
1528           PetscCall(PetscObjectReference((PetscObject)RT_Pi[i]));
1529           jac->RT_Pi[i] = RT_Pi[i];
1530         } else {
1531           PetscCall(MatConvert(RT_Pi[i], MATHYPRE, MAT_INITIAL_MATRIX, &jac->RT_Pi[i]));
1532         }
1533       }
1534     }
1535   }
1536   if (ND_PiFull) {
1537     PetscCall(PetscObjectTypeCompare((PetscObject)ND_PiFull, MATHYPRE, &ishypre));
1538     if (ishypre) {
1539       PetscCall(PetscObjectReference((PetscObject)ND_PiFull));
1540       jac->ND_PiFull = ND_PiFull;
1541     } else {
1542       PetscCall(MatConvert(ND_PiFull, MATHYPRE, MAT_INITIAL_MATRIX, &jac->ND_PiFull));
1543     }
1544   }
1545   if (ND_Pi) {
1546     for (i = 0; i < dim; ++i) {
1547       if (ND_Pi[i]) {
1548         PetscCall(PetscObjectTypeCompare((PetscObject)ND_Pi[i], MATHYPRE, &ishypre));
1549         if (ishypre) {
1550           PetscCall(PetscObjectReference((PetscObject)ND_Pi[i]));
1551           jac->ND_Pi[i] = ND_Pi[i];
1552         } else {
1553           PetscCall(MatConvert(ND_Pi[i], MATHYPRE, MAT_INITIAL_MATRIX, &jac->ND_Pi[i]));
1554         }
1555       }
1556     }
1557   }
1558 
1559   PetscFunctionReturn(PETSC_SUCCESS);
1560 }
1561 
1562 /*@
1563    PCHYPRESetInterpolations - Set interpolation matrices for `PCHYPRE` type of ams or ads
1564 
1565    Collective
1566 
1567    Input Parameters:
1568 +  pc - the preconditioning context
1569 .  dim - the dimension of the problem, only used in AMS
1570 .  RT_PiFull - Raviart-Thomas interpolation matrix
1571 .  RT_Pi - x/y/z component of Raviart-Thomas interpolation matrix
1572 .  ND_PiFull - Nedelec interpolation matrix
1573 -  ND_Pi - x/y/z component of Nedelec interpolation matrix
1574 
1575    Level: intermediate
1576 
1577    Notes:
1578     For AMS, only Nedelec interpolation matrices are needed, the Raviart-Thomas interpolation matrices can be set to NULL.
1579 
1580     For ADS, both type of interpolation matrices are needed.
1581 
1582    Developer Note:
1583    This automatically converts the matrix to `MATHYPRE` if it is not already of that type
1584 
1585 .seealso: `PCHYPRE`
1586 @*/
1587 PetscErrorCode PCHYPRESetInterpolations(PC pc, PetscInt dim, Mat RT_PiFull, Mat RT_Pi[], Mat ND_PiFull, Mat ND_Pi[])
1588 {
1589   PetscInt i;
1590 
1591   PetscFunctionBegin;
1592   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1593   if (RT_PiFull) {
1594     PetscValidHeaderSpecific(RT_PiFull, MAT_CLASSID, 3);
1595     PetscCheckSameComm(pc, 1, RT_PiFull, 3);
1596   }
1597   if (RT_Pi) {
1598     PetscValidPointer(RT_Pi, 4);
1599     for (i = 0; i < dim; ++i) {
1600       if (RT_Pi[i]) {
1601         PetscValidHeaderSpecific(RT_Pi[i], MAT_CLASSID, 4);
1602         PetscCheckSameComm(pc, 1, RT_Pi[i], 4);
1603       }
1604     }
1605   }
1606   if (ND_PiFull) {
1607     PetscValidHeaderSpecific(ND_PiFull, MAT_CLASSID, 5);
1608     PetscCheckSameComm(pc, 1, ND_PiFull, 5);
1609   }
1610   if (ND_Pi) {
1611     PetscValidPointer(ND_Pi, 6);
1612     for (i = 0; i < dim; ++i) {
1613       if (ND_Pi[i]) {
1614         PetscValidHeaderSpecific(ND_Pi[i], MAT_CLASSID, 6);
1615         PetscCheckSameComm(pc, 1, ND_Pi[i], 6);
1616       }
1617     }
1618   }
1619   PetscTryMethod(pc, "PCHYPRESetInterpolations_C", (PC, PetscInt, Mat, Mat[], Mat, Mat[]), (pc, dim, RT_PiFull, RT_Pi, ND_PiFull, ND_Pi));
1620   PetscFunctionReturn(PETSC_SUCCESS);
1621 }
1622 
1623 static PetscErrorCode PCHYPRESetPoissonMatrix_HYPRE(PC pc, Mat A, PetscBool isalpha)
1624 {
1625   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1626   PetscBool ishypre;
1627 
1628   PetscFunctionBegin;
1629   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATHYPRE, &ishypre));
1630   if (ishypre) {
1631     if (isalpha) {
1632       PetscCall(PetscObjectReference((PetscObject)A));
1633       PetscCall(MatDestroy(&jac->alpha_Poisson));
1634       jac->alpha_Poisson = A;
1635     } else {
1636       if (A) {
1637         PetscCall(PetscObjectReference((PetscObject)A));
1638       } else {
1639         jac->ams_beta_is_zero = PETSC_TRUE;
1640       }
1641       PetscCall(MatDestroy(&jac->beta_Poisson));
1642       jac->beta_Poisson = A;
1643     }
1644   } else {
1645     if (isalpha) {
1646       PetscCall(MatDestroy(&jac->alpha_Poisson));
1647       PetscCall(MatConvert(A, MATHYPRE, MAT_INITIAL_MATRIX, &jac->alpha_Poisson));
1648     } else {
1649       if (A) {
1650         PetscCall(MatDestroy(&jac->beta_Poisson));
1651         PetscCall(MatConvert(A, MATHYPRE, MAT_INITIAL_MATRIX, &jac->beta_Poisson));
1652       } else {
1653         PetscCall(MatDestroy(&jac->beta_Poisson));
1654         jac->ams_beta_is_zero = PETSC_TRUE;
1655       }
1656     }
1657   }
1658   PetscFunctionReturn(PETSC_SUCCESS);
1659 }
1660 
1661 /*@
1662    PCHYPRESetAlphaPoissonMatrix - Set vector Poisson matrix for `PCHYPRE` of type ams
1663 
1664    Collective
1665 
1666    Input Parameters:
1667 +  pc - the preconditioning context
1668 -  A - the matrix
1669 
1670    Level: intermediate
1671 
1672    Note:
1673     A should be obtained by discretizing the vector valued Poisson problem with linear finite elements
1674 
1675    Developer Note:
1676    This automatically converts the matrix to `MATHYPRE` if it is not already of that type
1677 
1678    If this is only for  `PCHYPRE` type of ams it should be called `PCHYPREAMSSetAlphaPoissonMatrix()`
1679 
1680 .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetBetaPoissonMatrix()`
1681 @*/
1682 PetscErrorCode PCHYPRESetAlphaPoissonMatrix(PC pc, Mat A)
1683 {
1684   PetscFunctionBegin;
1685   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1686   PetscValidHeaderSpecific(A, MAT_CLASSID, 2);
1687   PetscCheckSameComm(pc, 1, A, 2);
1688   PetscTryMethod(pc, "PCHYPRESetPoissonMatrix_C", (PC, Mat, PetscBool), (pc, A, PETSC_TRUE));
1689   PetscFunctionReturn(PETSC_SUCCESS);
1690 }
1691 
1692 /*@
1693    PCHYPRESetBetaPoissonMatrix - Set Poisson matrix for `PCHYPRE` of type ams
1694 
1695    Collective
1696 
1697    Input Parameters:
1698 +  pc - the preconditioning context
1699 -  A - the matrix, or NULL to turn it off
1700 
1701    Level: intermediate
1702 
1703    Note:
1704    A should be obtained by discretizing the Poisson problem with linear finite elements.
1705 
1706    Developer Note:
1707    This automatically converts the matrix to `MATHYPRE` if it is not already of that type
1708 
1709    If this is only for  `PCHYPRE` type of ams it should be called `PCHYPREAMSPCHYPRESetBetaPoissonMatrix()`
1710 
1711 .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetAlphaPoissonMatrix()`
1712 @*/
1713 PetscErrorCode PCHYPRESetBetaPoissonMatrix(PC pc, Mat A)
1714 {
1715   PetscFunctionBegin;
1716   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1717   if (A) {
1718     PetscValidHeaderSpecific(A, MAT_CLASSID, 2);
1719     PetscCheckSameComm(pc, 1, A, 2);
1720   }
1721   PetscTryMethod(pc, "PCHYPRESetPoissonMatrix_C", (PC, Mat, PetscBool), (pc, A, PETSC_FALSE));
1722   PetscFunctionReturn(PETSC_SUCCESS);
1723 }
1724 
1725 static PetscErrorCode PCHYPRESetEdgeConstantVectors_HYPRE(PC pc, Vec ozz, Vec zoz, Vec zzo)
1726 {
1727   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1728 
1729   PetscFunctionBegin;
1730   /* throw away any vector if already set */
1731   PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[0]));
1732   PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[1]));
1733   PetscCall(VecHYPRE_IJVectorDestroy(&jac->constants[2]));
1734   PetscCall(VecHYPRE_IJVectorCreate(ozz->map, &jac->constants[0]));
1735   PetscCall(VecHYPRE_IJVectorCopy(ozz, jac->constants[0]));
1736   PetscCall(VecHYPRE_IJVectorCreate(zoz->map, &jac->constants[1]));
1737   PetscCall(VecHYPRE_IJVectorCopy(zoz, jac->constants[1]));
1738   jac->dim = 2;
1739   if (zzo) {
1740     PetscCall(VecHYPRE_IJVectorCreate(zzo->map, &jac->constants[2]));
1741     PetscCall(VecHYPRE_IJVectorCopy(zzo, jac->constants[2]));
1742     jac->dim++;
1743   }
1744   PetscFunctionReturn(PETSC_SUCCESS);
1745 }
1746 
1747 /*@
1748    PCHYPRESetEdgeConstantVectors - Set the representation of the constant vector fields in the edge element basis for `PCHYPRE` of type ams
1749 
1750    Collective
1751 
1752    Input Parameters:
1753 +  pc - the preconditioning context
1754 .  ozz - vector representing (1,0,0) (or (1,0) in 2D)
1755 .  zoz - vector representing (0,1,0) (or (0,1) in 2D)
1756 -  zzo - vector representing (0,0,1) (use NULL in 2D)
1757 
1758    Level: intermediate
1759 
1760    Developer Note:
1761    If this is only for  `PCHYPRE` type of ams it should be called `PCHYPREAMSSetEdgeConstantVectors()`
1762 
1763 .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetAlphaPoissonMatrix()`
1764 @*/
1765 PetscErrorCode PCHYPRESetEdgeConstantVectors(PC pc, Vec ozz, Vec zoz, Vec zzo)
1766 {
1767   PetscFunctionBegin;
1768   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1769   PetscValidHeaderSpecific(ozz, VEC_CLASSID, 2);
1770   PetscValidHeaderSpecific(zoz, VEC_CLASSID, 3);
1771   if (zzo) PetscValidHeaderSpecific(zzo, VEC_CLASSID, 4);
1772   PetscCheckSameComm(pc, 1, ozz, 2);
1773   PetscCheckSameComm(pc, 1, zoz, 3);
1774   if (zzo) PetscCheckSameComm(pc, 1, zzo, 4);
1775   PetscTryMethod(pc, "PCHYPRESetEdgeConstantVectors_C", (PC, Vec, Vec, Vec), (pc, ozz, zoz, zzo));
1776   PetscFunctionReturn(PETSC_SUCCESS);
1777 }
1778 
1779 static PetscErrorCode PCHYPREAMSSetInteriorNodes_HYPRE(PC pc, Vec interior)
1780 {
1781   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1782 
1783   PetscFunctionBegin;
1784   PetscCall(VecHYPRE_IJVectorDestroy(&jac->interior));
1785   PetscCall(VecHYPRE_IJVectorCreate(interior->map, &jac->interior));
1786   PetscCall(VecHYPRE_IJVectorCopy(interior, jac->interior));
1787   jac->ams_beta_is_zero_part = PETSC_TRUE;
1788   PetscFunctionReturn(PETSC_SUCCESS);
1789 }
1790 
1791 /*@
1792   PCHYPREAMSSetInteriorNodes - Set the list of interior nodes to a zero-conductivity region for `PCHYPRE` of type ams
1793 
1794    Collective
1795 
1796    Input Parameters:
1797 +  pc - the preconditioning context
1798 -  interior - vector. node is interior if its entry in the array is 1.0.
1799 
1800    Level: intermediate
1801 
1802    Note:
1803    This calls `HYPRE_AMSSetInteriorNodes()`
1804 
1805    Developer Note:
1806    If this is only for  `PCHYPRE` type of ams it should be called `PCHYPREAMSSetInteriorNodes()`
1807 
1808 .seealso: `PCHYPRE`, `PCHYPRESetDiscreteGradient()`, `PCHYPRESetDiscreteCurl()`, `PCHYPRESetAlphaPoissonMatrix()`
1809 @*/
1810 PetscErrorCode PCHYPREAMSSetInteriorNodes(PC pc, Vec interior)
1811 {
1812   PetscFunctionBegin;
1813   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
1814   PetscValidHeaderSpecific(interior, VEC_CLASSID, 2);
1815   PetscCheckSameComm(pc, 1, interior, 2);
1816   PetscTryMethod(pc, "PCHYPREAMSSetInteriorNodes_C", (PC, Vec), (pc, interior));
1817   PetscFunctionReturn(PETSC_SUCCESS);
1818 }
1819 
1820 static PetscErrorCode PCSetCoordinates_HYPRE(PC pc, PetscInt dim, PetscInt nloc, PetscReal *coords)
1821 {
1822   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1823   Vec       tv;
1824   PetscInt  i;
1825 
1826   PetscFunctionBegin;
1827   /* throw away any coordinate vector if already set */
1828   PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[0]));
1829   PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[1]));
1830   PetscCall(VecHYPRE_IJVectorDestroy(&jac->coords[2]));
1831   jac->dim = dim;
1832 
1833   /* compute IJ vector for coordinates */
1834   PetscCall(VecCreate(PetscObjectComm((PetscObject)pc), &tv));
1835   PetscCall(VecSetType(tv, VECSTANDARD));
1836   PetscCall(VecSetSizes(tv, nloc, PETSC_DECIDE));
1837   for (i = 0; i < dim; i++) {
1838     PetscScalar *array;
1839     PetscInt     j;
1840 
1841     PetscCall(VecHYPRE_IJVectorCreate(tv->map, &jac->coords[i]));
1842     PetscCall(VecGetArrayWrite(tv, &array));
1843     for (j = 0; j < nloc; j++) array[j] = coords[j * dim + i];
1844     PetscCall(VecRestoreArrayWrite(tv, &array));
1845     PetscCall(VecHYPRE_IJVectorCopy(tv, jac->coords[i]));
1846   }
1847   PetscCall(VecDestroy(&tv));
1848   PetscFunctionReturn(PETSC_SUCCESS);
1849 }
1850 
1851 static PetscErrorCode PCHYPREGetType_HYPRE(PC pc, const char *name[])
1852 {
1853   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1854 
1855   PetscFunctionBegin;
1856   *name = jac->hypre_type;
1857   PetscFunctionReturn(PETSC_SUCCESS);
1858 }
1859 
1860 static PetscErrorCode PCHYPRESetType_HYPRE(PC pc, const char name[])
1861 {
1862   PC_HYPRE *jac = (PC_HYPRE *)pc->data;
1863   PetscBool flag;
1864 
1865   PetscFunctionBegin;
1866   if (jac->hypre_type) {
1867     PetscCall(PetscStrcmp(jac->hypre_type, name, &flag));
1868     PetscCheck(flag, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Cannot reset the HYPRE preconditioner type once it has been set");
1869     PetscFunctionReturn(PETSC_SUCCESS);
1870   } else {
1871     PetscCall(PetscStrallocpy(name, &jac->hypre_type));
1872   }
1873 
1874   jac->maxiter         = PETSC_DEFAULT;
1875   jac->tol             = PETSC_DEFAULT;
1876   jac->printstatistics = PetscLogPrintInfo;
1877 
1878   PetscCall(PetscStrcmp("pilut", jac->hypre_type, &flag));
1879   if (flag) {
1880     PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre));
1881     PetscCallExternal(HYPRE_ParCSRPilutCreate, jac->comm_hypre, &jac->hsolver);
1882     pc->ops->setfromoptions = PCSetFromOptions_HYPRE_Pilut;
1883     pc->ops->view           = PCView_HYPRE_Pilut;
1884     jac->destroy            = HYPRE_ParCSRPilutDestroy;
1885     jac->setup              = HYPRE_ParCSRPilutSetup;
1886     jac->solve              = HYPRE_ParCSRPilutSolve;
1887     jac->factorrowsize      = PETSC_DEFAULT;
1888     PetscFunctionReturn(PETSC_SUCCESS);
1889   }
1890   PetscCall(PetscStrcmp("euclid", jac->hypre_type, &flag));
1891   if (flag) {
1892 #if defined(PETSC_USE_64BIT_INDICES)
1893     SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Hypre Euclid does not support 64-bit indices");
1894 #endif
1895     PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre));
1896     PetscCallExternal(HYPRE_EuclidCreate, jac->comm_hypre, &jac->hsolver);
1897     pc->ops->setfromoptions = PCSetFromOptions_HYPRE_Euclid;
1898     pc->ops->view           = PCView_HYPRE_Euclid;
1899     jac->destroy            = HYPRE_EuclidDestroy;
1900     jac->setup              = HYPRE_EuclidSetup;
1901     jac->solve              = HYPRE_EuclidSolve;
1902     jac->factorrowsize      = PETSC_DEFAULT;
1903     jac->eu_level           = PETSC_DEFAULT; /* default */
1904     PetscFunctionReturn(PETSC_SUCCESS);
1905   }
1906   PetscCall(PetscStrcmp("parasails", jac->hypre_type, &flag));
1907   if (flag) {
1908     PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &jac->comm_hypre));
1909     PetscCallExternal(HYPRE_ParaSailsCreate, jac->comm_hypre, &jac->hsolver);
1910     pc->ops->setfromoptions = PCSetFromOptions_HYPRE_ParaSails;
1911     pc->ops->view           = PCView_HYPRE_ParaSails;
1912     jac->destroy            = HYPRE_ParaSailsDestroy;
1913     jac->setup              = HYPRE_ParaSailsSetup;
1914     jac->solve              = HYPRE_ParaSailsSolve;
1915     /* initialize */
1916     jac->nlevels   = 1;
1917     jac->threshold = .1;
1918     jac->filter    = .1;
1919     jac->loadbal   = 0;
1920     if (PetscLogPrintInfo) jac->logging = (int)PETSC_TRUE;
1921     else jac->logging = (int)PETSC_FALSE;
1922 
1923     jac->ruse = (int)PETSC_FALSE;
1924     jac->symt = 0;
1925     PetscCallExternal(HYPRE_ParaSailsSetParams, jac->hsolver, jac->threshold, jac->nlevels);
1926     PetscCallExternal(HYPRE_ParaSailsSetFilter, jac->hsolver, jac->filter);
1927     PetscCallExternal(HYPRE_ParaSailsSetLoadbal, jac->hsolver, jac->loadbal);
1928     PetscCallExternal(HYPRE_ParaSailsSetLogging, jac->hsolver, jac->logging);
1929     PetscCallExternal(HYPRE_ParaSailsSetReuse, jac->hsolver, jac->ruse);
1930     PetscCallExternal(HYPRE_ParaSailsSetSym, jac->hsolver, jac->symt);
1931     PetscFunctionReturn(PETSC_SUCCESS);
1932   }
1933   PetscCall(PetscStrcmp("boomeramg", jac->hypre_type, &flag));
1934   if (flag) {
1935     PetscCallExternal(HYPRE_BoomerAMGCreate, &jac->hsolver);
1936     pc->ops->setfromoptions  = PCSetFromOptions_HYPRE_BoomerAMG;
1937     pc->ops->view            = PCView_HYPRE_BoomerAMG;
1938     pc->ops->applytranspose  = PCApplyTranspose_HYPRE_BoomerAMG;
1939     pc->ops->applyrichardson = PCApplyRichardson_HYPRE_BoomerAMG;
1940     pc->ops->matapply        = PCMatApply_HYPRE_BoomerAMG;
1941     PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetInterpolations_C", PCGetInterpolations_BoomerAMG));
1942     PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGetCoarseOperators_C", PCGetCoarseOperators_BoomerAMG));
1943     jac->destroy         = HYPRE_BoomerAMGDestroy;
1944     jac->setup           = HYPRE_BoomerAMGSetup;
1945     jac->solve           = HYPRE_BoomerAMGSolve;
1946     jac->applyrichardson = PETSC_FALSE;
1947     /* these defaults match the hypre defaults */
1948     jac->cycletype       = 1;
1949     jac->maxlevels       = 25;
1950     jac->maxiter         = 1;
1951     jac->tol             = 0.0; /* tolerance of zero indicates use as preconditioner (suppresses convergence errors) */
1952     jac->truncfactor     = 0.0;
1953     jac->strongthreshold = .25;
1954     jac->maxrowsum       = .9;
1955     jac->coarsentype     = 6;
1956     jac->measuretype     = 0;
1957     jac->gridsweeps[0] = jac->gridsweeps[1] = jac->gridsweeps[2] = 1;
1958     jac->smoothtype                                              = -1; /* Not set by default */
1959     jac->smoothnumlevels                                         = 25;
1960     jac->eu_level                                                = 0;
1961     jac->eu_droptolerance                                        = 0;
1962     jac->eu_bj                                                   = 0;
1963     jac->relaxtype[0] = jac->relaxtype[1] = 6; /* Defaults to SYMMETRIC since in PETSc we are using a PC - most likely with CG */
1964     jac->relaxtype[2]                     = 9; /*G.E. */
1965     jac->relaxweight                      = 1.0;
1966     jac->outerrelaxweight                 = 1.0;
1967     jac->relaxorder                       = 1;
1968     jac->interptype                       = 0;
1969     jac->Rtype                            = 0;
1970     jac->Rstrongthreshold                 = 0.25;
1971     jac->Rfilterthreshold                 = 0.0;
1972     jac->Adroptype                        = -1;
1973     jac->Adroptol                         = 0.0;
1974     jac->agg_nl                           = 0;
1975     jac->agg_interptype                   = 4;
1976     jac->pmax                             = 0;
1977     jac->truncfactor                      = 0.0;
1978     jac->agg_num_paths                    = 1;
1979     jac->maxc                             = 9;
1980     jac->minc                             = 1;
1981     jac->nodal_coarsening                 = 0;
1982     jac->nodal_coarsening_diag            = 0;
1983     jac->vec_interp_variant               = 0;
1984     jac->vec_interp_qmax                  = 0;
1985     jac->vec_interp_smooth                = PETSC_FALSE;
1986     jac->interp_refine                    = 0;
1987     jac->nodal_relax                      = PETSC_FALSE;
1988     jac->nodal_relax_levels               = 1;
1989     jac->rap2                             = 0;
1990 
1991     /* GPU defaults
1992          from https://hypre.readthedocs.io/en/latest/solvers-boomeramg.html#gpu-supported-options
1993          and /src/parcsr_ls/par_amg.c */
1994 #if defined(PETSC_HAVE_HYPRE_DEVICE)
1995     jac->keeptranspose  = PETSC_TRUE;
1996     jac->mod_rap2       = 1;
1997     jac->coarsentype    = 8;
1998     jac->relaxorder     = 0;
1999     jac->interptype     = 6;
2000     jac->relaxtype[0]   = 18;
2001     jac->relaxtype[1]   = 18;
2002     jac->agg_interptype = 7;
2003 #else
2004     jac->keeptranspose = PETSC_FALSE;
2005     jac->mod_rap2      = 0;
2006 #endif
2007     PetscCallExternal(HYPRE_BoomerAMGSetCycleType, jac->hsolver, jac->cycletype);
2008     PetscCallExternal(HYPRE_BoomerAMGSetMaxLevels, jac->hsolver, jac->maxlevels);
2009     PetscCallExternal(HYPRE_BoomerAMGSetMaxIter, jac->hsolver, jac->maxiter);
2010     PetscCallExternal(HYPRE_BoomerAMGSetTol, jac->hsolver, jac->tol);
2011     PetscCallExternal(HYPRE_BoomerAMGSetTruncFactor, jac->hsolver, jac->truncfactor);
2012     PetscCallExternal(HYPRE_BoomerAMGSetStrongThreshold, jac->hsolver, jac->strongthreshold);
2013     PetscCallExternal(HYPRE_BoomerAMGSetMaxRowSum, jac->hsolver, jac->maxrowsum);
2014     PetscCallExternal(HYPRE_BoomerAMGSetCoarsenType, jac->hsolver, jac->coarsentype);
2015     PetscCallExternal(HYPRE_BoomerAMGSetMeasureType, jac->hsolver, jac->measuretype);
2016     PetscCallExternal(HYPRE_BoomerAMGSetRelaxOrder, jac->hsolver, jac->relaxorder);
2017     PetscCallExternal(HYPRE_BoomerAMGSetInterpType, jac->hsolver, jac->interptype);
2018     PetscCallExternal(HYPRE_BoomerAMGSetAggNumLevels, jac->hsolver, jac->agg_nl);
2019     PetscCallExternal(HYPRE_BoomerAMGSetAggInterpType, jac->hsolver, jac->agg_interptype);
2020     PetscCallExternal(HYPRE_BoomerAMGSetPMaxElmts, jac->hsolver, jac->pmax);
2021     PetscCallExternal(HYPRE_BoomerAMGSetNumPaths, jac->hsolver, jac->agg_num_paths);
2022     PetscCallExternal(HYPRE_BoomerAMGSetRelaxType, jac->hsolver, jac->relaxtype[0]);  /* defaults coarse to 9 */
2023     PetscCallExternal(HYPRE_BoomerAMGSetNumSweeps, jac->hsolver, jac->gridsweeps[0]); /* defaults coarse to 1 */
2024     PetscCallExternal(HYPRE_BoomerAMGSetMaxCoarseSize, jac->hsolver, jac->maxc);
2025     PetscCallExternal(HYPRE_BoomerAMGSetMinCoarseSize, jac->hsolver, jac->minc);
2026     /* GPU */
2027 #if PETSC_PKG_HYPRE_VERSION_GE(2, 18, 0)
2028     PetscCallExternal(HYPRE_BoomerAMGSetKeepTranspose, jac->hsolver, jac->keeptranspose ? 1 : 0);
2029     PetscCallExternal(HYPRE_BoomerAMGSetRAP2, jac->hsolver, jac->rap2);
2030     PetscCallExternal(HYPRE_BoomerAMGSetModuleRAP2, jac->hsolver, jac->mod_rap2);
2031 #endif
2032 
2033     /* AIR */
2034 #if PETSC_PKG_HYPRE_VERSION_GE(2, 18, 0)
2035     PetscCallExternal(HYPRE_BoomerAMGSetRestriction, jac->hsolver, jac->Rtype);
2036     PetscCallExternal(HYPRE_BoomerAMGSetStrongThresholdR, jac->hsolver, jac->Rstrongthreshold);
2037     PetscCallExternal(HYPRE_BoomerAMGSetFilterThresholdR, jac->hsolver, jac->Rfilterthreshold);
2038     PetscCallExternal(HYPRE_BoomerAMGSetADropTol, jac->hsolver, jac->Adroptol);
2039     PetscCallExternal(HYPRE_BoomerAMGSetADropType, jac->hsolver, jac->Adroptype);
2040 #endif
2041     PetscFunctionReturn(PETSC_SUCCESS);
2042   }
2043   PetscCall(PetscStrcmp("ams", jac->hypre_type, &flag));
2044   if (flag) {
2045     PetscCallExternal(HYPRE_AMSCreate, &jac->hsolver);
2046     pc->ops->setfromoptions = PCSetFromOptions_HYPRE_AMS;
2047     pc->ops->view           = PCView_HYPRE_AMS;
2048     jac->destroy            = HYPRE_AMSDestroy;
2049     jac->setup              = HYPRE_AMSSetup;
2050     jac->solve              = HYPRE_AMSSolve;
2051     jac->coords[0]          = NULL;
2052     jac->coords[1]          = NULL;
2053     jac->coords[2]          = NULL;
2054     jac->interior           = NULL;
2055     /* solver parameters: these are borrowed from mfem package, and they are not the default values from HYPRE AMS */
2056     jac->as_print       = 0;
2057     jac->as_max_iter    = 1;  /* used as a preconditioner */
2058     jac->as_tol         = 0.; /* used as a preconditioner */
2059     jac->ams_cycle_type = 13;
2060     /* Smoothing options */
2061     jac->as_relax_type   = 2;
2062     jac->as_relax_times  = 1;
2063     jac->as_relax_weight = 1.0;
2064     jac->as_omega        = 1.0;
2065     /* Vector valued Poisson AMG solver parameters: coarsen type, agg_levels, relax_type, interp_type, Pmax */
2066     jac->as_amg_alpha_opts[0] = 10;
2067     jac->as_amg_alpha_opts[1] = 1;
2068     jac->as_amg_alpha_opts[2] = 6;
2069     jac->as_amg_alpha_opts[3] = 6;
2070     jac->as_amg_alpha_opts[4] = 4;
2071     jac->as_amg_alpha_theta   = 0.25;
2072     /* Scalar Poisson AMG solver parameters: coarsen type, agg_levels, relax_type, interp_type, Pmax */
2073     jac->as_amg_beta_opts[0] = 10;
2074     jac->as_amg_beta_opts[1] = 1;
2075     jac->as_amg_beta_opts[2] = 6;
2076     jac->as_amg_beta_opts[3] = 6;
2077     jac->as_amg_beta_opts[4] = 4;
2078     jac->as_amg_beta_theta   = 0.25;
2079     PetscCallExternal(HYPRE_AMSSetPrintLevel, jac->hsolver, jac->as_print);
2080     PetscCallExternal(HYPRE_AMSSetMaxIter, jac->hsolver, jac->as_max_iter);
2081     PetscCallExternal(HYPRE_AMSSetCycleType, jac->hsolver, jac->ams_cycle_type);
2082     PetscCallExternal(HYPRE_AMSSetTol, jac->hsolver, jac->as_tol);
2083     PetscCallExternal(HYPRE_AMSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega);
2084     PetscCallExternal(HYPRE_AMSSetAlphaAMGOptions, jac->hsolver, jac->as_amg_alpha_opts[0], /* AMG coarsen type */
2085                       jac->as_amg_alpha_opts[1],                                            /* AMG agg_levels */
2086                       jac->as_amg_alpha_opts[2],                                            /* AMG relax_type */
2087                       jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3],                   /* AMG interp_type */
2088                       jac->as_amg_alpha_opts[4]);                                           /* AMG Pmax */
2089     PetscCallExternal(HYPRE_AMSSetBetaAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0],   /* AMG coarsen type */
2090                       jac->as_amg_beta_opts[1],                                             /* AMG agg_levels */
2091                       jac->as_amg_beta_opts[2],                                             /* AMG relax_type */
2092                       jac->as_amg_beta_theta, jac->as_amg_beta_opts[3],                     /* AMG interp_type */
2093                       jac->as_amg_beta_opts[4]);                                            /* AMG Pmax */
2094     /* Zero conductivity */
2095     jac->ams_beta_is_zero      = PETSC_FALSE;
2096     jac->ams_beta_is_zero_part = PETSC_FALSE;
2097     PetscFunctionReturn(PETSC_SUCCESS);
2098   }
2099   PetscCall(PetscStrcmp("ads", jac->hypre_type, &flag));
2100   if (flag) {
2101     PetscCallExternal(HYPRE_ADSCreate, &jac->hsolver);
2102     pc->ops->setfromoptions = PCSetFromOptions_HYPRE_ADS;
2103     pc->ops->view           = PCView_HYPRE_ADS;
2104     jac->destroy            = HYPRE_ADSDestroy;
2105     jac->setup              = HYPRE_ADSSetup;
2106     jac->solve              = HYPRE_ADSSolve;
2107     jac->coords[0]          = NULL;
2108     jac->coords[1]          = NULL;
2109     jac->coords[2]          = NULL;
2110     /* solver parameters: these are borrowed from mfem package, and they are not the default values from HYPRE ADS */
2111     jac->as_print       = 0;
2112     jac->as_max_iter    = 1;  /* used as a preconditioner */
2113     jac->as_tol         = 0.; /* used as a preconditioner */
2114     jac->ads_cycle_type = 13;
2115     /* Smoothing options */
2116     jac->as_relax_type   = 2;
2117     jac->as_relax_times  = 1;
2118     jac->as_relax_weight = 1.0;
2119     jac->as_omega        = 1.0;
2120     /* AMS solver parameters: cycle_type, coarsen type, agg_levels, relax_type, interp_type, Pmax */
2121     jac->ams_cycle_type       = 14;
2122     jac->as_amg_alpha_opts[0] = 10;
2123     jac->as_amg_alpha_opts[1] = 1;
2124     jac->as_amg_alpha_opts[2] = 6;
2125     jac->as_amg_alpha_opts[3] = 6;
2126     jac->as_amg_alpha_opts[4] = 4;
2127     jac->as_amg_alpha_theta   = 0.25;
2128     /* Vector Poisson AMG solver parameters: coarsen type, agg_levels, relax_type, interp_type, Pmax */
2129     jac->as_amg_beta_opts[0] = 10;
2130     jac->as_amg_beta_opts[1] = 1;
2131     jac->as_amg_beta_opts[2] = 6;
2132     jac->as_amg_beta_opts[3] = 6;
2133     jac->as_amg_beta_opts[4] = 4;
2134     jac->as_amg_beta_theta   = 0.25;
2135     PetscCallExternal(HYPRE_ADSSetPrintLevel, jac->hsolver, jac->as_print);
2136     PetscCallExternal(HYPRE_ADSSetMaxIter, jac->hsolver, jac->as_max_iter);
2137     PetscCallExternal(HYPRE_ADSSetCycleType, jac->hsolver, jac->ams_cycle_type);
2138     PetscCallExternal(HYPRE_ADSSetTol, jac->hsolver, jac->as_tol);
2139     PetscCallExternal(HYPRE_ADSSetSmoothingOptions, jac->hsolver, jac->as_relax_type, jac->as_relax_times, jac->as_relax_weight, jac->as_omega);
2140     PetscCallExternal(HYPRE_ADSSetAMSOptions, jac->hsolver, jac->ams_cycle_type,      /* AMG coarsen type */
2141                       jac->as_amg_alpha_opts[0],                                      /* AMG coarsen type */
2142                       jac->as_amg_alpha_opts[1],                                      /* AMG agg_levels */
2143                       jac->as_amg_alpha_opts[2],                                      /* AMG relax_type */
2144                       jac->as_amg_alpha_theta, jac->as_amg_alpha_opts[3],             /* AMG interp_type */
2145                       jac->as_amg_alpha_opts[4]);                                     /* AMG Pmax */
2146     PetscCallExternal(HYPRE_ADSSetAMGOptions, jac->hsolver, jac->as_amg_beta_opts[0], /* AMG coarsen type */
2147                       jac->as_amg_beta_opts[1],                                       /* AMG agg_levels */
2148                       jac->as_amg_beta_opts[2],                                       /* AMG relax_type */
2149                       jac->as_amg_beta_theta, jac->as_amg_beta_opts[3],               /* AMG interp_type */
2150                       jac->as_amg_beta_opts[4]);                                      /* AMG Pmax */
2151     PetscFunctionReturn(PETSC_SUCCESS);
2152   }
2153   PetscCall(PetscFree(jac->hypre_type));
2154 
2155   jac->hypre_type = NULL;
2156   SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown HYPRE preconditioner %s; Choices are euclid, pilut, parasails, boomeramg, ams", name);
2157 }
2158 
2159 /*
2160     It only gets here if the HYPRE type has not been set before the call to
2161    ...SetFromOptions() which actually is most of the time
2162 */
2163 PetscErrorCode PCSetFromOptions_HYPRE(PC pc, PetscOptionItems *PetscOptionsObject)
2164 {
2165   PetscInt    indx;
2166   const char *type[] = {"euclid", "pilut", "parasails", "boomeramg", "ams", "ads"};
2167   PetscBool   flg;
2168 
2169   PetscFunctionBegin;
2170   PetscOptionsHeadBegin(PetscOptionsObject, "HYPRE preconditioner options");
2171   PetscCall(PetscOptionsEList("-pc_hypre_type", "HYPRE preconditioner type", "PCHYPRESetType", type, PETSC_STATIC_ARRAY_LENGTH(type), "boomeramg", &indx, &flg));
2172   if (flg) {
2173     PetscCall(PCHYPRESetType_HYPRE(pc, type[indx]));
2174   } else {
2175     PetscCall(PCHYPRESetType_HYPRE(pc, "boomeramg"));
2176   }
2177   PetscTryTypeMethod(pc, setfromoptions, PetscOptionsObject);
2178   PetscOptionsHeadEnd();
2179   PetscFunctionReturn(PETSC_SUCCESS);
2180 }
2181 
2182 /*@C
2183      PCHYPRESetType - Sets which hypre preconditioner you wish to use
2184 
2185    Input Parameters:
2186 +     pc - the preconditioner context
2187 -     name - either  euclid, pilut, parasails, boomeramg, ams, ads
2188 
2189    Options Database Key:
2190    -pc_hypre_type - One of euclid, pilut, parasails, boomeramg, ams, ads
2191 
2192    Level: intermediate
2193 
2194 .seealso: `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHYPRE`
2195 @*/
2196 PetscErrorCode PCHYPRESetType(PC pc, const char name[])
2197 {
2198   PetscFunctionBegin;
2199   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2200   PetscValidCharPointer(name, 2);
2201   PetscTryMethod(pc, "PCHYPRESetType_C", (PC, const char[]), (pc, name));
2202   PetscFunctionReturn(PETSC_SUCCESS);
2203 }
2204 
2205 /*@C
2206      PCHYPREGetType - Gets which hypre preconditioner you are using
2207 
2208    Input Parameter:
2209 .     pc - the preconditioner context
2210 
2211    Output Parameter:
2212 .     name - either  euclid, pilut, parasails, boomeramg, ams, ads
2213 
2214    Level: intermediate
2215 
2216 .seealso: `PCCreate()`, `PCHYPRESetType()`, `PCType`, `PC`, `PCHYPRE`
2217 @*/
2218 PetscErrorCode PCHYPREGetType(PC pc, const char *name[])
2219 {
2220   PetscFunctionBegin;
2221   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2222   PetscValidPointer(name, 2);
2223   PetscTryMethod(pc, "PCHYPREGetType_C", (PC, const char *[]), (pc, name));
2224   PetscFunctionReturn(PETSC_SUCCESS);
2225 }
2226 
2227 /*@C
2228    PCMGGalerkinSetMatProductAlgorithm - Set type of SpGEMM for hypre to use on GPUs
2229 
2230    Logically Collective
2231 
2232    Input Parameters:
2233 +  pc - the hypre context
2234 -  type - one of 'cusparse', 'hypre'
2235 
2236    Options Database Key:
2237 .  -pc_mg_galerkin_mat_product_algorithm <cusparse,hypre> - Type of SpGEMM to use in hypre
2238 
2239    Level: intermediate
2240 
2241    Developer Note:
2242    How the name starts with `PCMG`, should it not be `PCHYPREBoomerAMG`?
2243 
2244 .seealso: `PCHYPRE`, `PCMGGalerkinGetMatProductAlgorithm()`
2245 @*/
2246 PetscErrorCode PCMGGalerkinSetMatProductAlgorithm(PC pc, const char name[])
2247 {
2248   PetscFunctionBegin;
2249   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2250   PetscTryMethod(pc, "PCMGGalerkinSetMatProductAlgorithm_C", (PC, const char[]), (pc, name));
2251   PetscFunctionReturn(PETSC_SUCCESS);
2252 }
2253 
2254 /*@C
2255    PCMGGalerkinGetMatProductAlgorithm - Get type of SpGEMM for hypre to use on GPUs
2256 
2257    Not Collective
2258 
2259    Input Parameter:
2260 .  pc - the multigrid context
2261 
2262    Output Parameter:
2263 .  name - one of 'cusparse', 'hypre'
2264 
2265    Level: intermediate
2266 
2267 .seealso: `PCHYPRE`, ``PCMGGalerkinSetMatProductAlgorithm()`
2268 @*/
2269 PetscErrorCode PCMGGalerkinGetMatProductAlgorithm(PC pc, const char *name[])
2270 {
2271   PetscFunctionBegin;
2272   PetscValidHeaderSpecific(pc, PC_CLASSID, 1);
2273   PetscTryMethod(pc, "PCMGGalerkinGetMatProductAlgorithm_C", (PC, const char *[]), (pc, name));
2274   PetscFunctionReturn(PETSC_SUCCESS);
2275 }
2276 
2277 /*MC
2278      PCHYPRE - Allows you to use the matrix element based preconditioners in the LLNL package hypre as PETSc `PC`
2279 
2280    Options Database Keys:
2281 +   -pc_hypre_type - One of euclid, pilut, parasails, boomeramg, ams, ads
2282 .   -pc_hypre_boomeramg_nodal_coarsen <n> - where n is from 1 to 6 (see `HYPRE_BOOMERAMGSetNodal()`)
2283 .   -pc_hypre_boomeramg_vec_interp_variant <v> - where v is from 1 to 3 (see `HYPRE_BoomerAMGSetInterpVecVariant()`)
2284 -   Many others, run with -pc_type hypre -pc_hypre_type XXX -help to see options for the XXX preconditioner
2285 
2286    Level: intermediate
2287 
2288    Notes:
2289     Apart from pc_hypre_type (for which there is `PCHYPRESetType()`),
2290           the many hypre options can ONLY be set via the options database (e.g. the command line
2291           or with `PetscOptionsSetValue()`, there are no functions to set them)
2292 
2293           The options -pc_hypre_boomeramg_max_iter and -pc_hypre_boomeramg_tol refer to the number of iterations
2294           (V-cycles) and tolerance that boomeramg does EACH time it is called. So for example, if
2295           -pc_hypre_boomeramg_max_iter is set to 2 then 2-V-cycles are being used to define the preconditioner
2296           (-pc_hypre_boomeramg_tol should be set to 0.0 - the default - to strictly use a fixed number of
2297           iterations per hypre call). -ksp_max_it and -ksp_rtol STILL determine the total number of iterations
2298           and tolerance for the Krylov solver. For example, if -pc_hypre_boomeramg_max_iter is 2 and -ksp_max_it is 10
2299           then AT MOST twenty V-cycles of boomeramg will be called.
2300 
2301            Note that the option -pc_hypre_boomeramg_relax_type_all defaults to symmetric relaxation
2302            (symmetric-SOR/Jacobi), which is required for Krylov solvers like CG that expect symmetry.
2303            Otherwise, you may want to use -pc_hypre_boomeramg_relax_type_all SOR/Jacobi.
2304           If you wish to use BoomerAMG WITHOUT a Krylov method use -ksp_type richardson NOT -ksp_type preonly
2305           and use -ksp_max_it to control the number of V-cycles.
2306           (see the PETSc FAQ.html at the PETSc website under the Documentation tab).
2307 
2308           `MatSetNearNullSpace()` - if you provide a near null space to your matrix it is ignored by hypre UNLESS you also use
2309           the following two options: ``-pc_hypre_boomeramg_nodal_coarsen <n> -pc_hypre_boomeramg_vec_interp_variant <v>``
2310 
2311           See `PCPFMG`, `PCSMG`, and `PCSYSPFMG` for access to hypre's other (nonalgebraic) multigrid solvers
2312 
2313           For `PCHYPRE` type of ams or ads auxiliary data must be provided to the preconditioner with `PCHYPRESetDiscreteGradient()`,
2314           `PCHYPRESetDiscreteCurl()`, `PCHYPRESetInterpolations()`, `PCHYPRESetAlphaPoissonMatrix()`, `PCHYPRESetBetaPoissonMatrix()`, `PCHYPRESetEdgeConstantVectors()`,
2315           `PCHYPREAMSSetInteriorNodes()`
2316 
2317    PETSc provides its own geometric and algebraic multigrid solvers `PCMG` and `PCGAMG`, also see `PCHMG` which is useful for certain multicomponent problems
2318 
2319    GPU Notes:
2320      To configure hypre BoomerAMG so that it can utilize NVIDIA GPUs run ./configure --download-hypre --with-cuda
2321      Then pass `VECCUDA` vectors and `MATAIJCUSPARSE` matrices to the solvers and PETSc will automatically utilize hypre's GPU solvers.
2322 
2323      To configure hypre BoomerAMG so that it can utilize AMD GPUs run ./configure --download-hypre --with-hip
2324      Then pass `VECHIP` vectors to the solvers and PETSc will automatically utilize hypre's GPU solvers.
2325 
2326 .seealso: `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHYPRESetType()`, `PCPFMG`, `PCGAMG`, `PCSYSPFMG`, `PCSMG`, `PCHYPRESetDiscreteGradient()`,
2327           `PCHYPRESetDiscreteCurl()`, `PCHYPRESetInterpolations()`, `PCHYPRESetAlphaPoissonMatrix()`, `PCHYPRESetBetaPoissonMatrix()`, `PCHYPRESetEdgeConstantVectors()`,
2328           PCHYPREAMSSetInteriorNodes()
2329 M*/
2330 
2331 PETSC_EXTERN PetscErrorCode PCCreate_HYPRE(PC pc)
2332 {
2333   PC_HYPRE *jac;
2334 
2335   PetscFunctionBegin;
2336   PetscCall(PetscNew(&jac));
2337 
2338   pc->data                = jac;
2339   pc->ops->reset          = PCReset_HYPRE;
2340   pc->ops->destroy        = PCDestroy_HYPRE;
2341   pc->ops->setfromoptions = PCSetFromOptions_HYPRE;
2342   pc->ops->setup          = PCSetUp_HYPRE;
2343   pc->ops->apply          = PCApply_HYPRE;
2344   jac->comm_hypre         = MPI_COMM_NULL;
2345   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetType_C", PCHYPRESetType_HYPRE));
2346   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREGetType_C", PCHYPREGetType_HYPRE));
2347   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", PCSetCoordinates_HYPRE));
2348   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteGradient_C", PCHYPRESetDiscreteGradient_HYPRE));
2349   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetDiscreteCurl_C", PCHYPRESetDiscreteCurl_HYPRE));
2350   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetInterpolations_C", PCHYPRESetInterpolations_HYPRE));
2351   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetEdgeConstantVectors_C", PCHYPRESetEdgeConstantVectors_HYPRE));
2352   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPREAMSSetInteriorNodes_C", PCHYPREAMSSetInteriorNodes_HYPRE));
2353   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHYPRESetPoissonMatrix_C", PCHYPRESetPoissonMatrix_HYPRE));
2354   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinSetMatProductAlgorithm_C", PCMGGalerkinSetMatProductAlgorithm_HYPRE_BoomerAMG));
2355   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCMGGalerkinGetMatProductAlgorithm_C", PCMGGalerkinGetMatProductAlgorithm_HYPRE_BoomerAMG));
2356 #if defined(PETSC_HAVE_HYPRE_DEVICE)
2357   #if defined(HYPRE_USING_HIP)
2358   PetscCall(PetscDeviceInitialize(PETSC_DEVICE_HIP));
2359   #endif
2360   #if defined(HYPRE_USING_CUDA)
2361   PetscCall(PetscDeviceInitialize(PETSC_DEVICE_CUDA));
2362   #endif
2363 #endif
2364   PetscHYPREInitialize();
2365   PetscFunctionReturn(PETSC_SUCCESS);
2366 }
2367 
2368 typedef struct {
2369   MPI_Comm           hcomm; /* does not share comm with HYPRE_StructMatrix because need to create solver before getting matrix */
2370   HYPRE_StructSolver hsolver;
2371 
2372   /* keep copy of PFMG options used so may view them */
2373   PetscInt  its;
2374   double    tol;
2375   PetscInt  relax_type;
2376   PetscInt  rap_type;
2377   PetscInt  num_pre_relax, num_post_relax;
2378   PetscInt  max_levels;
2379   PetscInt  skip_relax;
2380   PetscBool print_statistics;
2381 } PC_PFMG;
2382 
2383 PetscErrorCode PCDestroy_PFMG(PC pc)
2384 {
2385   PC_PFMG *ex = (PC_PFMG *)pc->data;
2386 
2387   PetscFunctionBegin;
2388   if (ex->hsolver) PetscCallExternal(HYPRE_StructPFMGDestroy, ex->hsolver);
2389   PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &ex->hcomm));
2390   PetscCall(PetscFree(pc->data));
2391   PetscFunctionReturn(PETSC_SUCCESS);
2392 }
2393 
2394 static const char *PFMGRelaxType[] = {"Jacobi", "Weighted-Jacobi", "symmetric-Red/Black-Gauss-Seidel", "Red/Black-Gauss-Seidel"};
2395 static const char *PFMGRAPType[]   = {"Galerkin", "non-Galerkin"};
2396 
2397 PetscErrorCode PCView_PFMG(PC pc, PetscViewer viewer)
2398 {
2399   PetscBool iascii;
2400   PC_PFMG  *ex = (PC_PFMG *)pc->data;
2401 
2402   PetscFunctionBegin;
2403   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
2404   if (iascii) {
2405     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE PFMG preconditioning\n"));
2406     PetscCall(PetscViewerASCIIPrintf(viewer, "    max iterations %" PetscInt_FMT "\n", ex->its));
2407     PetscCall(PetscViewerASCIIPrintf(viewer, "    tolerance %g\n", ex->tol));
2408     PetscCall(PetscViewerASCIIPrintf(viewer, "    relax type %s\n", PFMGRelaxType[ex->relax_type]));
2409     PetscCall(PetscViewerASCIIPrintf(viewer, "    RAP type %s\n", PFMGRAPType[ex->rap_type]));
2410     PetscCall(PetscViewerASCIIPrintf(viewer, "    number pre-relax %" PetscInt_FMT " post-relax %" PetscInt_FMT "\n", ex->num_pre_relax, ex->num_post_relax));
2411     PetscCall(PetscViewerASCIIPrintf(viewer, "    max levels %" PetscInt_FMT "\n", ex->max_levels));
2412     PetscCall(PetscViewerASCIIPrintf(viewer, "    skip relax %" PetscInt_FMT "\n", ex->skip_relax));
2413   }
2414   PetscFunctionReturn(PETSC_SUCCESS);
2415 }
2416 
2417 PetscErrorCode PCSetFromOptions_PFMG(PC pc, PetscOptionItems *PetscOptionsObject)
2418 {
2419   PC_PFMG *ex = (PC_PFMG *)pc->data;
2420 
2421   PetscFunctionBegin;
2422   PetscOptionsHeadBegin(PetscOptionsObject, "PFMG options");
2423   PetscCall(PetscOptionsBool("-pc_pfmg_print_statistics", "Print statistics", "HYPRE_StructPFMGSetPrintLevel", ex->print_statistics, &ex->print_statistics, NULL));
2424   PetscCall(PetscOptionsInt("-pc_pfmg_its", "Number of iterations of PFMG to use as preconditioner", "HYPRE_StructPFMGSetMaxIter", ex->its, &ex->its, NULL));
2425   PetscCallExternal(HYPRE_StructPFMGSetMaxIter, ex->hsolver, ex->its);
2426   PetscCall(PetscOptionsInt("-pc_pfmg_num_pre_relax", "Number of smoothing steps before coarse grid", "HYPRE_StructPFMGSetNumPreRelax", ex->num_pre_relax, &ex->num_pre_relax, NULL));
2427   PetscCallExternal(HYPRE_StructPFMGSetNumPreRelax, ex->hsolver, ex->num_pre_relax);
2428   PetscCall(PetscOptionsInt("-pc_pfmg_num_post_relax", "Number of smoothing steps after coarse grid", "HYPRE_StructPFMGSetNumPostRelax", ex->num_post_relax, &ex->num_post_relax, NULL));
2429   PetscCallExternal(HYPRE_StructPFMGSetNumPostRelax, ex->hsolver, ex->num_post_relax);
2430 
2431   PetscCall(PetscOptionsInt("-pc_pfmg_max_levels", "Max Levels for MG hierarchy", "HYPRE_StructPFMGSetMaxLevels", ex->max_levels, &ex->max_levels, NULL));
2432   PetscCallExternal(HYPRE_StructPFMGSetMaxLevels, ex->hsolver, ex->max_levels);
2433 
2434   PetscCall(PetscOptionsReal("-pc_pfmg_tol", "Tolerance of PFMG", "HYPRE_StructPFMGSetTol", ex->tol, &ex->tol, NULL));
2435   PetscCallExternal(HYPRE_StructPFMGSetTol, ex->hsolver, ex->tol);
2436   PetscCall(PetscOptionsEList("-pc_pfmg_relax_type", "Relax type for the up and down cycles", "HYPRE_StructPFMGSetRelaxType", PFMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(PFMGRelaxType), PFMGRelaxType[ex->relax_type], &ex->relax_type, NULL));
2437   PetscCallExternal(HYPRE_StructPFMGSetRelaxType, ex->hsolver, ex->relax_type);
2438   PetscCall(PetscOptionsEList("-pc_pfmg_rap_type", "RAP type", "HYPRE_StructPFMGSetRAPType", PFMGRAPType, PETSC_STATIC_ARRAY_LENGTH(PFMGRAPType), PFMGRAPType[ex->rap_type], &ex->rap_type, NULL));
2439   PetscCallExternal(HYPRE_StructPFMGSetRAPType, ex->hsolver, ex->rap_type);
2440   PetscCall(PetscOptionsInt("-pc_pfmg_skip_relax", "Skip relaxation on certain grids for isotropic problems. This can greatly improve efficiency by eliminating unnecessary relaxations when the underlying problem is isotropic", "HYPRE_StructPFMGSetSkipRelax", ex->skip_relax, &ex->skip_relax, NULL));
2441   PetscCallExternal(HYPRE_StructPFMGSetSkipRelax, ex->hsolver, ex->skip_relax);
2442   PetscOptionsHeadEnd();
2443   PetscFunctionReturn(PETSC_SUCCESS);
2444 }
2445 
2446 PetscErrorCode PCApply_PFMG(PC pc, Vec x, Vec y)
2447 {
2448   PC_PFMG           *ex = (PC_PFMG *)pc->data;
2449   PetscScalar       *yy;
2450   const PetscScalar *xx;
2451   PetscInt           ilower[3], iupper[3];
2452   HYPRE_Int          hlower[3], hupper[3];
2453   Mat_HYPREStruct   *mx = (Mat_HYPREStruct *)(pc->pmat->data);
2454 
2455   PetscFunctionBegin;
2456   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
2457   PetscCall(DMDAGetCorners(mx->da, &ilower[0], &ilower[1], &ilower[2], &iupper[0], &iupper[1], &iupper[2]));
2458   /* when HYPRE_MIXEDINT is defined, sizeof(HYPRE_Int) == 32 */
2459   iupper[0] += ilower[0] - 1;
2460   iupper[1] += ilower[1] - 1;
2461   iupper[2] += ilower[2] - 1;
2462   hlower[0] = (HYPRE_Int)ilower[0];
2463   hlower[1] = (HYPRE_Int)ilower[1];
2464   hlower[2] = (HYPRE_Int)ilower[2];
2465   hupper[0] = (HYPRE_Int)iupper[0];
2466   hupper[1] = (HYPRE_Int)iupper[1];
2467   hupper[2] = (HYPRE_Int)iupper[2];
2468 
2469   /* copy x values over to hypre */
2470   PetscCallExternal(HYPRE_StructVectorSetConstantValues, mx->hb, 0.0);
2471   PetscCall(VecGetArrayRead(x, &xx));
2472   PetscCallExternal(HYPRE_StructVectorSetBoxValues, mx->hb, hlower, hupper, (HYPRE_Complex *)xx);
2473   PetscCall(VecRestoreArrayRead(x, &xx));
2474   PetscCallExternal(HYPRE_StructVectorAssemble, mx->hb);
2475   PetscCallExternal(HYPRE_StructPFMGSolve, ex->hsolver, mx->hmat, mx->hb, mx->hx);
2476 
2477   /* copy solution values back to PETSc */
2478   PetscCall(VecGetArray(y, &yy));
2479   PetscCallExternal(HYPRE_StructVectorGetBoxValues, mx->hx, hlower, hupper, (HYPRE_Complex *)yy);
2480   PetscCall(VecRestoreArray(y, &yy));
2481   PetscFunctionReturn(PETSC_SUCCESS);
2482 }
2483 
2484 static PetscErrorCode PCApplyRichardson_PFMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason)
2485 {
2486   PC_PFMG  *jac = (PC_PFMG *)pc->data;
2487   HYPRE_Int oits;
2488 
2489   PetscFunctionBegin;
2490   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
2491   PetscCallExternal(HYPRE_StructPFMGSetMaxIter, jac->hsolver, its * jac->its);
2492   PetscCallExternal(HYPRE_StructPFMGSetTol, jac->hsolver, rtol);
2493 
2494   PetscCall(PCApply_PFMG(pc, b, y));
2495   PetscCallExternal(HYPRE_StructPFMGGetNumIterations, jac->hsolver, &oits);
2496   *outits = oits;
2497   if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS;
2498   else *reason = PCRICHARDSON_CONVERGED_RTOL;
2499   PetscCallExternal(HYPRE_StructPFMGSetTol, jac->hsolver, jac->tol);
2500   PetscCallExternal(HYPRE_StructPFMGSetMaxIter, jac->hsolver, jac->its);
2501   PetscFunctionReturn(PETSC_SUCCESS);
2502 }
2503 
2504 PetscErrorCode PCSetUp_PFMG(PC pc)
2505 {
2506   PC_PFMG         *ex = (PC_PFMG *)pc->data;
2507   Mat_HYPREStruct *mx = (Mat_HYPREStruct *)(pc->pmat->data);
2508   PetscBool        flg;
2509 
2510   PetscFunctionBegin;
2511   PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRESTRUCT, &flg));
2512   PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "Must use MATHYPRESTRUCT with this preconditioner");
2513 
2514   /* create the hypre solver object and set its information */
2515   if (ex->hsolver) PetscCallExternal(HYPRE_StructPFMGDestroy, ex->hsolver);
2516   PetscCallExternal(HYPRE_StructPFMGCreate, ex->hcomm, &ex->hsolver);
2517 
2518   // Print Hypre statistics about the solve process
2519   if (ex->print_statistics) PetscCallExternal(HYPRE_StructPFMGSetPrintLevel, ex->hsolver, 3);
2520 
2521   // The hypre options must be repeated here because the StructPFMG was destroyed and recreated
2522   PetscCallExternal(HYPRE_StructPFMGSetMaxIter, ex->hsolver, ex->its);
2523   PetscCallExternal(HYPRE_StructPFMGSetNumPreRelax, ex->hsolver, ex->num_pre_relax);
2524   PetscCallExternal(HYPRE_StructPFMGSetNumPostRelax, ex->hsolver, ex->num_post_relax);
2525   PetscCallExternal(HYPRE_StructPFMGSetMaxLevels, ex->hsolver, ex->max_levels);
2526   PetscCallExternal(HYPRE_StructPFMGSetTol, ex->hsolver, ex->tol);
2527   PetscCallExternal(HYPRE_StructPFMGSetRelaxType, ex->hsolver, ex->relax_type);
2528   PetscCallExternal(HYPRE_StructPFMGSetRAPType, ex->hsolver, ex->rap_type);
2529 
2530   PetscCallExternal(HYPRE_StructPFMGSetup, ex->hsolver, mx->hmat, mx->hb, mx->hx);
2531   PetscCallExternal(HYPRE_StructPFMGSetZeroGuess, ex->hsolver);
2532   PetscFunctionReturn(PETSC_SUCCESS);
2533 }
2534 
2535 /*MC
2536      PCPFMG - the hypre PFMG multigrid solver
2537 
2538    Options Database Keys:
2539 + -pc_pfmg_its <its> - number of iterations of PFMG to use as preconditioner
2540 . -pc_pfmg_num_pre_relax <steps> - number of smoothing steps before coarse grid solve
2541 . -pc_pfmg_num_post_relax <steps> - number of smoothing steps after coarse grid solve
2542 . -pc_pfmg_tol <tol> - tolerance of PFMG
2543 . -pc_pfmg_relax_type - relaxation type for the up and down cycles, one of Jacobi,Weighted-Jacobi,symmetric-Red/Black-Gauss-Seidel,Red/Black-Gauss-Seidel
2544 . -pc_pfmg_rap_type - type of coarse matrix generation, one of Galerkin,non-Galerkin
2545 - -pc_pfmg_skip_relax - skip relaxation on certain grids for isotropic problems. This can greatly improve efficiency by eliminating unnecessary relaxations
2546                         when the underlying problem is isotropic, one of 0,1
2547 
2548    Level: advanced
2549 
2550    Notes:
2551    This is for CELL-centered descretizations
2552 
2553    See `PCSYSPFMG` for a version suitable for systems of PDEs, and `PCSMG`
2554 
2555    See `PCHYPRE` for hypre's BoomerAMG algebraic multigrid solver
2556 
2557    This must be used with the `MATHYPRESTRUCT` matrix type.
2558 
2559    This provides only some of the functionality of PFMG, it supports only one block per process defined by a PETSc `DMDA`.
2560 
2561 .seealso: `PCMG`, `MATHYPRESTRUCT`, `PCHYPRE`, `PCGAMG`, `PCSYSPFMG`, `PCSMG`
2562 M*/
2563 
2564 PETSC_EXTERN PetscErrorCode PCCreate_PFMG(PC pc)
2565 {
2566   PC_PFMG *ex;
2567 
2568   PetscFunctionBegin;
2569   PetscCall(PetscNew(&ex));
2570   pc->data = ex;
2571 
2572   ex->its              = 1;
2573   ex->tol              = 1.e-8;
2574   ex->relax_type       = 1;
2575   ex->rap_type         = 0;
2576   ex->num_pre_relax    = 1;
2577   ex->num_post_relax   = 1;
2578   ex->max_levels       = 0;
2579   ex->skip_relax       = 0;
2580   ex->print_statistics = PETSC_FALSE;
2581 
2582   pc->ops->setfromoptions  = PCSetFromOptions_PFMG;
2583   pc->ops->view            = PCView_PFMG;
2584   pc->ops->destroy         = PCDestroy_PFMG;
2585   pc->ops->apply           = PCApply_PFMG;
2586   pc->ops->applyrichardson = PCApplyRichardson_PFMG;
2587   pc->ops->setup           = PCSetUp_PFMG;
2588 
2589   PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &ex->hcomm));
2590   PetscHYPREInitialize();
2591   PetscCallExternal(HYPRE_StructPFMGCreate, ex->hcomm, &ex->hsolver);
2592   PetscFunctionReturn(PETSC_SUCCESS);
2593 }
2594 
2595 /* we know we are working with a HYPRE_SStructMatrix */
2596 typedef struct {
2597   MPI_Comm            hcomm; /* does not share comm with HYPRE_SStructMatrix because need to create solver before getting matrix */
2598   HYPRE_SStructSolver ss_solver;
2599 
2600   /* keep copy of SYSPFMG options used so may view them */
2601   PetscInt its;
2602   double   tol;
2603   PetscInt relax_type;
2604   PetscInt num_pre_relax, num_post_relax;
2605 } PC_SysPFMG;
2606 
2607 PetscErrorCode PCDestroy_SysPFMG(PC pc)
2608 {
2609   PC_SysPFMG *ex = (PC_SysPFMG *)pc->data;
2610 
2611   PetscFunctionBegin;
2612   if (ex->ss_solver) PetscCallExternal(HYPRE_SStructSysPFMGDestroy, ex->ss_solver);
2613   PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &ex->hcomm));
2614   PetscCall(PetscFree(pc->data));
2615   PetscFunctionReturn(PETSC_SUCCESS);
2616 }
2617 
2618 static const char *SysPFMGRelaxType[] = {"Weighted-Jacobi", "Red/Black-Gauss-Seidel"};
2619 
2620 PetscErrorCode PCView_SysPFMG(PC pc, PetscViewer viewer)
2621 {
2622   PetscBool   iascii;
2623   PC_SysPFMG *ex = (PC_SysPFMG *)pc->data;
2624 
2625   PetscFunctionBegin;
2626   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
2627   if (iascii) {
2628     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE SysPFMG preconditioning\n"));
2629     PetscCall(PetscViewerASCIIPrintf(viewer, "  max iterations %" PetscInt_FMT "\n", ex->its));
2630     PetscCall(PetscViewerASCIIPrintf(viewer, "  tolerance %g\n", ex->tol));
2631     PetscCall(PetscViewerASCIIPrintf(viewer, "  relax type %s\n", PFMGRelaxType[ex->relax_type]));
2632     PetscCall(PetscViewerASCIIPrintf(viewer, "  number pre-relax %" PetscInt_FMT " post-relax %" PetscInt_FMT "\n", ex->num_pre_relax, ex->num_post_relax));
2633   }
2634   PetscFunctionReturn(PETSC_SUCCESS);
2635 }
2636 
2637 PetscErrorCode PCSetFromOptions_SysPFMG(PC pc, PetscOptionItems *PetscOptionsObject)
2638 {
2639   PC_SysPFMG *ex  = (PC_SysPFMG *)pc->data;
2640   PetscBool   flg = PETSC_FALSE;
2641 
2642   PetscFunctionBegin;
2643   PetscOptionsHeadBegin(PetscOptionsObject, "SysPFMG options");
2644   PetscCall(PetscOptionsBool("-pc_syspfmg_print_statistics", "Print statistics", "HYPRE_SStructSysPFMGSetPrintLevel", flg, &flg, NULL));
2645   if (flg) PetscCallExternal(HYPRE_SStructSysPFMGSetPrintLevel, ex->ss_solver, 3);
2646   PetscCall(PetscOptionsInt("-pc_syspfmg_its", "Number of iterations of SysPFMG to use as preconditioner", "HYPRE_SStructSysPFMGSetMaxIter", ex->its, &ex->its, NULL));
2647   PetscCallExternal(HYPRE_SStructSysPFMGSetMaxIter, ex->ss_solver, ex->its);
2648   PetscCall(PetscOptionsInt("-pc_syspfmg_num_pre_relax", "Number of smoothing steps before coarse grid", "HYPRE_SStructSysPFMGSetNumPreRelax", ex->num_pre_relax, &ex->num_pre_relax, NULL));
2649   PetscCallExternal(HYPRE_SStructSysPFMGSetNumPreRelax, ex->ss_solver, ex->num_pre_relax);
2650   PetscCall(PetscOptionsInt("-pc_syspfmg_num_post_relax", "Number of smoothing steps after coarse grid", "HYPRE_SStructSysPFMGSetNumPostRelax", ex->num_post_relax, &ex->num_post_relax, NULL));
2651   PetscCallExternal(HYPRE_SStructSysPFMGSetNumPostRelax, ex->ss_solver, ex->num_post_relax);
2652 
2653   PetscCall(PetscOptionsReal("-pc_syspfmg_tol", "Tolerance of SysPFMG", "HYPRE_SStructSysPFMGSetTol", ex->tol, &ex->tol, NULL));
2654   PetscCallExternal(HYPRE_SStructSysPFMGSetTol, ex->ss_solver, ex->tol);
2655   PetscCall(PetscOptionsEList("-pc_syspfmg_relax_type", "Relax type for the up and down cycles", "HYPRE_SStructSysPFMGSetRelaxType", SysPFMGRelaxType, PETSC_STATIC_ARRAY_LENGTH(SysPFMGRelaxType), SysPFMGRelaxType[ex->relax_type], &ex->relax_type, NULL));
2656   PetscCallExternal(HYPRE_SStructSysPFMGSetRelaxType, ex->ss_solver, ex->relax_type);
2657   PetscOptionsHeadEnd();
2658   PetscFunctionReturn(PETSC_SUCCESS);
2659 }
2660 
2661 PetscErrorCode PCApply_SysPFMG(PC pc, Vec x, Vec y)
2662 {
2663   PC_SysPFMG        *ex = (PC_SysPFMG *)pc->data;
2664   PetscScalar       *yy;
2665   const PetscScalar *xx;
2666   PetscInt           ilower[3], iupper[3];
2667   HYPRE_Int          hlower[3], hupper[3];
2668   Mat_HYPRESStruct  *mx       = (Mat_HYPRESStruct *)(pc->pmat->data);
2669   PetscInt           ordering = mx->dofs_order;
2670   PetscInt           nvars    = mx->nvars;
2671   PetscInt           part     = 0;
2672   PetscInt           size;
2673   PetscInt           i;
2674 
2675   PetscFunctionBegin;
2676   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
2677   PetscCall(DMDAGetCorners(mx->da, &ilower[0], &ilower[1], &ilower[2], &iupper[0], &iupper[1], &iupper[2]));
2678   /* when HYPRE_MIXEDINT is defined, sizeof(HYPRE_Int) == 32 */
2679   iupper[0] += ilower[0] - 1;
2680   iupper[1] += ilower[1] - 1;
2681   iupper[2] += ilower[2] - 1;
2682   hlower[0] = (HYPRE_Int)ilower[0];
2683   hlower[1] = (HYPRE_Int)ilower[1];
2684   hlower[2] = (HYPRE_Int)ilower[2];
2685   hupper[0] = (HYPRE_Int)iupper[0];
2686   hupper[1] = (HYPRE_Int)iupper[1];
2687   hupper[2] = (HYPRE_Int)iupper[2];
2688 
2689   size = 1;
2690   for (i = 0; i < 3; i++) size *= (iupper[i] - ilower[i] + 1);
2691 
2692   /* copy x values over to hypre for variable ordering */
2693   if (ordering) {
2694     PetscCallExternal(HYPRE_SStructVectorSetConstantValues, mx->ss_b, 0.0);
2695     PetscCall(VecGetArrayRead(x, &xx));
2696     for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorSetBoxValues, mx->ss_b, part, hlower, hupper, i, (HYPRE_Complex *)(xx + (size * i)));
2697     PetscCall(VecRestoreArrayRead(x, &xx));
2698     PetscCallExternal(HYPRE_SStructVectorAssemble, mx->ss_b);
2699     PetscCallExternal(HYPRE_SStructMatrixMatvec, 1.0, mx->ss_mat, mx->ss_b, 0.0, mx->ss_x);
2700     PetscCallExternal(HYPRE_SStructSysPFMGSolve, ex->ss_solver, mx->ss_mat, mx->ss_b, mx->ss_x);
2701 
2702     /* copy solution values back to PETSc */
2703     PetscCall(VecGetArray(y, &yy));
2704     for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorGetBoxValues, mx->ss_x, part, hlower, hupper, i, (HYPRE_Complex *)(yy + (size * i)));
2705     PetscCall(VecRestoreArray(y, &yy));
2706   } else { /* nodal ordering must be mapped to variable ordering for sys_pfmg */
2707     PetscScalar *z;
2708     PetscInt     j, k;
2709 
2710     PetscCall(PetscMalloc1(nvars * size, &z));
2711     PetscCallExternal(HYPRE_SStructVectorSetConstantValues, mx->ss_b, 0.0);
2712     PetscCall(VecGetArrayRead(x, &xx));
2713 
2714     /* transform nodal to hypre's variable ordering for sys_pfmg */
2715     for (i = 0; i < size; i++) {
2716       k = i * nvars;
2717       for (j = 0; j < nvars; j++) z[j * size + i] = xx[k + j];
2718     }
2719     for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorSetBoxValues, mx->ss_b, part, hlower, hupper, i, (HYPRE_Complex *)(z + (size * i)));
2720     PetscCall(VecRestoreArrayRead(x, &xx));
2721     PetscCallExternal(HYPRE_SStructVectorAssemble, mx->ss_b);
2722     PetscCallExternal(HYPRE_SStructSysPFMGSolve, ex->ss_solver, mx->ss_mat, mx->ss_b, mx->ss_x);
2723 
2724     /* copy solution values back to PETSc */
2725     PetscCall(VecGetArray(y, &yy));
2726     for (i = 0; i < nvars; i++) PetscCallExternal(HYPRE_SStructVectorGetBoxValues, mx->ss_x, part, hlower, hupper, i, (HYPRE_Complex *)(z + (size * i)));
2727     /* transform hypre's variable ordering for sys_pfmg to nodal ordering */
2728     for (i = 0; i < size; i++) {
2729       k = i * nvars;
2730       for (j = 0; j < nvars; j++) yy[k + j] = z[j * size + i];
2731     }
2732     PetscCall(VecRestoreArray(y, &yy));
2733     PetscCall(PetscFree(z));
2734   }
2735   PetscFunctionReturn(PETSC_SUCCESS);
2736 }
2737 
2738 static PetscErrorCode PCApplyRichardson_SysPFMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason)
2739 {
2740   PC_SysPFMG *jac = (PC_SysPFMG *)pc->data;
2741   HYPRE_Int   oits;
2742 
2743   PetscFunctionBegin;
2744   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
2745   PetscCallExternal(HYPRE_SStructSysPFMGSetMaxIter, jac->ss_solver, its * jac->its);
2746   PetscCallExternal(HYPRE_SStructSysPFMGSetTol, jac->ss_solver, rtol);
2747   PetscCall(PCApply_SysPFMG(pc, b, y));
2748   PetscCallExternal(HYPRE_SStructSysPFMGGetNumIterations, jac->ss_solver, &oits);
2749   *outits = oits;
2750   if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS;
2751   else *reason = PCRICHARDSON_CONVERGED_RTOL;
2752   PetscCallExternal(HYPRE_SStructSysPFMGSetTol, jac->ss_solver, jac->tol);
2753   PetscCallExternal(HYPRE_SStructSysPFMGSetMaxIter, jac->ss_solver, jac->its);
2754   PetscFunctionReturn(PETSC_SUCCESS);
2755 }
2756 
2757 PetscErrorCode PCSetUp_SysPFMG(PC pc)
2758 {
2759   PC_SysPFMG       *ex = (PC_SysPFMG *)pc->data;
2760   Mat_HYPRESStruct *mx = (Mat_HYPRESStruct *)(pc->pmat->data);
2761   PetscBool         flg;
2762 
2763   PetscFunctionBegin;
2764   PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRESSTRUCT, &flg));
2765   PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "Must use MATHYPRESSTRUCT with this preconditioner");
2766 
2767   /* create the hypre sstruct solver object and set its information */
2768   if (ex->ss_solver) PetscCallExternal(HYPRE_SStructSysPFMGDestroy, ex->ss_solver);
2769   PetscCallExternal(HYPRE_SStructSysPFMGCreate, ex->hcomm, &ex->ss_solver);
2770   PetscCallExternal(HYPRE_SStructSysPFMGSetZeroGuess, ex->ss_solver);
2771   PetscCallExternal(HYPRE_SStructSysPFMGSetup, ex->ss_solver, mx->ss_mat, mx->ss_b, mx->ss_x);
2772   PetscFunctionReturn(PETSC_SUCCESS);
2773 }
2774 
2775 /*MC
2776      PCSYSPFMG - the hypre SysPFMG multigrid solver
2777 
2778    Level: advanced
2779 
2780    Options Database Keys:
2781 + -pc_syspfmg_its <its> - number of iterations of SysPFMG to use as preconditioner
2782 . -pc_syspfmg_num_pre_relax <steps> - number of smoothing steps before coarse grid
2783 . -pc_syspfmg_num_post_relax <steps> - number of smoothing steps after coarse grid
2784 . -pc_syspfmg_tol <tol> - tolerance of SysPFMG
2785 - -pc_syspfmg_relax_type <Weighted-Jacobi,Red/Black-Gauss-Seidel> - relaxation type for the up and down cycles
2786 
2787    Notes:
2788    See `PCPFMG` for hypre's PFMG that works for a scalar PDE and `PCSMG`
2789 
2790    See `PCHYPRE` for hypre's BoomerAMG algebraic multigrid solver
2791 
2792    This is for CELL-centered descretizations
2793 
2794    This must be used with the `MATHYPRESSTRUCT` matrix type.
2795 
2796    This does not give access to all the functionality of hypres SysPFMG, it supports only one part, and one block per process defined by a PETSc `DMDA`.
2797 
2798 .seealso: `PCMG`, `MATHYPRESSTRUCT`, `PCPFMG`, `PCHYPRE`, `PCGAMG`, `PCSMG`
2799 M*/
2800 
2801 PETSC_EXTERN PetscErrorCode PCCreate_SysPFMG(PC pc)
2802 {
2803   PC_SysPFMG *ex;
2804 
2805   PetscFunctionBegin;
2806   PetscCall(PetscNew(&ex));
2807   pc->data = ex;
2808 
2809   ex->its            = 1;
2810   ex->tol            = 1.e-8;
2811   ex->relax_type     = 1;
2812   ex->num_pre_relax  = 1;
2813   ex->num_post_relax = 1;
2814 
2815   pc->ops->setfromoptions  = PCSetFromOptions_SysPFMG;
2816   pc->ops->view            = PCView_SysPFMG;
2817   pc->ops->destroy         = PCDestroy_SysPFMG;
2818   pc->ops->apply           = PCApply_SysPFMG;
2819   pc->ops->applyrichardson = PCApplyRichardson_SysPFMG;
2820   pc->ops->setup           = PCSetUp_SysPFMG;
2821 
2822   PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &ex->hcomm));
2823   PetscHYPREInitialize();
2824   PetscCallExternal(HYPRE_SStructSysPFMGCreate, ex->hcomm, &ex->ss_solver);
2825   PetscFunctionReturn(PETSC_SUCCESS);
2826 }
2827 
2828 /* PC SMG */
2829 typedef struct {
2830   MPI_Comm           hcomm; /* does not share comm with HYPRE_StructMatrix because need to create solver before getting matrix */
2831   HYPRE_StructSolver hsolver;
2832   PetscInt           its; /* keep copy of SMG options used so may view them */
2833   double             tol;
2834   PetscBool          print_statistics;
2835   PetscInt           num_pre_relax, num_post_relax;
2836 } PC_SMG;
2837 
2838 PetscErrorCode PCDestroy_SMG(PC pc)
2839 {
2840   PC_SMG *ex = (PC_SMG *)pc->data;
2841 
2842   PetscFunctionBegin;
2843   if (ex->hsolver) PetscCallExternal(HYPRE_StructSMGDestroy, ex->hsolver);
2844   PetscCall(PetscCommRestoreComm(PetscObjectComm((PetscObject)pc), &ex->hcomm));
2845   PetscCall(PetscFree(pc->data));
2846   PetscFunctionReturn(PETSC_SUCCESS);
2847 }
2848 
2849 PetscErrorCode PCView_SMG(PC pc, PetscViewer viewer)
2850 {
2851   PetscBool iascii;
2852   PC_SMG   *ex = (PC_SMG *)pc->data;
2853 
2854   PetscFunctionBegin;
2855   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
2856   if (iascii) {
2857     PetscCall(PetscViewerASCIIPrintf(viewer, "  HYPRE SMG preconditioning\n"));
2858     PetscCall(PetscViewerASCIIPrintf(viewer, "    max iterations %" PetscInt_FMT "\n", ex->its));
2859     PetscCall(PetscViewerASCIIPrintf(viewer, "    tolerance %g\n", ex->tol));
2860     PetscCall(PetscViewerASCIIPrintf(viewer, "    number pre-relax %" PetscInt_FMT " post-relax %" PetscInt_FMT "\n", ex->num_pre_relax, ex->num_post_relax));
2861   }
2862   PetscFunctionReturn(PETSC_SUCCESS);
2863 }
2864 
2865 PetscErrorCode PCSetFromOptions_SMG(PC pc, PetscOptionItems *PetscOptionsObject)
2866 {
2867   PC_SMG *ex = (PC_SMG *)pc->data;
2868 
2869   PetscFunctionBegin;
2870   PetscOptionsHeadBegin(PetscOptionsObject, "SMG options");
2871 
2872   PetscCall(PetscOptionsInt("-pc_smg_its", "Number of iterations of SMG to use as preconditioner", "HYPRE_StructSMGSetMaxIter", ex->its, &ex->its, NULL));
2873   PetscCall(PetscOptionsInt("-pc_smg_num_pre_relax", "Number of smoothing steps before coarse grid", "HYPRE_StructSMGSetNumPreRelax", ex->num_pre_relax, &ex->num_pre_relax, NULL));
2874   PetscCall(PetscOptionsInt("-pc_smg_num_post_relax", "Number of smoothing steps after coarse grid", "HYPRE_StructSMGSetNumPostRelax", ex->num_post_relax, &ex->num_post_relax, NULL));
2875   PetscCall(PetscOptionsReal("-pc_smg_tol", "Tolerance of SMG", "HYPRE_StructSMGSetTol", ex->tol, &ex->tol, NULL));
2876 
2877   PetscOptionsHeadEnd();
2878   PetscFunctionReturn(PETSC_SUCCESS);
2879 }
2880 
2881 PetscErrorCode PCApply_SMG(PC pc, Vec x, Vec y)
2882 {
2883   PC_SMG            *ex = (PC_SMG *)pc->data;
2884   PetscScalar       *yy;
2885   const PetscScalar *xx;
2886   PetscInt           ilower[3], iupper[3];
2887   HYPRE_Int          hlower[3], hupper[3];
2888   Mat_HYPREStruct   *mx = (Mat_HYPREStruct *)(pc->pmat->data);
2889 
2890   PetscFunctionBegin;
2891   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
2892   PetscCall(DMDAGetCorners(mx->da, &ilower[0], &ilower[1], &ilower[2], &iupper[0], &iupper[1], &iupper[2]));
2893   /* when HYPRE_MIXEDINT is defined, sizeof(HYPRE_Int) == 32 */
2894   iupper[0] += ilower[0] - 1;
2895   iupper[1] += ilower[1] - 1;
2896   iupper[2] += ilower[2] - 1;
2897   hlower[0] = (HYPRE_Int)ilower[0];
2898   hlower[1] = (HYPRE_Int)ilower[1];
2899   hlower[2] = (HYPRE_Int)ilower[2];
2900   hupper[0] = (HYPRE_Int)iupper[0];
2901   hupper[1] = (HYPRE_Int)iupper[1];
2902   hupper[2] = (HYPRE_Int)iupper[2];
2903 
2904   /* copy x values over to hypre */
2905   PetscCallExternal(HYPRE_StructVectorSetConstantValues, mx->hb, 0.0);
2906   PetscCall(VecGetArrayRead(x, &xx));
2907   PetscCallExternal(HYPRE_StructVectorSetBoxValues, mx->hb, hlower, hupper, (HYPRE_Complex *)xx);
2908   PetscCall(VecRestoreArrayRead(x, &xx));
2909   PetscCallExternal(HYPRE_StructVectorAssemble, mx->hb);
2910   PetscCallExternal(HYPRE_StructSMGSolve, ex->hsolver, mx->hmat, mx->hb, mx->hx);
2911 
2912   /* copy solution values back to PETSc */
2913   PetscCall(VecGetArray(y, &yy));
2914   PetscCallExternal(HYPRE_StructVectorGetBoxValues, mx->hx, hlower, hupper, (HYPRE_Complex *)yy);
2915   PetscCall(VecRestoreArray(y, &yy));
2916   PetscFunctionReturn(PETSC_SUCCESS);
2917 }
2918 
2919 static PetscErrorCode PCApplyRichardson_SMG(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason)
2920 {
2921   PC_SMG   *jac = (PC_SMG *)pc->data;
2922   HYPRE_Int oits;
2923 
2924   PetscFunctionBegin;
2925   PetscCall(PetscCitationsRegister(hypreCitation, &cite));
2926   PetscCallExternal(HYPRE_StructSMGSetMaxIter, jac->hsolver, its * jac->its);
2927   PetscCallExternal(HYPRE_StructSMGSetTol, jac->hsolver, rtol);
2928 
2929   PetscCall(PCApply_SMG(pc, b, y));
2930   PetscCallExternal(HYPRE_StructSMGGetNumIterations, jac->hsolver, &oits);
2931   *outits = oits;
2932   if (oits == its) *reason = PCRICHARDSON_CONVERGED_ITS;
2933   else *reason = PCRICHARDSON_CONVERGED_RTOL;
2934   PetscCallExternal(HYPRE_StructSMGSetTol, jac->hsolver, jac->tol);
2935   PetscCallExternal(HYPRE_StructSMGSetMaxIter, jac->hsolver, jac->its);
2936   PetscFunctionReturn(PETSC_SUCCESS);
2937 }
2938 
2939 PetscErrorCode PCSetUp_SMG(PC pc)
2940 {
2941   PetscInt         i, dim;
2942   PC_SMG          *ex = (PC_SMG *)pc->data;
2943   Mat_HYPREStruct *mx = (Mat_HYPREStruct *)(pc->pmat->data);
2944   PetscBool        flg;
2945   DMBoundaryType   p[3];
2946   PetscInt         M[3];
2947 
2948   PetscFunctionBegin;
2949   PetscCall(PetscObjectTypeCompare((PetscObject)pc->pmat, MATHYPRESTRUCT, &flg));
2950   PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "Must use MATHYPRESTRUCT with this preconditioner");
2951 
2952   PetscCall(DMDAGetInfo(mx->da, &dim, &M[0], &M[1], &M[2], 0, 0, 0, 0, 0, &p[0], &p[1], &p[2], 0));
2953   // Check if power of 2 in periodic directions
2954   for (i = 0; i < dim; i++) {
2955     if (((M[i] & (M[i] - 1)) != 0) && (p[i] == DM_BOUNDARY_PERIODIC)) {
2956       SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "With SMG, the number of points in a periodic direction must be a power of 2, but is here %" PetscInt_FMT ".", M[i]);
2957     }
2958   }
2959 
2960   /* create the hypre solver object and set its information */
2961   if (ex->hsolver) PetscCallExternal(HYPRE_StructSMGDestroy, (ex->hsolver));
2962   PetscCallExternal(HYPRE_StructSMGCreate, ex->hcomm, &ex->hsolver);
2963   // The hypre options must be set here and not in SetFromOptions because it is created here!
2964   PetscCallExternal(HYPRE_StructSMGSetMaxIter, ex->hsolver, ex->its);
2965   PetscCallExternal(HYPRE_StructSMGSetNumPreRelax, ex->hsolver, ex->num_pre_relax);
2966   PetscCallExternal(HYPRE_StructSMGSetNumPostRelax, ex->hsolver, ex->num_post_relax);
2967   PetscCallExternal(HYPRE_StructSMGSetTol, ex->hsolver, ex->tol);
2968 
2969   PetscCallExternal(HYPRE_StructSMGSetup, ex->hsolver, mx->hmat, mx->hb, mx->hx);
2970   PetscCallExternal(HYPRE_StructSMGSetZeroGuess, ex->hsolver);
2971   PetscFunctionReturn(PETSC_SUCCESS);
2972 }
2973 
2974 /*MC
2975      PCSMG - the hypre (structured grid) SMG multigrid solver
2976 
2977    Level: advanced
2978 
2979    Options Database Keys:
2980 + -pc_smg_its <its> - number of iterations of SMG to use as preconditioner
2981 . -pc_smg_num_pre_relax <steps> - number of smoothing steps before coarse grid
2982 . -pc_smg_num_post_relax <steps> - number of smoothing steps after coarse grid
2983 - -pc_smg_tol <tol> - tolerance of SMG
2984 
2985    Notes:
2986    This is for CELL-centered descretizations
2987 
2988    This must be used with the `MATHYPRESTRUCT` `MatType`.
2989 
2990    This does not provide all the functionality of  hypre's SMG solver, it supports only one block per process defined by a PETSc `DMDA`.
2991 
2992    See `PCSYSPFMG`, `PCSMG`, `PCPFMG`, and `PCHYPRE` for access to hypre's other preconditioners
2993 
2994 .seealso:  `PCMG`, `MATHYPRESTRUCT`, `PCPFMG`, `PCSYSPFMG`, `PCHYPRE`, `PCGAMG`
2995 M*/
2996 
2997 PETSC_EXTERN PetscErrorCode PCCreate_SMG(PC pc)
2998 {
2999   PC_SMG *ex;
3000 
3001   PetscFunctionBegin;
3002   PetscCall(PetscNew(&ex));
3003   pc->data = ex;
3004 
3005   ex->its            = 1;
3006   ex->tol            = 1.e-8;
3007   ex->num_pre_relax  = 1;
3008   ex->num_post_relax = 1;
3009 
3010   pc->ops->setfromoptions  = PCSetFromOptions_SMG;
3011   pc->ops->view            = PCView_SMG;
3012   pc->ops->destroy         = PCDestroy_SMG;
3013   pc->ops->apply           = PCApply_SMG;
3014   pc->ops->applyrichardson = PCApplyRichardson_SMG;
3015   pc->ops->setup           = PCSetUp_SMG;
3016 
3017   PetscCall(PetscCommGetComm(PetscObjectComm((PetscObject)pc), &ex->hcomm));
3018   PetscHYPREInitialize();
3019   PetscCallExternal(HYPRE_StructSMGCreate, ex->hcomm, &ex->hsolver);
3020   PetscFunctionReturn(PETSC_SUCCESS);
3021 }
3022