www.mooseframework.org
Classes | Functions
Moose::PetscSupport Namespace Reference

Classes

class  PetscOptions
 A struct for storing the various types of petsc options and values. More...
 

Functions

void petscSetOptions (const PetscOptions &po, const SolverParams &solver_params)
 A function for setting the PETSc options in PETSc from the options supplied to MOOSE. More...
 
void petscSetKSPDefaults (FEProblemBase &problem, KSP ksp)
 Set the default options for a KSP. More...
 
template<typename T >
void setLinearSolverDefaults (FEProblemBase &problem, LinearSolver< T > &linear_solver)
 Set the defaults for a libMesh LinearSolver. More...
 
void petscSetDefaults (FEProblemBase &problem)
 Sets the default options for PETSc. More...
 
void petscSetupDM (NonlinearSystemBase &nl, const std::string &dm_name)
 Setup the PETSc DM object. More...
 
PetscErrorCode petscSetupOutput (CommandLine *cmd_line)
 
void outputNorm (libMesh::Real old_norm, libMesh::Real norm, bool use_color=false)
 Helper function for outputting the norm values with/without color. More...
 
PetscErrorCode petscLinearMonitor (KSP, PetscInt its, PetscReal rnorm, void *void_ptr)
 Helper function for displaying the linear residual during PETSC solve. More...
 
void storePetscOptions (FEProblemBase &fe_problem, const InputParameters &params)
 Stores the PETSc options supplied from the InputParameters with MOOSE. More...
 
void processPetscFlags (const MultiMooseEnum &petsc_flags, PetscOptions &petsc_options)
 Populate flags in a given PetscOptions object using a vector of input arguments. More...
 
void processPetscPairs (const std::vector< std::pair< MooseEnumItem, std::string >> &petsc_pair_options, const unsigned int mesh_dimension, PetscOptions &petsc_options)
 Populate name and value pairs in a given PetscOptions object using vectors of input arguments. More...
 
std::set< std::string > getPetscValidLineSearches ()
 Returns the valid petsc line search options as a set of strings. More...
 
InputParameters getPetscValidParams ()
 Returns the PETSc options that are common between Executioners and Preconditioners. More...
 
MultiMooseEnum getCommonPetscFlags ()
 A helper function to produce a MultiMooseEnum with commonly used PETSc single options (flags) More...
 
MultiMooseEnum getCommonPetscKeys ()
 A helper function to produce a MultiMooseEnum with commonly used PETSc iname options (keys in key-value pairs) More...
 
bool isSNESVI (FEProblemBase &fe_problem)
 check if SNES type is variational inequalities (VI) solver More...
 
void setSinglePetscOption (const std::string &name, const std::string &value="")
 A wrapper function for dealing with different versions of PetscOptionsSetValue. More...
 
void addPetscOptionsFromCommandline ()
 
void petscSetDefaultPCSide (FEProblemBase &problem, KSP ksp)
 Setup which side we want to apply preconditioner. More...
 
void petscSetDefaultKSPNormType (FEProblemBase &problem, KSP ksp)
 Set norm type. More...
 
void colorAdjacencyMatrix (PetscScalar *adjacency_matrix, unsigned int size, unsigned int colors, std::vector< unsigned int > &vertex_colors, const char *coloring_algorithm)
 This method takes an adjacency matrix, and a desired number of colors and applies a graph coloring algorithm to produce a coloring. More...
 
void disableNonlinearConvergedReason (FEProblemBase &fe_problem)
 disable printing of the nonlinear convergence reason More...
 
void disableLinearConvergedReason (FEProblemBase &fe_problem)
 disable printing of the linear convergence reason More...
 
std::string stringify (const LineSearchType &t)
 
std::string stringify (const MffdType &t)
 
void setSolverOptions (const SolverParams &solver_params)
 
PetscErrorCode petscNonlinearConverged (SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, void *ctx)
 
PCSide getPetscPCSide (Moose::PCSideType pcs)
 
KSPNormType getPetscKSPNormType (Moose::MooseKSPNormType kspnorm)
 

Function Documentation

◆ addPetscOptionsFromCommandline()

void Moose::PetscSupport::addPetscOptionsFromCommandline ( )

Definition at line 220 of file PetscSupport.C.

Referenced by petscSetOptions(), and Moose::SlepcSupport::slepcSetOptions().

221 {
222  // commandline options always win
223  // the options from a user commandline will overwrite the existing ones if any conflicts
224  { // Get any options specified on the command-line
225  int argc;
226  char ** args;
227 
228  PetscGetArgs(&argc, &args);
229 #if PETSC_VERSION_LESS_THAN(3, 7, 0)
230  PetscOptionsInsert(&argc, &args, NULL);
231 #else
232  PetscOptionsInsert(LIBMESH_PETSC_NULLPTR, &argc, &args, NULL);
233 #endif
234  }
235 }

◆ colorAdjacencyMatrix()

void Moose::PetscSupport::colorAdjacencyMatrix ( PetscScalar *  adjacency_matrix,
unsigned int  size,
unsigned int  colors,
std::vector< unsigned int > &  vertex_colors,
const char *  coloring_algorithm 
)

This method takes an adjacency matrix, and a desired number of colors and applies a graph coloring algorithm to produce a coloring.

The coloring is returned as a vector of unsigned integers indicating which color or group each vextex in the adjacency matrix belongs to.

Definition at line 944 of file PetscSupport.C.

949 {
950  // Mat A will be a dense matrix from the incoming data structure
951  Mat A;
952  MatCreate(MPI_COMM_SELF, &A);
953  MatSetSizes(A, size, size, size, size);
954  MatSetType(A, MATSEQDENSE);
955  // PETSc requires a non-const data array to populate the matrix
956  MatSeqDenseSetPreallocation(A, adjacency_matrix);
957  MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
958  MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
959 
960  // Convert A to a sparse matrix
961  MatConvert(A,
962  MATAIJ,
963 #if PETSC_VERSION_LESS_THAN(3, 7, 0)
964  MAT_REUSE_MATRIX,
965 #else
966  MAT_INPLACE_MATRIX,
967 #endif
968  &A);
969 
970  ISColoring iscoloring;
971  MatColoring mc;
972  MatColoringCreate(A, &mc);
973  MatColoringSetType(mc, coloring_algorithm);
974  MatColoringSetMaxColors(mc, static_cast<PetscInt>(colors));
975 
976  // Petsc normally colors by distance two (neighbors of neighbors), we just want one
977  MatColoringSetDistance(mc, 1);
978  MatColoringSetFromOptions(mc);
979  MatColoringApply(mc, &iscoloring);
980 
981  PetscInt nn;
982  IS * is;
983 #if PETSC_RELEASE_LESS_THAN(3, 12, 0)
984  ISColoringGetIS(iscoloring, &nn, &is);
985 #else
986  ISColoringGetIS(iscoloring, PETSC_USE_POINTER, &nn, &is);
987 #endif
988 
989  if (nn > static_cast<PetscInt>(colors))
990  throw std::runtime_error("Not able to color with designated number of colors");
991 
992  for (int i = 0; i < nn; i++)
993  {
994  PetscInt isize;
995  const PetscInt * indices;
996  ISGetLocalSize(is[i], &isize);
997  ISGetIndices(is[i], &indices);
998  for (int j = 0; j < isize; j++)
999  {
1000  mooseAssert(indices[j] < static_cast<PetscInt>(vertex_colors.size()), "Index out of bounds");
1001  vertex_colors[indices[j]] = i;
1002  }
1003  ISRestoreIndices(is[i], &indices);
1004  }
1005 
1006  MatDestroy(&A);
1007  MatColoringDestroy(&mc);
1008  ISColoringDestroy(&iscoloring);
1009 }
PetscErrorCode PetscInt const PetscInt IS * is

