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