◆ disableLinearConvergedReason()

void Moose::PetscSupport::disableLinearConvergedReason ( FEProblemBase fe_problem)

disable printing of the linear convergence reason

Definition at line 1025 of file PetscSupport.C.

Referenced by CommonOutputAction::act().

1026 {
1027  auto & petsc_options = fe_problem.getPetscOptions();
1028 
1029  petsc_options.flags.erase("-ksp_converged_reason");
1030 
1031  auto & pairs = petsc_options.pairs;
1032  auto it = MooseUtils::findPair(pairs, "-ksp_converged_reason", MooseUtils::Any);
1033  if (it != pairs.end())
1034  pairs.erase(it);
1035 }
Moose::PetscSupport::PetscOptions & getPetscOptions()
Retrieve a writable reference the PETSc options (used by PetscSupport)
MultiMooseEnum flags
Single value PETSc options (flags)
Definition: PetscSupport.h:47
C::iterator findPair(C &container, const M1 &first, const M2 &second)
Find a specific pair in a container matching on first, second or both pair components.
Definition: MooseUtils.h:1053
void erase(const std::string &names)
Un-assign a value.
static const struct MooseUtils::AnyType Any

◆ disableNonlinearConvergedReason()

void Moose::PetscSupport::disableNonlinearConvergedReason ( FEProblemBase fe_problem)

disable printing of the nonlinear convergence reason

Definition at line 1012 of file PetscSupport.C.

Referenced by CommonOutputAction::act().

1013 {
1014  auto & petsc_options = fe_problem.getPetscOptions();
1015 
1016  petsc_options.flags.erase("-snes_converged_reason");
1017 
1018  auto & pairs = petsc_options.pairs;
1019  auto it = MooseUtils::findPair(pairs, "-snes_converged_reason", MooseUtils::Any);
1020  if (it != pairs.end())
1021  pairs.erase(it);
1022 }
Moose::PetscSupport::PetscOptions & getPetscOptions()
Retrieve a writable reference the PETSc options (used by PetscSupport)
MultiMooseEnum flags
Single value PETSc options (flags)
Definition: PetscSupport.h:47
C::iterator findPair(C &container, const M1 &first, const M2 &second)
Find a specific pair in a container matching on first, second or both pair components.
Definition: MooseUtils.h:1053
void erase(const std::string &names)
Un-assign a value.
static const struct MooseUtils::AnyType Any

◆ getCommonPetscFlags()

MultiMooseEnum Moose::PetscSupport::getCommonPetscFlags ( )

A helper function to produce a MultiMooseEnum with commonly used PETSc single options (flags)

Definition at line 874 of file PetscSupport.C.

Referenced by getPetscValidParams(), AddFieldSplitAction::validParams(), and Split::validParams().

875 {
876  return MultiMooseEnum(
877  "-dm_moose_print_embedding -dm_view -ksp_converged_reason -ksp_gmres_modifiedgramschmidt "
878  "-ksp_monitor -ksp_monitor_snes_lg-snes_ksp_ew -ksp_snes_ew -snes_converged_reason "
879  "-snes_ksp -snes_ksp_ew -snes_linesearch_monitor -snes_mf -snes_mf_operator -snes_monitor "
880  "-snes_test_display -snes_view",
881  "",
882  true);
883 }
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...

◆ getCommonPetscKeys()

MultiMooseEnum Moose::PetscSupport::getCommonPetscKeys ( )

A helper function to produce a MultiMooseEnum with commonly used PETSc iname options (keys in key-value pairs)

Definition at line 886 of file PetscSupport.C.

Referenced by getPetscValidParams(), and AddFieldSplitAction::validParams().

887 {
888  return MultiMooseEnum("-ksp_atol -ksp_gmres_restart -ksp_max_it -ksp_pc_side -ksp_rtol "
889  "-ksp_type -mat_fd_coloring_err -mat_fd_type -mat_mffd_type "
890  "-pc_asm_overlap -pc_factor_levels "
891  "-pc_factor_mat_ordering_type -pc_hypre_boomeramg_grid_sweeps_all "
892  "-pc_hypre_boomeramg_max_iter "
893  "-pc_hypre_boomeramg_strong_threshold -pc_hypre_type -pc_type -snes_atol "
894  "-snes_linesearch_type "
895  "-snes_ls -snes_max_it -snes_rtol -snes_divergence_tolerance -snes_type "
896  "-sub_ksp_type -sub_pc_type",
897  "",
898  true);
899 }
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...

◆ getPetscKSPNormType()

KSPNormType Moose::PetscSupport::getPetscKSPNormType ( Moose::MooseKSPNormType  kspnorm)

Definition at line 434 of file PetscSupport.C.

Referenced by petscSetDefaultKSPNormType().

435 {
436  switch (kspnorm)
437  {
438  case Moose::KSPN_NONE:
439  return KSP_NORM_NONE;
441  return KSP_NORM_PRECONDITIONED;
443  return KSP_NORM_UNPRECONDITIONED;
444  case Moose::KSPN_NATURAL:
445  return KSP_NORM_NATURAL;
446  case Moose::KSPN_DEFAULT:
447  return KSP_NORM_DEFAULT;
448  default:
449  mooseError("Unknown KSP norm type requested.");
450  break;
451  }
452 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
Use whatever we have in PETSc.
Definition: MooseTypes.h:749

◆ getPetscPCSide()

PCSide Moose::PetscSupport::getPetscPCSide ( Moose::PCSideType  pcs)

Definition at line 417 of file PetscSupport.C.

Referenced by petscSetDefaultPCSide().

418 {
419  switch (pcs)
420  {
421  case Moose::PCS_LEFT:
422  return PC_LEFT;
423  case Moose::PCS_RIGHT:
424  return PC_RIGHT;
426  return PC_SYMMETRIC;
427  default:
428  mooseError("Unknown PC side requested.");
429  break;
430  }
431 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284

◆ getPetscValidLineSearches()

std::set< std::string > Moose::PetscSupport::getPetscValidLineSearches ( )

Returns the valid petsc line search options as a set of strings.

Definition at line 833 of file PetscSupport.C.

Referenced by FEProblemSolve::validParams().

834 {
835  return {"default", "shell", "none", "basic", "l2", "bt", "cp"};
836 }

◆ getPetscValidParams()

InputParameters Moose::PetscSupport::getPetscValidParams ( )

Returns the PETSc options that are common between Executioners and Preconditioners.

Returns
InputParameters object containing the PETSc related parameters

The output of this function should be added to the the parameters object of the overarching class

See also
CreateExecutionerAction

Definition at line 839 of file PetscSupport.C.

Referenced by FEProblemSolve::validParams(), and MoosePreconditioner::validParams().

840 {
842 
843  MooseEnum solve_type("PJFNK JFNK NEWTON FD LINEAR");
844  params.addParam<MooseEnum>("solve_type",
845  solve_type,
846  "PJFNK: Preconditioned Jacobian-Free Newton Krylov "
847  "JFNK: Jacobian-Free Newton Krylov "
848  "NEWTON: Full Newton Solve "
849  "FD: Use finite differences to compute Jacobian "
850  "LINEAR: Solving a linear problem");
851 
852  MooseEnum mffd_type("wp ds", "wp");
853  params.addParam<MooseEnum>("mffd_type",
854  mffd_type,
855  "Specifies the finite differencing type for "
856  "Jacobian-free solve types. Note that the "
857  "default is wp (for Walker and Pernice).");
858 
859  params.addParam<MultiMooseEnum>(
860  "petsc_options", getCommonPetscFlags(), "Singleton PETSc options");
861  params.addParam<MultiMooseEnum>(
862  "petsc_options_iname", getCommonPetscKeys(), "Names of PETSc name/value pairs");
863  params.addParam<std::vector<std::string>>(
864  "petsc_options_value",
865  "Values of PETSc name/value pairs (must correspond with \"petsc_options_iname\"");
866  params.addParamNamesToGroup("solve_type petsc_options petsc_options_iname petsc_options_value "
867  "mffd_type",
868  "PETSc");
869 
870  return params;
871 }
MultiMooseEnum getCommonPetscKeys()
A helper function to produce a MultiMooseEnum with commonly used PETSc iname options (keys in key-val...
Definition: PetscSupport.C:886
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
InputParameters emptyInputParameters()
MultiMooseEnum getCommonPetscFlags()
A helper function to produce a MultiMooseEnum with commonly used PETSc single options (flags) ...
Definition: PetscSupport.C:874
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition: MooseEnum.h:31
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an option parameter and a documentation string to the InputParameters object...
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
void addParamNamesToGroup(const std::string &space_delim_names, const std::string group_name)
This method takes a space delimited list of parameter names and adds them to the specified group name...

◆ isSNESVI()

bool Moose::PetscSupport::isSNESVI ( FEProblemBase fe_problem)

check if SNES type is variational inequalities (VI) solver

Definition at line 902 of file PetscSupport.C.

Referenced by BoundsBase::BoundsBase().

903 {
904  PetscOptions & petsc = fe_problem.getPetscOptions();
905 
906  int argc;
907  char ** args;
908  PetscGetArgs(&argc, &args);
909 
910  std::vector<std::string> cml_arg;
911  for (int i = 0; i < argc; i++)
912  cml_arg.push_back(args[i]);
913 
914  if (MooseUtils::findPair(petsc.pairs, MooseUtils::Any, "vinewtonssls") == petsc.pairs.end() &&
915  MooseUtils::findPair(petsc.pairs, MooseUtils::Any, "vinewtonrsls") == petsc.pairs.end() &&
916  std::find(cml_arg.begin(), cml_arg.end(), "vinewtonssls") == cml_arg.end() &&
917  std::find(cml_arg.begin(), cml_arg.end(), "vinewtonrsls") == cml_arg.end())
918  return false;
919 
920  return true;
921 }
Moose::PetscSupport::PetscOptions & getPetscOptions()
Retrieve a writable reference the PETSc options (used by PetscSupport)
C::iterator findPair(C &container, const M1 &first, const M2 &second)
Find a specific pair in a container matching on first, second or both pair components.
Definition: MooseUtils.h:1053
static const struct MooseUtils::AnyType Any

◆ outputNorm()

void Moose::PetscSupport::outputNorm ( libMesh::Real  old_norm,
libMesh::Real  norm,
bool  use_color = false 
)

Helper function for outputting the norm values with/without color.

◆ petscLinearMonitor()

PetscErrorCode Moose::PetscSupport::petscLinearMonitor ( KSP  ,
PetscInt  its,
PetscReal  rnorm,
void void_ptr 
)

Helper function for displaying the linear residual during PETSC solve.

◆ petscNonlinearConverged()

PetscErrorCode Moose::PetscSupport::petscNonlinearConverged ( SNES  snes,
PetscInt  it,
PetscReal  xnorm,
PetscReal  snorm,
PetscReal  fnorm,
SNESConvergedReason *  reason,
void ctx 
)

Definition at line 276 of file PetscSupport.C.

Referenced by petscSetDefaults().

283 {
284  FEProblemBase & problem = *static_cast<FEProblemBase *>(ctx);
285  NonlinearSystemBase & system = problem.currentNonlinearSystem();
286 
287  // Let's be nice and always check PETSc error codes.
288  PetscErrorCode ierr = 0;
289 
290  // Temporary variables to store SNES tolerances. Usual C-style would be to declare
291  // but not initialize these... but it bothers me to leave anything uninitialized.
292  PetscReal atol = 0.; // absolute convergence tolerance
293  PetscReal rtol = 0.; // relative convergence tolerance
294  PetscReal stol = 0.; // convergence (step) tolerance in terms of the norm of the change in the
295  // solution between steps
296  PetscInt maxit = 0; // maximum number of iterations
297  PetscInt maxf = 0; // maximum number of function evaluations
298 
299  // Ask the SNES object about its tolerances.
300  ierr = SNESGetTolerances(snes, &atol, &rtol, &stol, &maxit, &maxf);
301  CHKERRABORT(problem.comm().get(), ierr);
302 
303  // Ask the SNES object about its divergence tolerance.
304  PetscReal divtol = 0.; // relative divergence tolerance
305 #if !PETSC_VERSION_LESS_THAN(3, 8, 0)
306  ierr = SNESGetDivergenceTolerance(snes, &divtol);
307  CHKERRABORT(problem.comm().get(), ierr);
308 #endif
309 
310  // Get current number of function evaluations done by SNES.
311  PetscInt nfuncs = 0;
312  ierr = SNESGetNumberFunctionEvals(snes, &nfuncs);
313  CHKERRABORT(problem.comm().get(), ierr);
314 
315  // Whether or not to force SNESSolve() take at least one iteration regardless of the initial
316  // residual norm
317 #if !PETSC_VERSION_LESS_THAN(3, 8, 4)
318  PetscBool force_iteration = PETSC_FALSE;
319  ierr = SNESGetForceIteration(snes, &force_iteration);
320  CHKERRABORT(problem.comm().get(), ierr);
321 
322  if (force_iteration && !(problem.getNonlinearForcedIterations()))
323  problem.setNonlinearForcedIterations(1);
324 
325  if (!force_iteration && (problem.getNonlinearForcedIterations()))
326  {
327  ierr = SNESSetForceIteration(snes, PETSC_TRUE);
328  CHKERRABORT(problem.comm().get(), ierr);
329  }
330 #endif
331 
332  // See if SNESSetFunctionDomainError() has been called. Note:
333  // SNESSetFunctionDomainError() and SNESGetFunctionDomainError()
334  // were added in different releases of PETSc.
335  PetscBool domainerror;
336  ierr = SNESGetFunctionDomainError(snes, &domainerror);
337  CHKERRABORT(problem.comm().get(), ierr);
338  if (domainerror)
339  {
340  *reason = SNES_DIVERGED_FUNCTION_DOMAIN;
341  return 0;
342  }
343 
344  // Error message that will be set by the FEProblemBase.
345  std::string msg;
346 
347  // xnorm: 2-norm of current iterate
348  // snorm: 2-norm of current step
349  // fnorm: 2-norm of function at current iterate
350  MooseNonlinearConvergenceReason moose_reason =
351  problem.checkNonlinearConvergence(msg,
352  it,
353  xnorm,
354  snorm,
355  fnorm,
356  rtol,
357  divtol,
358  stol,
359  atol,
360  nfuncs,
361  maxf,
364 
365  if (msg.length() > 0)
366 #if !PETSC_VERSION_LESS_THAN(3, 17, 0)
367  PetscInfo(snes, "%s", msg.c_str());
368 #else
369  PetscInfo(snes, msg.c_str());
370 #endif
371 
372  switch (moose_reason)
373  {
375  *reason = SNES_CONVERGED_ITERATING;
376  break;
377 
379  *reason = SNES_CONVERGED_FNORM_ABS;
380  break;
381 
383  *reason = SNES_CONVERGED_FNORM_RELATIVE;
384  break;
385 
387 #if !PETSC_VERSION_LESS_THAN(3, 8, 0) // A new convergence enum in PETSc 3.8
388  *reason = SNES_DIVERGED_DTOL;
389 #endif
390  break;
391 
393  *reason = SNES_CONVERGED_SNORM_RELATIVE;
394  break;
395 
397  *reason = SNES_DIVERGED_FUNCTION_COUNT;
398  break;
399 
401  *reason = SNES_DIVERGED_FNORM_NAN;
402  break;
403 
405  *reason = SNES_DIVERGED_LINE_SEARCH;
406  break;
407 
409  *reason = SNES_DIVERGED_LOCAL_MIN;
410  break;
411  }
412 
413  return 0;
414 }
const Parallel::Communicator & comm() const
Specialization of SubProblem for solving nonlinear equations plus auxiliary equations.
ierr
auto max(const L &left, const R &right)
Nonlinear system to be solved.
NonlinearSystemBase & currentNonlinearSystem()
virtual MooseNonlinearConvergenceReason checkNonlinearConvergence(std::string &msg, const PetscInt it, const Real xnorm, const Real snorm, const Real fnorm, const Real rtol, const Real divtol, const Real stol, const Real abstol, const PetscInt nfuncs, const PetscInt max_funcs, const Real initial_residual_before_preset_bcs, const Real div_threshold)
Check for convergence of the nonlinear solution.
void setNonlinearForcedIterations(const unsigned int nl_forced_its)
method setting the minimum number of nonlinear iterations before performing divergence checks ...
MooseNonlinearConvergenceReason
Enumeration for nonlinear convergence reasons.
Definition: FEProblemBase.h:98
void * ctx
unsigned int getNonlinearForcedIterations() const
method returning the number of forced nonlinear iterations

◆ petscSetDefaultKSPNormType()

void Moose::PetscSupport::petscSetDefaultKSPNormType ( FEProblemBase problem,
KSP  ksp 
)

Set norm type.

Definition at line 455 of file PetscSupport.C.

Referenced by Moose::SlepcSupport::mooseSlepcEPSSNESKSPSetPCSide(), and petscSetKSPDefaults().

456 {
457  for (const auto i : make_range(problem.numNonlinearSystems()))
458  {
460  KSPSetNormType(ksp, getPetscKSPNormType(nl.getMooseKSPNormType()));
461  }
462 }
KSPNormType getPetscKSPNormType(Moose::MooseKSPNormType kspnorm)
Definition: PetscSupport.C:434
virtual std::size_t numNonlinearSystems() const override
Nonlinear system to be solved.
NonlinearSystemBase & getNonlinearSystemBase(const unsigned int sys_num)
IntRange< T > make_range(T beg, T end)
Moose::MooseKSPNormType getMooseKSPNormType()

◆ petscSetDefaultPCSide()

void Moose::PetscSupport::petscSetDefaultPCSide ( FEProblemBase problem,
KSP  ksp 
)

Setup which side we want to apply preconditioner.

Definition at line 465 of file PetscSupport.C.

Referenced by Moose::SlepcSupport::mooseSlepcEPSSNESKSPSetPCSide(), and petscSetKSPDefaults().

466 {
467  for (const auto i : make_range(problem.numNonlinearSystems()))
468  {
470 
471  // PETSc 3.2.x+
472  if (nl.getPCSide() != Moose::PCS_DEFAULT)
473  KSPSetPCSide(ksp, getPetscPCSide(nl.getPCSide()));
474  }
475 }
virtual std::size_t numNonlinearSystems() const override
Moose::PCSideType getPCSide()
Nonlinear system to be solved.
PCSide getPetscPCSide(Moose::PCSideType pcs)
Definition: PetscSupport.C:417
Use whatever we have in PETSc.
Definition: MooseTypes.h:737
NonlinearSystemBase & getNonlinearSystemBase(const unsigned int sys_num)
IntRange< T > make_range(T beg, T end)

◆ petscSetDefaults()

void Moose::PetscSupport::petscSetDefaults ( FEProblemBase problem)

Sets the default options for PETSc.

Definition at line 500 of file PetscSupport.C.

Referenced by FEProblemBase::initPetscOutputAndSomeSolverSettings(), and Moose::setSolverDefaults().

501 {
502  for (auto nl_index : make_range(problem.numNonlinearSystems()))
503  {
504  // dig out PETSc solver
505  NonlinearSystemBase & nl = problem.getNonlinearSystemBase(nl_index);
506  PetscNonlinearSolver<Number> * petsc_solver =
507  dynamic_cast<PetscNonlinearSolver<Number> *>(nl.nonlinearSolver());
508  SNES snes = petsc_solver->snes();
509  KSP ksp;
510  auto ierr = SNESGetKSP(snes, &ksp);
511  CHKERRABORT(nl.comm().get(), ierr);
512 
513  ierr = SNESSetMaxLinearSolveFailures(snes, 1000000);
514  CHKERRABORT(nl.comm().get(), ierr);
515 
516  ierr = SNESSetCheckJacobianDomainError(snes, PETSC_TRUE);
517  CHKERRABORT(nl.comm().get(), ierr);
518 
519  // In 3.0.0, the context pointer must actually be used, and the
520  // final argument to KSPSetConvergenceTest() is a pointer to a
521  // routine for destroying said private data context. In this case,
522  // we use the default context provided by PETSc in addition to
523  // a few other tests.
524  {
525  ierr = SNESSetConvergenceTest(snes, petscNonlinearConverged, &problem, LIBMESH_PETSC_NULLPTR);
526  CHKERRABORT(nl.comm().get(), ierr);
527  }
528 
529  petscSetKSPDefaults(problem, ksp);
530  }
531 }
virtual NonlinearSolver< Number > * nonlinearSolver()=0
virtual std::size_t numNonlinearSystems() const override
const Parallel::Communicator & comm() const
void petscSetKSPDefaults(FEProblemBase &problem, KSP ksp)
Set the default options for a KSP.
Definition: PetscSupport.C:478
ierr
Nonlinear system to be solved.
NonlinearSystemBase & getNonlinearSystemBase(const unsigned int sys_num)
IntRange< T > make_range(T beg, T end)
PetscErrorCode petscNonlinearConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, void *ctx)
Definition: PetscSupport.C:276

◆ petscSetKSPDefaults()

void Moose::PetscSupport::petscSetKSPDefaults ( FEProblemBase problem,
KSP  ksp 
)

Set the default options for a KSP.

Definition at line 478 of file PetscSupport.C.

Referenced by petscSetDefaults(), and setLinearSolverDefaults().

479 {
480  auto & es = problem.es();
481 
482  PetscReal rtol = es.parameters.get<Real>("linear solver tolerance");
483  PetscReal atol = es.parameters.get<Real>("linear solver absolute tolerance");
484 
485  // MOOSE defaults this to -1 for some dumb reason
486  if (atol < 0)
487  atol = 1e-50;
488 
489  PetscReal maxits = es.parameters.get<unsigned int>("linear solver maximum iterations");
490 
491  // 1e100 is because we don't use divtol currently
492  KSPSetTolerances(ksp, rtol, atol, 1e100, maxits);
493 
494  petscSetDefaultPCSide(problem, ksp);
495 
496  petscSetDefaultKSPNormType(problem, ksp);
497 }
void petscSetDefaultKSPNormType(FEProblemBase &problem, KSP ksp)
Set norm type.
Definition: PetscSupport.C:455
virtual EquationSystems & es() override
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
void petscSetDefaultPCSide(FEProblemBase &problem, KSP ksp)
Setup which side we want to apply preconditioner.
Definition: PetscSupport.C:465

◆ petscSetOptions()

void Moose::PetscSupport::petscSetOptions ( const PetscOptions po,
const SolverParams solver_params 
)

A function for setting the PETSc options in PETSc from the options supplied to MOOSE.

Definition at line 238 of file PetscSupport.C.

Referenced by Moose::SlepcSupport::slepcSetOptions(), and FEProblemBase::solve().

239 {
240 #if PETSC_VERSION_LESS_THAN(3, 7, 0)
241  PetscOptionsClear();
242 #else
243  PetscOptionsClear(LIBMESH_PETSC_NULLPTR);
244 #endif
245 
246  setSolverOptions(solver_params);
247 
248  // Add any additional options specified in the input file
249  for (const auto & flag : po.flags)
250  setSinglePetscOption(flag.rawName().c_str());
251 
252  // Add option pairs
253  for (auto & option : po.pairs)
254  setSinglePetscOption(option.first, option.second);
255 
257 }
void addPetscOptionsFromCommandline()
Definition: PetscSupport.C:220
void setSolverOptions(const SolverParams &solver_params)
Definition: PetscSupport.C:138
void setSinglePetscOption(const std::string &name, const std::string &value="")
A wrapper function for dealing with different versions of PetscOptionsSetValue.
Definition: PetscSupport.C:924

◆ petscSetupDM()

void Moose::PetscSupport::petscSetupDM ( NonlinearSystemBase nl,
const std::string &  dm_name 
)

Setup the PETSc DM object.

Definition at line 175 of file PetscSupport.C.

Referenced by NonlinearSystemBase::setupDM().

176 {
177  PetscErrorCode ierr;
178  PetscBool ismoose;
179  DM dm = LIBMESH_PETSC_NULLPTR;
180 
181  // Initialize the part of the DM package that's packaged with Moose; in the PETSc source tree this
182  // call would be in DMInitializePackage()
184  CHKERRABORT(nl.comm().get(), ierr);
185  // Create and set up the DM that will consume the split options and deal with block matrices.
186  PetscNonlinearSolver<Number> * petsc_solver =
187  dynamic_cast<PetscNonlinearSolver<Number> *>(nl.nonlinearSolver());
188  SNES snes = petsc_solver->snes();
189  // if there exists a DMMoose object, not to recreate a new one
190  ierr = SNESGetDM(snes, &dm);
191  CHKERRABORT(nl.comm().get(), ierr);
192  if (dm)
193  {
194  ierr = PetscObjectTypeCompare((PetscObject)dm, DMMOOSE, &ismoose);
195  CHKERRABORT(nl.comm().get(), ierr);
196  if (ismoose)
197  return;
198  }
199  ierr = DMCreateMoose(nl.comm().get(), nl, dm_name, &dm);
200  CHKERRABORT(nl.comm().get(), ierr);
201  ierr = DMSetFromOptions(dm);
202  CHKERRABORT(nl.comm().get(), ierr);
203  ierr = DMSetUp(dm);
204  CHKERRABORT(nl.comm().get(), ierr);
205  ierr = SNESSetDM(snes, dm);
206  CHKERRABORT(nl.comm().get(), ierr);
207  ierr = DMDestroy(&dm);
208  CHKERRABORT(nl.comm().get(), ierr);
209  // We temporarily comment out this updating function because
210  // we lack an approach to check if the problem
211  // structure has been changed from the last iteration.
212  // The indices will be rebuilt for every timestep.
213  // TODO: figure out a way to check the structure changes of the
214  // matrix
215  // ierr = SNESSetUpdate(snes,SNESUpdateDMMoose);
216  // CHKERRABORT(nl.comm().get(),ierr);
217 }
virtual NonlinearSolver< Number > * nonlinearSolver()=0
const Parallel::Communicator & comm() const
ierr
PetscErrorCode DMCreateMoose(MPI_Comm comm, NonlinearSystemBase &nl, const std::string &dm_name, DM *dm)
Create a MOOSE DM.
PetscErrorCode DMMooseRegisterAll()

◆ petscSetupOutput()

PetscErrorCode Moose::PetscSupport::petscSetupOutput ( CommandLine cmd_line)

Definition at line 260 of file PetscSupport.C.

Referenced by MooseApp::executeExecutioner().

261 {
262  char code[10] = {45, 45, 109, 111, 111, 115, 101};
263  const std::vector<std::string> argv = cmd_line->getArguments();
264  for (const auto & arg : argv)
265  {
266  if (arg.compare(code) == 0)
267  {
269  break;
270  }
271  }
272  return 0;
273 }
static void petscSetupOutput()
Output string for setting up PETSC output.
Definition: Console.C:810
const std::vector< std::string > & getArguments()
Return the raw argv arguments as a vector.
Definition: CommandLine.h:71

◆ processPetscFlags()

void Moose::PetscSupport::processPetscFlags ( const MultiMooseEnum petsc_flags,
PetscOptions petsc_options 
)

Populate flags in a given PetscOptions object using a vector of input arguments.

Parameters
petsc_flagsContainer holding the flags of the petsc options
petsc_optionsData structure which handles petsc options within moose

"-log_summary" cannot be used in the input file. This option needs to be set when PETSc is initialized which happens before the parser is even created. We'll throw an error if somebody attempts to add this option later.

"-log_summary" cannot be used in the input file. This option needs to be set when PETSc is initialized which happens before the parser is even created. We'll throw an error if somebody attempts to add this option later.

Definition at line 594 of file PetscSupport.C.

Referenced by storePetscOptions().

595 {
596  // Update the PETSc single flags
597  for (const auto & option : petsc_flags)
598  {
605  if (option == "-log_summary" || option == "-log_view")
606  mooseError("The PETSc option \"-log_summary\" or \"-log_view\" can only be used on the "
607  "command line. Please "
608  "remove it from the input file");
609 
610  // Warn about superseded PETSc options (Note: -snes is not a REAL option, but people used it in
611  // their input files)
612  else
613  {
614  std::string help_string;
615  if (option == "-snes" || option == "-snes_mf" || option == "-snes_mf_operator")
616  help_string = "Please set the solver type through \"solve_type\".";
617  else if (option == "-ksp_monitor")
618  help_string = "Please use \"Outputs/print_linear_residuals=true\"";
619 
620  if (help_string != "")
621  mooseWarning("The PETSc option ",
622  std::string(option),
623  " should not be used directly in a MOOSE input file. ",
624  help_string);
625  }
626 
627  // Update the stored items, but do not create duplicates
628  if (!po.flags.contains(option))
629  po.flags.push_back(option);
630  }
631 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:296

◆ processPetscPairs()

void Moose::PetscSupport::processPetscPairs ( const std::vector< std::pair< MooseEnumItem, std::string >> &  petsc_pair_options,
const unsigned int  mesh_dimension,
PetscOptions petsc_options 
)

Populate name and value pairs in a given PetscOptions object using vectors of input arguments.

Parameters
petsc_pair_optionsOption-value pairs of petsc settings
mesh_dimensionThe mesh dimension, needed for multigrid settings
petsc_optionsData structure which handles petsc options within moose

Definition at line 634 of file PetscSupport.C.

Referenced by DiffusionPhysicsBase::addPreconditioning(), and storePetscOptions().

637 {
638  // the boolean in these pairs denote whether the user has specified any of the reason flags in the
639  // input file
640  std::array<std::pair<bool, std::string>, 2> reason_flags = {
641  {std::make_pair(false, "-snes_converged_reason"),
642  std::make_pair(false, "-ksp_converged_reason")}};
643 
644  for (auto & reason_flag : reason_flags)
645  if (po.flags.contains(reason_flag.second))
646  // We register the reason option as already existing
647  reason_flag.first = true;
648 
649  // Setup the name value pairs
650  bool boomeramg_found = false;
651  bool strong_threshold_found = false;
652 #if !PETSC_VERSION_LESS_THAN(3, 7, 0)
653  bool superlu_dist_found = false;
654  bool fact_pattern_found = false;
655  bool tiny_pivot_found = false;
656 #endif
657  std::string pc_description = "";
658 #if !PETSC_VERSION_LESS_THAN(3, 12, 0)
659  // If users use HMG, we would like to set
660  bool hmg_found = false;
661  bool matptap_found = false;
662  bool hmg_strong_threshold_found = false;
663 #endif
664 #if !PETSC_VERSION_LESS_THAN(3, 19, 2)
665  // Check for if users have set the options_left option
666  bool options_left_set = false;
667 #endif
668  std::vector<std::pair<std::string, std::string>> new_options;
669 
670  for (const auto & option : petsc_pair_options)
671  {
672  new_options.clear();
673 
674  // Do not add duplicate settings
675  if (MooseUtils::findPair(po.pairs, option.first, MooseUtils::Any) == po.pairs.end())
676  {
677 #if !PETSC_VERSION_LESS_THAN(3, 9, 0)
678  if (option.first == "-pc_factor_mat_solver_package")
679  new_options.emplace_back("-pc_factor_mat_solver_type", option.second);
680 #else
681  if (option.first == "-pc_factor_mat_solver_type")
682  new_options.push_back("-pc_factor_mat_solver_package", option.second);
683 #endif
684 
685  // Look for a pc description
686  if (option.first == "-pc_type" || option.first == "-pc_sub_type" ||
687  option.first == "-pc_hypre_type")
688  pc_description += option.second + ' ';
689 
690 #if !PETSC_VERSION_LESS_THAN(3, 12, 0)
691  if (option.first == "-pc_type" && option.second == "hmg")
692  hmg_found = true;
693 
694  // MPIAIJ for PETSc 3.12.0: -matptap_via
695  // MAIJ for PETSc 3.12.0: -matmaijptap_via
696  // MPIAIJ for PETSc 3.13 to 3.16: -matptap_via, -matproduct_ptap_via
697  // MAIJ for PETSc 3.13 to 3.16: -matproduct_ptap_via
698  // MPIAIJ for PETSc 3.17 and higher: -matptap_via, -mat_product_algorithm
699  // MAIJ for PETSc 3.17 and higher: -mat_product_algorithm
700 #if !PETSC_VERSION_LESS_THAN(3, 17, 0)
701  if (hmg_found && (option.first == "-matptap_via" || option.first == "-matmaijptap_via" ||
702  option.first == "-matproduct_ptap_via"))
703  new_options.emplace_back("-mat_product_algorithm", option.second);
704 #elif !PETSC_VERSION_LESS_THAN(3, 13, 0)
705  if (hmg_found && (option.first == "-matptap_via" || option.first == "-matmaijptap_via"))
706  new_options.emplace_back("-matproduct_ptap_via", option.second);
707 #else
708  if (hmg_found && (option.first == "-matproduct_ptap_via"))
709  {
710  new_options.emplace_back("-matptap_via", option.second);
711  new_options.emplace_back("-matmaijptap_via", option.second);
712  }
713 #endif
714 
715  if (option.first == "-matptap_via" || option.first == "-matmaijptap_via" ||
716  option.first == "-matproduct_ptap_via" || option.first == "-mat_product_algorithm")
717  matptap_found = true;
718 
719  // For 3D problems, we need to set this 0.7
720  if (option.first == "-hmg_inner_pc_hypre_boomeramg_strong_threshold")
721  hmg_strong_threshold_found = true;
722 #endif
723  // This special case is common enough that we'd like to handle it for the user.
724  if (option.first == "-pc_hypre_type" && option.second == "boomeramg")
725  boomeramg_found = true;
726  if (option.first == "-pc_hypre_boomeramg_strong_threshold")
727  strong_threshold_found = true;
728 #if !PETSC_VERSION_LESS_THAN(3, 7, 0)
729  if ((option.first == "-pc_factor_mat_solver_package" ||
730  option.first == "-pc_factor_mat_solver_type") &&
731  option.second == "superlu_dist")
732  superlu_dist_found = true;
733  if (option.first == "-mat_superlu_dist_fact")
734  fact_pattern_found = true;
735  if (option.first == "-mat_superlu_dist_replacetinypivot")
736  tiny_pivot_found = true;
737 #endif
738 
739 #if !PETSC_VERSION_LESS_THAN(3, 19, 2)
740  if (option.first == "-options_left")
741  options_left_set = true;
742 #endif
743 
744  if (!new_options.empty())
745  std::copy(new_options.begin(), new_options.end(), std::back_inserter(po.pairs));
746  else
747  po.pairs.push_back(option);
748  }
749  else
750  {
751  for (unsigned int j = 0; j < po.pairs.size(); j++)
752  if (option.first == po.pairs[j].first)
753  po.pairs[j].second = option.second;
754  }
755  }
756 
757 #if !PETSC_VERSION_LESS_THAN(3, 14, 0)
758  for (const auto & reason_flag : reason_flags)
759  // Was the option already found in PetscOptions::flags? Or does it exist in PetscOptions::pairs
760  // as an iname already? If not, then we add our flag
761  if (!reason_flag.first && (std::find_if(po.pairs.begin(),
762  po.pairs.end(),
763  [&reason_flag](auto & pair) {
764  return pair.first == reason_flag.second;
765  }) == po.pairs.end()))
766  po.pairs.emplace_back(reason_flag.second, "::failed");
767 #endif
768 
769  // When running a 3D mesh with boomeramg, it is almost always best to supply a strong threshold
770  // value. We will provide that for the user here if they haven't supplied it themselves.
771  if (boomeramg_found && !strong_threshold_found && mesh_dimension == 3)
772  {
773  po.pairs.emplace_back("-pc_hypre_boomeramg_strong_threshold", "0.7");
774  pc_description += "strong_threshold: 0.7 (auto)";
775  }
776 
777 #if !PETSC_VERSION_LESS_THAN(3, 12, 0)
778  if (hmg_found && !hmg_strong_threshold_found && mesh_dimension == 3)
779  {
780  po.pairs.emplace_back("-hmg_inner_pc_hypre_boomeramg_strong_threshold", "0.7");
781  pc_description += "strong_threshold: 0.7 (auto)";
782  }
783 
784  // Default PETSc PtAP takes too much memory, and it is not quite useful
785  // Let us switch to use new algorithm
786  if (hmg_found && !matptap_found)
787  {
788 #if !PETSC_VERSION_LESS_THAN(3, 17, 0)
789  po.pairs.emplace_back("-mat_product_algorithm", "allatonce");
790 #elif !PETSC_VERSION_LESS_THAN(3, 13, 0)
791  po.pairs.emplace_back("-matproduct_ptap_via", "allatonce");
792 #else
793  po.pairs.emplace_back("-matptap_via", "allatonce");
794  po.pairs.emplace_back("-matmaijptap_via", "allatonce");
795 #endif
796  }
797 #endif
798 
799 #if !PETSC_VERSION_LESS_THAN(3, 7, 0)
800  // In PETSc-3.7.{0--4}, there is a bug when using superlu_dist, and we have to use
801  // SamePattern_SameRowPerm, otherwise we use whatever we have in PETSc
802  if (superlu_dist_found && !fact_pattern_found)
803  {
804  po.pairs.emplace_back("-mat_superlu_dist_fact",
805 #if PETSC_VERSION_LESS_THAN(3, 7, 5)
806  "SamePattern_SameRowPerm");
807  pc_description += "mat_superlu_dist_fact: SamePattern_SameRowPerm ";
808 #else
809  "SamePattern");
810  pc_description += "mat_superlu_dist_fact: SamePattern ";
811 #endif
812  }
813 
814  // restore this superlu option
815  if (superlu_dist_found && !tiny_pivot_found)
816  {
817  po.pairs.emplace_back("-mat_superlu_dist_replacetinypivot", "1");
818  pc_description += " mat_superlu_dist_replacetinypivot: true ";
819  }
820 #endif
821  // Set Preconditioner description
822  po.pc_description += pc_description;
823 
824  // Turn off default options_left warnings added in 3.19.3 pre-release for all PETSc builds
825  // (PETSc commit: 59f199a7), unless the user has set a preference.
826 #if !PETSC_VERSION_LESS_THAN(3, 19, 2)
827  if (!options_left_set && !po.flags.contains("-options_left"))
828  po.pairs.emplace_back("-options_left", "0");
829 #endif
830 }
C::iterator findPair(C &container, const M1 &first, const M2 &second)
Find a specific pair in a container matching on first, second or both pair components.
Definition: MooseUtils.h:1053
static const struct MooseUtils::AnyType Any

◆ setLinearSolverDefaults()

template<typename T >
void Moose::PetscSupport::setLinearSolverDefaults ( FEProblemBase problem,
LinearSolver< T > &  linear_solver 
)

Set the defaults for a libMesh LinearSolver.

Used in explicit solves

Definition at line 70 of file PetscSupport.h.

Referenced by ExplicitTimeIntegrator::meshChanged().

71 {
72  petscSetKSPDefaults(problem, libMesh::cast_ref<PetscLinearSolver<T> &>(linear_solver).ksp());
73 }
Tnew cast_ref(Told &oldvar)
void petscSetKSPDefaults(FEProblemBase &problem, KSP ksp)
Set the default options for a KSP.
Definition: PetscSupport.C:478

◆ setSinglePetscOption()

void Moose::PetscSupport::setSinglePetscOption ( const std::string &  name,
const std::string &  value = "" 
)

A wrapper function for dealing with different versions of PetscOptionsSetValue.

This is not generally called from MOOSE code, it is instead intended to be called by stuff in MOOSE::PetscSupport.

Definition at line 924 of file PetscSupport.C.

Referenced by Moose::SlepcSupport::clearFreeNonlinearPowerIterations(), petscSetOptions(), Moose::SlepcSupport::setEigenProblemOptions(), Moose::SlepcSupport::setEigenSolverOptions(), Moose::SlepcSupport::setFreeNonlinearPowerIterations(), Moose::SlepcSupport::setNewtonPetscOptions(), Moose::SlepcSupport::setNonlinearPowerOptions(), Moose::SlepcSupport::setSlepcEigenSolverTolerances(), setSolverOptions(), Moose::SlepcSupport::setWhichEigenPairsOptions(), and Moose::SlepcSupport::slepcSetOptions().

925 {
926  PetscErrorCode ierr;
927 
928 #if PETSC_VERSION_LESS_THAN(3, 7, 0)
929  ierr = PetscOptionsSetValue(name.c_str(), value == "" ? LIBMESH_PETSC_NULLPTR : value.c_str());
930 #else
931  // PETSc 3.7.0 and later version. First argument is the options
932  // database to use, NULL indicates the default global database.
933  ierr = PetscOptionsSetValue(
934  LIBMESH_PETSC_NULLPTR, name.c_str(), value == "" ? LIBMESH_PETSC_NULLPTR : value.c_str());
935 #endif
936 
937  // Not convenient to use the usual error checking macro, because we
938  // don't have a specific communicator in this helper function.
939  if (ierr)
940  mooseError("Error setting PETSc option: ", name);
941 }
std::string name(const ElemQuality q)
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
ierr
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)

◆ setSolverOptions()

void Moose::PetscSupport::setSolverOptions ( const SolverParams solver_params)

Definition at line 138 of file PetscSupport.C.

Referenced by petscSetOptions().

139 {
140  // set PETSc options implied by a solve type
141  switch (solver_params._type)
142  {
143  case Moose::ST_PJFNK:
144  setSinglePetscOption("-snes_mf_operator");
145  setSinglePetscOption("-mat_mffd_type", stringify(solver_params._mffd_type));
146  break;
147 
148  case Moose::ST_JFNK:
149  setSinglePetscOption("-snes_mf");
150  setSinglePetscOption("-mat_mffd_type", stringify(solver_params._mffd_type));
151  break;
152 
153  case Moose::ST_NEWTON:
154  break;
155 
156  case Moose::ST_FD:
157  setSinglePetscOption("-snes_fd");
158  break;
159 
160  case Moose::ST_LINEAR:
161  setSinglePetscOption("-snes_type", "ksponly");
162  setSinglePetscOption("-snes_monitor_cancel");
163  break;
164  }
165 
166  Moose::LineSearchType ls_type = solver_params._line_search;
167  if (ls_type == Moose::LS_NONE)
168  ls_type = Moose::LS_BASIC;
169 
170  if (ls_type != Moose::LS_DEFAULT && ls_type != Moose::LS_CONTACT && ls_type != Moose::LS_PROJECT)
171  setSinglePetscOption("-snes_linesearch_type", stringify(ls_type));
172 }
Full Newton Solve.
Definition: MooseTypes.h:759
Moose::LineSearchType _line_search
Definition: SolverParams.h:20
Solving a linear problem.
Definition: MooseTypes.h:761
Moose::MffdType _mffd_type
Definition: SolverParams.h:21
LineSearchType
Type of the line search.
Definition: MooseTypes.h:838
std::string stringify(const MffdType &t)
Definition: PetscSupport.C:123
Jacobian-Free Newton Krylov.
Definition: MooseTypes.h:758
Moose::SolveType _type
Definition: SolverParams.h:19
Use finite differences to compute Jacobian.
Definition: MooseTypes.h:760
Preconditioned Jacobian-Free Newton Krylov.
Definition: MooseTypes.h:757
void setSinglePetscOption(const std::string &name, const std::string &value="")
A wrapper function for dealing with different versions of PetscOptionsSetValue.
Definition: PetscSupport.C:924

◆ storePetscOptions()

void Moose::PetscSupport::storePetscOptions ( FEProblemBase fe_problem,
const InputParameters params 
)

Stores the PETSc options supplied from the InputParameters with MOOSE.

Definition at line 534 of file PetscSupport.C.

Referenced by SetupPreconditionerAction::act(), and FEProblemSolve::FEProblemSolve().

535 {
536  // Note: Options set in the Preconditioner block will override those set in the Executioner block
537  if (params.isParamValid("solve_type") && !params.isParamValid("_use_eigen_value"))
538  {
539  // Extract the solve type
540  const std::string & solve_type = params.get<MooseEnum>("solve_type");
541  fe_problem.solverParams()._type = Moose::stringToEnum<Moose::SolveType>(solve_type);
542  }
543 
544  if (params.isParamValid("line_search"))
545  {
546  MooseEnum line_search = params.get<MooseEnum>("line_search");
547  if (fe_problem.solverParams()._line_search == Moose::LS_INVALID || line_search != "default")
548  {
549  Moose::LineSearchType enum_line_search =
550  Moose::stringToEnum<Moose::LineSearchType>(line_search);
551  fe_problem.solverParams()._line_search = enum_line_search;
552  if (enum_line_search == LS_CONTACT || enum_line_search == LS_PROJECT)
553  for (auto nl_index : make_range(fe_problem.numNonlinearSystems()))
554  {
555  NonlinearImplicitSystem * nl_system = dynamic_cast<NonlinearImplicitSystem *>(
556  &fe_problem.getNonlinearSystemBase(nl_index).system());
557  if (!nl_system)
558  mooseError("You've requested a line search but you must be solving an EigenProblem. "
559  "These two things are not consistent.");
560  PetscNonlinearSolver<Real> * petsc_nonlinear_solver =
561  dynamic_cast<PetscNonlinearSolver<Real> *>(nl_system->nonlinear_solver.get());
562  if (!petsc_nonlinear_solver)
563  mooseError("Currently the MOOSE line searches all use Petsc, so you "
564  "must use Petsc as your non-linear solver.");
565  petsc_nonlinear_solver->linesearch_object =
566  std::make_unique<ComputeLineSearchObjectWrapper>(fe_problem);
567  }
568  }
569  }
570 
571  if (params.isParamValid("mffd_type"))
572  {
573  MooseEnum mffd_type = params.get<MooseEnum>("mffd_type");
574  fe_problem.solverParams()._mffd_type = Moose::stringToEnum<Moose::MffdType>(mffd_type);
575  }
576 
577  // The parameters contained in the Action
578  const auto & petsc_options = params.get<MultiMooseEnum>("petsc_options");
579  const auto & petsc_pair_options =
580  params.get<MooseEnumItem, std::string>("petsc_options_iname", "petsc_options_value");
581 
582  // A reference to the PetscOptions object that contains the settings that will be used in the
583  // solve
585 
586  // First process the single petsc options/flags
587  processPetscFlags(petsc_options, po);
588 
589  // Then process the option-value pairs
590  processPetscPairs(petsc_pair_options, fe_problem.mesh().dimension(), po);
591 }
Moose::PetscSupport::PetscOptions & getPetscOptions()
Retrieve a writable reference the PETSc options (used by PetscSupport)
SolverParams & solverParams()
Get the solver parameters.
virtual std::size_t numNonlinearSystems() const override
Moose::LineSearchType _line_search
Definition: SolverParams.h:20
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
std::vector< std::pair< R1, R2 > > get(const std::string &param1, const std::string &param2) const
Combine two vector parameters into a single vector of pairs.
A struct for storing the various types of petsc options and values.
Definition: PetscSupport.h:38
Moose::MffdType _mffd_type
Definition: SolverParams.h:21
LineSearchType
Type of the line search.
Definition: MooseTypes.h:838
virtual unsigned int dimension() const
Returns MeshBase::mesh_dimension(), (not MeshBase::spatial_dimension()!) of the underlying libMesh me...
Definition: MooseMesh.C:2678
void processPetscPairs(const std::vector< std::pair< MooseEnumItem, std::string >> &petsc_pair_options, const unsigned int mesh_dimension, PetscOptions &petsc_options)
Populate name and value pairs in a given PetscOptions object using vectors of input arguments...
Definition: PetscSupport.C:634
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition: MooseEnum.h:31
Moose::SolveType _type
Definition: SolverParams.h:19
NonlinearSystemBase & getNonlinearSystemBase(const unsigned int sys_num)
void processPetscFlags(const MultiMooseEnum &petsc_flags, PetscOptions &petsc_options)
Populate flags in a given PetscOptions object using a vector of input arguments.
Definition: PetscSupport.C:594
Class for containing MooseEnum item information.
Definition: MooseEnumItem.h:18
virtual System & system() override
Get the reference to the libMesh system.
IntRange< T > make_range(T beg, T end)
virtual MooseMesh & mesh() override
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
means not set
Definition: MooseTypes.h:840
bool isParamValid(const std::string &name) const
This method returns parameters that have been initialized in one fashion or another, i.e.

◆ stringify() [1/2]

std::string Moose::PetscSupport::stringify ( const LineSearchType t)

Definition at line 94 of file PetscSupport.C.

Referenced by setSolverOptions().

95 {
96  switch (t)
97  {
98  case LS_BASIC:
99  return "basic";
100  case LS_DEFAULT:
101  return "default";
102  case LS_NONE:
103  return "none";
104  case LS_SHELL:
105  return "shell";
106  case LS_L2:
107  return "l2";
108  case LS_BT:
109  return "bt";
110  case LS_CP:
111  return "cp";
112  case LS_CONTACT:
113  return "contact";
114  case LS_PROJECT:
115  return "project";
116  case LS_INVALID:
117  mooseError("Invalid LineSearchType");
118  }
119  return "";
120 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
means not set
Definition: MooseTypes.h:840

◆ stringify() [2/2]

std::string Moose::PetscSupport::stringify ( const MffdType t)

Definition at line 123 of file PetscSupport.C.

124 {
125  switch (t)
126  {
127  case MFFD_WP:
128  return "wp";
129  case MFFD_DS:
130  return "ds";
131  case MFFD_INVALID:
132  mooseError("Invalid MffdType");
133  }
134  return "";
135 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
means not set
Definition: MooseTypes.h:857