34#include "libmesh/equation_systems.h"
35#include "libmesh/linear_implicit_system.h"
36#include "libmesh/nonlinear_implicit_system.h"
37#include "libmesh/petsc_linear_solver.h"
38#include "libmesh/petsc_matrix.h"
39#include "libmesh/petsc_nonlinear_solver.h"
40#include "libmesh/petsc_preconditioner.h"
41#include "libmesh/petsc_vector.h"
42#include "libmesh/sparse_matrix.h"
43#include "libmesh/petsc_solver_exception.h"
44#include "libmesh/simple_range.h"
53#include <petscoptions.h>
71 LibmeshPetscCallA(vector.
comm().
get(), VecView(petsc_vec.
vec(), 0));
78 LibmeshPetscCallA(mat.
comm().
get(), MatView(petsc_mat.
mat(), 0));
86 LibmeshPetscCallA(vector.
comm().
get(), VecView(petsc_vec.
vec(), 0));
94 LibmeshPetscCallA(mat.
comm().
get(), MatView(petsc_mat.
mat(), 0));
104#if !PETSC_RELEASE_LESS_THAN(3, 12, 0)
115#if !PETSC_RELEASE_LESS_THAN(3, 12, 0)
127 for (
auto & [_, vec] :
as_range(lm_sys.vectors_begin(), lm_sys.vectors_end()))
129 auto *
const petsc_vec = cast_ptr<PetscVector<Number> *>(vec.get());
130 LibmeshPetscCallA(problem.
comm().
get(), VecSetFromOptions(petsc_vec->vec()));
134 auto * petsc_vec = cast_ptr<PetscVector<Number> *>(lm_sys.
solution.get());
135 LibmeshPetscCallA(problem.
comm().
get(), VecSetFromOptions(petsc_vec->vec()));
137 LibmeshPetscCallA(problem.
comm().
get(), VecSetFromOptions(petsc_vec->vec()));
143 for (
const auto sys_index :
make_range(problem.numSolverSystems()))
144 applySystemVectorTypeOptions(problem, problem.getSolverSystem(sys_index).system());
150petscOptionsHasName(::PetscOptions options,
151 const std::string & name,
152 const std::string & prefix =
"")
154 PetscBool found = PETSC_FALSE;
155 const char *
const prefix_ptr = prefix.empty() ? nullptr : prefix.c_str();
156 LibmeshPetscCallA(PETSC_COMM_WORLD,
157 PetscOptionsHasName(options, prefix_ptr,
name.c_str(), &found));
164 for (
const auto sys_index :
make_range(problem.numSolverSystems()))
165 if (const auto solve_type = problem.solverParams(sys_index)._type;
173mightBeMatTypeOption(
const std::string & name)
175 static constexpr std::string_view mat_type_suffix =
"mat_type";
176 return name.size() >= mat_type_suffix.size() &&
177 std::equal(mat_type_suffix.rbegin(),
178 mat_type_suffix.rend(),
180 [](
const char left,
const char right)
183 return static_cast<int>(left) ==
184 std::tolower(libMesh::cast_int<unsigned char>(right));
189errorOnUnprefixedMatTypeOption(::PetscOptions options,
FEProblemBase & problem)
191 if (!petscOptionsHasName(options,
"-mat_type"))
194 std::string error_string =
195 "Setting option '-mat_type' is not supported without a solver-system prefix. Use an option "
198 if (hasMatrixFreeSolveType(problem))
200 " Attempting to change the matrix "
201 "type for the MFFD matrix type used to represent the Jacobian for (P)JFNK solve "
202 "types is not supported.";
210 const std::optional<std::size_t> system_index = std::nullopt)
212 const auto begin = system_index.value_or(0);
215 for (
const auto sys_index :
make_range(begin, end))
218 auto & lm_sys = solver_system.
system();
224 for (
auto & [_, mat] :
as_range(lm_sys.matrices_begin(), lm_sys.matrices_end()))
229 MatSetOptionsPrefix(petsc_mat->mat(), (solver_system.name() +
"_").c_str()));
230 LibmeshPetscCallA(problem.
comm().
get(), MatSetFromOptions(petsc_mat->mat()));
284 const auto prefix_with_dash =
'-' + solver_params.
_prefix;
286 switch (solver_params.
_type)
290 prefix_with_dash +
"snes_mf_operator");
292 prefix_with_dash +
"mat_mffd_type",
299 prefix_with_dash +
"mat_mffd_type",
312 dont_add_these_options, prefix_with_dash +
"snes_type",
"ksponly");
314 prefix_with_dash +
"snes_monitor_cancel");
324 dont_add_these_options, prefix_with_dash +
"snes_linesearch_type",
stringify(ls_type));
335 LibmeshPetscCallA(PETSC_COMM_WORLD, PetscGetArgs(&argc, &args));
336 std::vector<const char *> cl_args(args + 1, args + argc);
337 const auto cl_argc = libMesh::cast_int<int>(cl_args.size());
339 ::PetscOptions command_line_options;
340 LibmeshPetscCallA(PETSC_COMM_WORLD, PetscOptionsCreate(&command_line_options));
341 LibmeshPetscCallA(PETSC_COMM_WORLD,
342 PetscOptionsInsertArgs(command_line_options, cl_argc, cl_args.data()));
343 LibmeshPetscCallA(PETSC_COMM_WORLD,
344 PetscOptionsInsertArgs(LIBMESH_PETSC_NULLPTR, cl_argc, cl_args.data()));
348 LibmeshPetscCallA(PETSC_COMM_WORLD, PetscOptionsDestroy(&command_line_options));
352 errorOnUnprefixedMatTypeOption(command_line_options, *problem);
357 const bool have_vec_type = petscOptionsHasName(command_line_options,
"-vec_type");
358 bool have_mat_type =
false;
362 have_mat_type = petscOptionsHasName(
369 applyVectorTypeOptions(*problem);
371 applyMatrixTypeOptions(*problem);
373 LibmeshPetscCallA(PETSC_COMM_WORLD, PetscOptionsDestroy(&command_line_options));
380 for (
const auto & flag : po.
flags)
388 for (
auto & option : po.
pairs)
401 PetscCallAbort(PETSC_COMM_WORLD, PetscOptionsClear(LIBMESH_PETSC_NULLPTR));
408 const std::vector<SolverParams> & solver_params_vec,
411 PetscCallAbort(PETSC_COMM_WORLD, PetscOptionsClear(LIBMESH_PETSC_NULLPTR));
412 for (
const auto & solver_params : solver_params_vec)
421 char code[10] = {45, 45, 109, 111, 111, 115, 101};
422 const std::vector<std::string> argv = cmd_line->
getArguments();
423 for (
const auto & arg : argv)
425 if (arg.compare(code) == 0)
440 SNESConvergedReason * reason,
460 status = convergence.checkConvergence(it);
467 *reason = SNES_CONVERGED_ITERATING;
471 *reason = SNES_CONVERGED_FNORM_ABS;
475 *reason = SNES_DIVERGED_DTOL;
484 KSP , PetscInt it, PetscReal , KSPConvergedReason * reason,
void *
ctx)
505 status = convergence.checkConvergence(it);
512 *reason = KSP_CONVERGED_ITERATING;
517#if PETSC_VERSION_LESS_THAN(3, 24, 0)
518 *reason = KSP_CONVERGED_RTOL_NORMAL;
520 *reason = KSP_CONVERGED_RTOL_NORMAL_EQUATIONS;
525 *reason = KSP_DIVERGED_DTOL;
555 return KSP_NORM_NONE;
557 return KSP_NORM_PRECONDITIONED;
559 return KSP_NORM_UNPRECONDITIONED;
561 return KSP_NORM_NATURAL;
563 return KSP_NORM_DEFAULT;
565 mooseError(
"Unknown KSP norm type requested.");
576 LibmeshPetscCallA(problem.
comm().
get(),
597 auto & es = problem.
es();
600 PetscReal atol = es.parameters.get<
Real>(
"linear solver absolute tolerance");
606 PetscReal maxits = es.parameters.get<
unsigned int>(
"linear solver maximum iterations");
609 LibmeshPetscCallA(problem.
comm().
get(), KSPSetTolerances(ksp, rtol, atol, 1e100, maxits));
625 applyMatrixTypeOptions(problem);
632 auto *
const petsc_solver = cast_ptr<PetscNonlinearSolver<Number> *>(nl.
nonlinearSolver());
635 const char * snes_prefix =
nullptr;
636 std::string snes_prefix_str;
640 snes_prefix = snes_prefix_str.c_str();
642 SNES snes = petsc_solver->snes(snes_prefix);
644 LibmeshPetscCallA(nl.
comm().
get(), SNESGetKSP(snes, &ksp));
645 LibmeshPetscCallA(nl.
comm().
get(), SNESSetMaxLinearSolveFailures(snes, 1000000));
646 LibmeshPetscCallA(nl.
comm().
get(), SNESSetCheckJacobianDomainError(snes, PETSC_TRUE));
659 auto *
const petsc_solver =
662 if (lm_lin_sys.prefix_with_name())
663 petsc_solver->
init(lm_lin_sys.prefix().c_str());
665 petsc_solver->init();
668 KSP ksp = petsc_solver->ksp();
688#define checkPrefix(prefix) \
689 mooseAssert(prefix[0] == '-', \
690 "Leading prefix character must be a '-'. Current prefix is '" << prefix << "'"); \
691 mooseAssert((prefix.size() == 1) || (prefix.back() == '_'), \
692 "Terminating prefix character must be a '_'. Current prefix is '" << prefix << "'"); \
693 mooseAssert(MooseUtils::isAllLowercase(prefix), "PETSc prefixes should be all lower-case")
697 const std::string & prefix,
700 const auto & params = param_object.
parameters();
704 const auto & petsc_options = params.get<
MultiMooseEnum>(
"petsc_options");
705 const auto & petsc_pair_options =
706 params.
get<
MooseEnumItem, std::string>(
"petsc_options_iname",
"petsc_options_value");
717 petsc_pair_options, fe_problem.
mesh().
dimension(), prefix, param_object, po);
727 const std::string & solve_type = params.
get<
MooseEnum>(
"solve_type");
729 fe_problem.
solverParams(i).
_type = Moose::stringToEnum<Moose::SolveType>(solve_type);
739 const auto & line_search = params.
get<
MooseEnum>(
"line_search");
744 Moose::stringToEnum<Moose::LineSearchType>(line_search);
751 mooseError(
"You've requested a line search but you must be solving an EigenProblem. "
752 "These two things are not consistent.");
755 if (!petsc_nonlinear_solver)
756 mooseError(
"Currently the MOOSE line searches all use Petsc, so you "
757 "must use Petsc as your non-linear solver.");
759 std::make_unique<ComputeLineSearchObjectWrapper>(fe_problem);
770 const auto & mffd_type = params.
get<
MooseEnum>(
"mffd_type");
780 const auto & string_option =
static_cast<const std::string &
>(option);
781 if (string_option[0] !=
'-')
782 param_object.
mooseError(
"PETSc option '", string_option,
"' does not begin with '-'");
791 prefix.insert(prefix.begin(),
'-');
795 for (
const auto & option : petsc_flags)
799 const std::string & string_option = option.name();
807 if (option ==
"-log_summary" || option ==
"-log_view")
808 mooseError(
"The PETSc option \"-log_summary\" or \"-log_view\" can only be used on the "
809 "command line. Please "
810 "remove it from the input file");
813 const std::string prefixed_option = prefix + string_option.substr(1);
825 prefix.insert(prefix.begin(),
'-');
829#if !PETSC_VERSION_LESS_THAN(3, 14, 0)
832 std::array<std::string, 2> reason_flags = {{
"snes_converged_reason",
"ksp_converged_reason"}};
836 for (
const auto & reason_flag : reason_flags)
838 const auto full_flag = prefix + reason_flag;
839 if (!po.flags.isValueSet(full_flag) && !po.dont_add_these_options.contains(full_flag) &&
840 (std::find_if(po.pairs.begin(),
842 [&full_flag](
auto & pair)
843 { return pair.first == (full_flag); }) == po.pairs.end()))
844 po.
pairs.emplace_back(full_flag,
"::failed");
851 const std::vector<std::pair<MooseEnumItem, std::string>> & petsc_pair_options,
852 const unsigned int mesh_dimension,
857 prefix.insert(prefix.begin(),
'-');
861 bool boomeramg_found =
false;
862 bool strong_threshold_found =
false;
863#if !PETSC_VERSION_LESS_THAN(3, 7, 0)
864 bool superlu_dist_found =
false;
865 bool fact_pattern_found =
false;
866 bool tiny_pivot_found =
false;
868 std::string pc_description =
"";
869#if !PETSC_VERSION_LESS_THAN(3, 12, 0)
871 bool hmg_found =
false;
872 bool matptap_found =
false;
873 bool hmg_strong_threshold_found =
false;
875 std::vector<std::pair<std::string, std::string>> new_options;
877 for (
const auto & [option_name, option_value] : petsc_pair_options)
882 const std::string prefixed_option_name =
883 prefix +
static_cast<const std::string &
>(option_name).substr(1);
887 MooseUtils::findPair(po.
pairs, po.
pairs.begin(), prefixed_option_name, MooseUtils::Any);
888 it == po.
pairs.end())
890#if !PETSC_VERSION_LESS_THAN(3, 9, 0)
891 if (option_name ==
"-pc_factor_mat_solver_package")
892 new_options.emplace_back(prefix +
"pc_factor_mat_solver_type", option_value);
894 if (option_name ==
"-pc_factor_mat_solver_type")
895 new_options.push_back(prefix +
"pc_factor_mat_solver_package", option_value);
899 if (option_name ==
"-pc_type" || option_name ==
"-sub_pc_type" ||
900 option_name ==
"-pc_hypre_type")
901 pc_description += option_value +
' ';
903#if !PETSC_VERSION_LESS_THAN(3, 12, 0)
904 if (option_name ==
"-pc_type" && option_value ==
"hmg")
913#if !PETSC_VERSION_LESS_THAN(3, 17, 0)
914 if (hmg_found && (option_name ==
"-matptap_via" || option_name ==
"-matmaijptap_via" ||
915 option_name ==
"-matproduct_ptap_via"))
916 new_options.emplace_back(prefix +
"mat_product_algorithm", option_value);
917#elif !PETSC_VERSION_LESS_THAN(3, 13, 0)
918 if (hmg_found && (option_name ==
"-matptap_via" || option_name ==
"-matmaijptap_via"))
919 new_options.emplace_back(prefix +
"matproduct_ptap_via", option_value);
921 if (hmg_found && (option_name ==
"-matproduct_ptap_via"))
923 new_options.emplace_back(prefix +
"matptap_via", option_value);
924 new_options.emplace_back(prefix +
"matmaijptap_via", option_value);
928 if (option_name ==
"-matptap_via" || option_name ==
"-matmaijptap_via" ||
929 option_name ==
"-matproduct_ptap_via" || option_name ==
"-mat_product_algorithm")
930 matptap_found =
true;
933 if (option_name ==
"-hmg_inner_pc_hypre_boomeramg_strong_threshold")
934 hmg_strong_threshold_found =
true;
937 if (option_name ==
"-pc_hypre_type" && option_value ==
"boomeramg")
938 boomeramg_found =
true;
939 if (option_name ==
"-pc_hypre_boomeramg_strong_threshold")
940 strong_threshold_found =
true;
941#if !PETSC_VERSION_LESS_THAN(3, 7, 0)
942 if ((option_name ==
"-pc_factor_mat_solver_package" ||
943 option_name ==
"-pc_factor_mat_solver_type") &&
944 option_value ==
"superlu_dist")
945 superlu_dist_found =
true;
946 if (option_name ==
"-mat_superlu_dist_fact")
947 fact_pattern_found =
true;
948 if (option_name ==
"-mat_superlu_dist_replacetinypivot")
949 tiny_pivot_found =
true;
952 if (!new_options.empty())
954 std::copy(new_options.begin(), new_options.end(), std::back_inserter(po.
pairs));
955 for (
const auto & option : new_options)
960 po.
pairs.push_back(std::make_pair(prefixed_option_name, option_value));
968 it->second = option_value;
969 it = MooseUtils::findPair(po.
pairs, std::next(it), prefixed_option_name, MooseUtils::Any);
970 }
while (it != po.
pairs.end());
976 if (boomeramg_found && !strong_threshold_found && mesh_dimension == 3)
978 po.
pairs.emplace_back(prefix +
"pc_hypre_boomeramg_strong_threshold",
"0.7");
979 pc_description +=
"strong_threshold: 0.7 (auto)";
982#if !PETSC_VERSION_LESS_THAN(3, 12, 0)
983 if (hmg_found && !hmg_strong_threshold_found && mesh_dimension == 3)
985 po.
pairs.emplace_back(prefix +
"hmg_inner_pc_hypre_boomeramg_strong_threshold",
"0.7");
986 pc_description +=
"strong_threshold: 0.7 (auto)";
991 if (hmg_found && !matptap_found)
993#if !PETSC_VERSION_LESS_THAN(3, 17, 0)
994 po.
pairs.emplace_back(prefix +
"mat_product_algorithm",
"allatonce");
995#elif !PETSC_VERSION_LESS_THAN(3, 13, 0)
996 po.
pairs.emplace_back(prefix +
"matproduct_ptap_via",
"allatonce");
998 po.
pairs.emplace_back(prefix +
"matptap_via",
"allatonce");
999 po.
pairs.emplace_back(prefix +
"matmaijptap_via",
"allatonce");
1004#if !PETSC_VERSION_LESS_THAN(3, 7, 0)
1007 if (superlu_dist_found && !fact_pattern_found)
1009 po.
pairs.emplace_back(prefix +
"mat_superlu_dist_fact",
1010#
if PETSC_VERSION_LESS_THAN(3, 7, 5)
1011 "SamePattern_SameRowPerm");
1012 pc_description +=
"mat_superlu_dist_fact: SamePattern_SameRowPerm ";
1015 pc_description +=
"mat_superlu_dist_fact: SamePattern ";
1020 if (superlu_dist_found && !tiny_pivot_found)
1022 po.
pairs.emplace_back(prefix +
"mat_superlu_dist_replacetinypivot",
"1");
1023 pc_description +=
" mat_superlu_dist_replacetinypivot: true ";
1027 if (!pc_description.empty() && prefix.size() > 1)
1028 po.
pc_description +=
"[" + prefix.substr(1, prefix.size() - 2) +
"]: ";
1032std::set<std::string>
1035 return {
"default",
"shell",
"none",
"basic",
"l2",
"bt",
"cp"};
1043 MooseEnum solve_type(
"PJFNK JFNK NEWTON FD LINEAR");
1046 "PJFNK: Preconditioned Jacobian-Free Newton Krylov "
1047 "JFNK: Jacobian-Free Newton Krylov "
1048 "NEWTON: Full Newton Solve "
1049 "FD: Use finite differences to compute Jacobian "
1050 "LINEAR: Solving a linear problem");
1055 "Specifies the finite differencing type for "
1056 "Jacobian-free solve types. Note that the "
1057 "default is wp (for Walker and Pernice).");
1063 params.
addParam<std::vector<std::string>>(
1064 "petsc_options_value",
1065 "Values of PETSc name/value pairs (must correspond with \"petsc_options_iname\"");
1066 params.
addParamNamesToGroup(
"solve_type petsc_options petsc_options_iname petsc_options_value "
1077 "-ksp_monitor_snes_lg -snes_ksp_ew -snes_converged_reason "
1078 "-snes_ksp -snes_linesearch_monitor -snes_mf -snes_mf_operator -snes_monitor "
1079 "-snes_test_display -snes_view -snes_monitor_cancel",
1088 "-ksp_converged_reason -ksp_gmres_modifiedgramschmidt -ksp_monitor",
"",
true);
1094 auto options =
MultiMooseEnum(
"-dm_moose_print_embedding -dm_view",
"",
true);
1103 return MultiMooseEnum(
"-snes_atol -snes_linesearch_type -snes_ls -snes_max_it -snes_rtol "
1104 "-snes_divergence_tolerance -snes_type",
1112 return MultiMooseEnum(
"-ksp_atol -ksp_gmres_restart -ksp_max_it -ksp_pc_side -ksp_rtol "
1113 "-ksp_type -sub_ksp_type",
1120 auto options =
MultiMooseEnum(
"-mat_fd_coloring_err -mat_fd_type -mat_mffd_type "
1121 "-pc_asm_overlap -pc_factor_levels "
1122 "-pc_factor_mat_ordering_type -pc_hypre_boomeramg_grid_sweeps_all "
1123 "-pc_hypre_boomeramg_max_iter "
1124 "-pc_hypre_boomeramg_strong_threshold -pc_hypre_type -pc_type "
1140 LibmeshPetscCallA(fe_problem.
comm().
get(), PetscGetArgs(&argc, &args));
1142 std::vector<std::string> cml_arg;
1143 for (
int i = 0; i < argc; i++)
1144 cml_arg.push_back(args[i]);
1146 if (MooseUtils::findPair(petsc.
pairs, petsc.
pairs.begin(), MooseUtils::Any,
"vinewtonssls") ==
1147 petsc.
pairs.end() &&
1148 MooseUtils::findPair(petsc.
pairs, petsc.
pairs.begin(), MooseUtils::Any,
"vinewtonrsls") ==
1149 petsc.
pairs.end() &&
1150 std::find(cml_arg.begin(), cml_arg.end(),
"vinewtonssls") == cml_arg.end() &&
1151 std::find(cml_arg.begin(), cml_arg.end(),
"vinewtonrsls") == cml_arg.end())
1159 const std::string & value ,
1164 LibmeshPetscCallA(comm.
get(),
1165 PetscOptionsSetValue(LIBMESH_PETSC_NULLPTR,
1167 value ==
"" ? LIBMESH_PETSC_NULLPTR : value.c_str()));
1171 ::PetscOptions single_option;
1172 LibmeshPetscCallA(comm.
get(), PetscOptionsCreate(&single_option));
1173 LibmeshPetscCallA(comm.
get(),
1174 PetscOptionsSetValue(single_option,
1176 value ==
"" ? LIBMESH_PETSC_NULLPTR : value.c_str()));
1177 auto check_problem = [problem, &name]()
1181 "Setting the option '",
1183 "' requires passing a 'problem' parameter. Contact a developer of your application "
1184 "to have them update their code. If in doubt, reach out to the MOOSE team on Github "
1189 if (petscOptionsHasName(single_option,
"-vec_type"))
1192 applyVectorTypeOptions(*problem);
1197 else if (problem && mightBeMatTypeOption(name))
1199 errorOnUnprefixedMatTypeOption(single_option, *problem);
1204 if (!petscOptionsHasName(single_option,
"-mat_type", solver_sys_name +
"_"))
1208 mooseError(
"Setting option '", name,
"' is incompatible with a JFNK 'solve_type'");
1210 applyMatrixTypeOptions(*problem, i);
1215 LibmeshPetscCallA(comm.
get(), PetscOptionsDestroy(&single_option));
1220 const std::string & name,
1221 const std::string & value ,
1224 if (!dont_add_these_options.
contains(name))
1231 unsigned int colors,
1232 std::vector<unsigned int> & vertex_colors,
1233 const char * coloring_algorithm)
1237 LibmeshPetscCallA(PETSC_COMM_SELF, MatCreate(PETSC_COMM_SELF, &A));
1238 LibmeshPetscCallA(PETSC_COMM_SELF, MatSetSizes(A, size, size, size, size));
1239 LibmeshPetscCallA(PETSC_COMM_SELF, MatSetType(A, MATSEQDENSE));
1241 LibmeshPetscCallA(PETSC_COMM_SELF, MatSeqDenseSetPreallocation(A, adjacency_matrix));
1242 LibmeshPetscCallA(PETSC_COMM_SELF, MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1243 LibmeshPetscCallA(PETSC_COMM_SELF, MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1246#if PETSC_VERSION_LESS_THAN(3, 7, 0)
1247 LibmeshPetscCallA(PETSC_COMM_SELF, MatConvert(A, MATAIJ, MAT_REUSE_MATRIX, &A));
1249 LibmeshPetscCallA(PETSC_COMM_SELF, MatConvert(A, MATAIJ, MAT_INPLACE_MATRIX, &A));
1252 ISColoring iscoloring;
1254 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringCreate(A, &mc));
1255 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringSetType(mc, coloring_algorithm));
1256 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringSetMaxColors(mc,
static_cast<PetscInt
>(colors)));
1259 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringSetDistance(mc, 1));
1260 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringSetFromOptions(mc));
1261 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringApply(mc, &iscoloring));
1265#if PETSC_RELEASE_LESS_THAN(3, 12, 0)
1266 LibmeshPetscCallA(PETSC_COMM_SELF, ISColoringGetIS(iscoloring, &nn, &
is));
1268 LibmeshPetscCallA(PETSC_COMM_SELF, ISColoringGetIS(iscoloring, PETSC_USE_POINTER, &nn, &
is));
1271 if (nn >
static_cast<PetscInt
>(colors))
1272 throw std::runtime_error(
"Not able to color with designated number of colors");
1274 for (
int i = 0; i < nn; i++)
1277 const PetscInt * indices;
1278 LibmeshPetscCallA(PETSC_COMM_SELF, ISGetLocalSize(
is[i], &isize));
1279 LibmeshPetscCallA(PETSC_COMM_SELF, ISGetIndices(
is[i], &indices));
1280 for (
int j = 0; j < isize; j++)
1282 mooseAssert(indices[j] <
static_cast<PetscInt
>(vertex_colors.size()),
"Index out of bounds");
1283 vertex_colors[indices[j]] = i;
1285 LibmeshPetscCallA(PETSC_COMM_SELF, ISRestoreIndices(
is[i], &indices));
1288 LibmeshPetscCallA(PETSC_COMM_SELF, MatDestroy(&A));
1289 LibmeshPetscCallA(PETSC_COMM_SELF, MatColoringDestroy(&mc));
1290 LibmeshPetscCallA(PETSC_COMM_SELF, ISColoringDestroy(&iscoloring));
1338std::unique_ptr<PetscMatrix<Number>>
1341 const std::string & binary_mat_file,
1342 const unsigned int mat_number_to_load)
1344 LibmeshPetscCallA(comm.
get(), MatCreate(comm.
get(), &mat));
1345 PetscViewer matviewer;
1348 PetscViewerBinaryOpen(comm.
get(), binary_mat_file.c_str(), FILE_MODE_READ, &matviewer));
1349 for (
unsigned int i = 0; i < mat_number_to_load; ++i)
1350 LibmeshPetscCallA(comm.
get(), MatLoad(mat, matviewer));
1351 LibmeshPetscCallA(comm.
get(), PetscViewerDestroy(&matviewer));
1353 return std::make_unique<PetscMatrix<Number>>(mat, comm);
1361 const std::string entry = (!bibtex.empty() && bibtex.back() ==
'\n') ? bibtex : bibtex +
"\n";
1362 LibmeshPetscCallA(PETSC_COMM_WORLD, PetscCitationsRegister(entry.c_str(),
nullptr));
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
const ExecFlagType EXEC_LINEAR_CONVERGENCE
const ExecFlagType EXEC_NONLINEAR_CONVERGENCE
void MooseVecView(NumericVector< Number > &vector)
void MooseMatView(SparseMatrix< Number > &mat)
virtual libMesh::System & system() override
Get the reference to the libMesh system.
This class wraps provides and tracks access to command line parameters.
const std::vector< std::string > & getArguments()
static void petscSetupOutput()
Output string for setting up PETSC output.
MooseConvergenceStatus
Status returned by calls to checkConvergence.
Specialization of SubProblem for solving nonlinear equations plus auxiliary equations.
bool hasLinearConvergenceObjects() const
Whether we have linear convergence objects.
PetscOptions & petscOptionsDatabase()
const std::vector< ConvergenceName > & getNonlinearConvergenceNames() const
Gets the nonlinear system convergence object name(s).
virtual std::size_t numLinearSystems() const override
virtual libMesh::EquationSystems & es() override
AuxiliarySystem & getAuxiliarySystem()
virtual std::size_t numSolverSystems() const override
virtual std::size_t numNonlinearSystems() const override
LinearSystem & currentLinearSystem()
Get a non-constant reference to the current linear system.
bool getFailNextNonlinearConvergenceCheck() const
Whether it will skip further residual evaluations and fail the next nonlinear convergence check(s)
LinearSystem & getLinearSystem(unsigned int sys_num)
Get non-constant reference to a linear system.
SolverParams & solverParams(unsigned int solver_sys_num=0)
Get the solver parameters.
virtual Convergence & getConvergence(const std::string &name, const THREAD_ID tid=0) const
Gets a Convergence object.
bool getFailNextSystemConvergenceCheck() const
Whether it will fail the next system convergence check(s), triggering failed step behavior.
void resetFailNextNonlinearConvergenceCheck()
Tell the problem that the nonlinear convergence check(s) may proceed as normal.
NonlinearSystemBase & currentNonlinearSystem()
virtual MooseMesh & mesh() override
SolverSystem & getSolverSystem(unsigned int sys_num)
Get non-constant reference to a solver system.
std::vector< SolverSystemName > _solver_sys_names
The union of nonlinear and linear system names.
const std::vector< ConvergenceName > & getLinearConvergenceNames() const
Gets the linear convergence object name(s).
virtual void execute(const ExecFlagType &exec_type)
Convenience function for performing execution of MOOSE systems.
Moose::PetscSupport::PetscOptions & getPetscOptions()
Retrieve a writable reference the PETSc options (used by PetscSupport)
NonlinearSystemBase & getNonlinearSystemBase(const unsigned int sys_num)
std::vector< std::shared_ptr< SolverSystem > > _solver_systems
Combined container to base pointer of every solver system.
void resetFailNextSystemConvergenceCheck()
Tell the problem that the system convergence check(s) may proceed as normal.
Linear system to be solved.
libMesh::LinearImplicitSystem & linearImplicitSystem()
Return a reference to the stored linear implicit system.
bool isUltimateMaster() const
Whether or not this app is the ultimate master app.
const InputParameters & parameters() const
Get the parameters of the object.
void mooseError(Args &&... args) const
Emits an error prefixed with object name and type and optionally a file path to the top-level block p...
MooseApp & getMooseApp() const
Get the MooseApp this class is associated with.
std::vector< std::string > getNames() const
Method for returning a vector of all valid enumeration names for this instance.
Class for containing MooseEnum item information.
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
virtual unsigned int dimension() const
Returns MeshBase::mesh_dimension(), (not MeshBase::spatial_dimension()!) of the underlying libMesh me...
bool _pushed
Whether a database was pushed and therefore needs to be popped.
PetscOptionsScope(FEProblemBase &problem)
FEProblemBase & _problem
Problem whose PETSc options database is activated.
A struct for storing the various types of petsc options and values.
MultiMooseEnum dont_add_these_options
Flags to explicitly not set, even if they are specified programmatically.
std::string pc_description
Preconditioner description.
std::vector< std::pair< std::string, std::string > > pairs
PETSc key-value pairs.
MultiMooseEnum user_set_options
Options that are set by the user at the input level.
MultiMooseEnum flags
Single value PETSc options (flags)
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type.
void setAdditionalValue(const std::string &names)
Insert operators Operator to insert (push_back) values into the enum.
bool isValueSet(const std::string &value) const
Methods for seeing if a value is set in the MultiMooseEnum.
unsigned int get(unsigned int i) const
Indexing operator Operator to retrieve the id of an item from the MultiMooseEnum.
bool contains(const std::string &value) const
Methods for seeing if a value is set in the MultiMooseEnum.
Nonlinear system to be solved.
virtual libMesh::NonlinearSolver< Number > * nonlinearSolver()=0
virtual libMesh::System & system() override
Get the reference to the libMesh system.
Base class shared by both Action and MooseObject.
Moose::MffdType _mffd_type
Moose::LineSearchType _line_search
Moose::MooseKSPNormType getMooseKSPNormType()
Get the norm in which the linear convergence is measured.
Moose::PCSideType getPCSide()
Get the current preconditioner side.
unsigned int number() const
Gets the number of this system.
virtual const std::string & name() const
std::unique_ptr< NonlinearSolver< Number > > nonlinear_solver
const Parallel::Communicator & comm() const
const T & get(std::string_view) const
virtual void init(const char *name=nullptr) override
std::unique_ptr< ComputeLineSearchObject > linesearch_object
std::unique_ptr< NumericVector< Number > > current_local_solution
void prefix_with_name(bool value)
std::unique_ptr< NumericVector< Number > > solution
std::string prefix() const
void petscSetOptionsHelper(const PetscOptions &po, FEProblemBase *const problem)
void checkUserProvidedPetscOption(const T &option, const ParallelParamObject ¶m_object)
std::string stringify(const LineSearchType &t)
void dontAddLinearConvergedReason(FEProblemBase &fe_problem)
Function to ensure that -ksp_converged_reason is not added to the PetscOptions storage object to be l...
void petscSetOptions(const PetscOptions &po, const SolverParams &solver_params, FEProblemBase *const problem=nullptr)
A function for setting the PETSc options in PETSc from the options supplied to MOOSE.
void setSolverOptions(const SolverParams &solver_params, const MultiMooseEnum &dont_add_these_options)
PetscErrorCode petscSetupOutput(CommandLine *cmd_line)
void petscSetDefaultKSPNormType(FEProblemBase &problem, KSP ksp)
Set norm type.
void setConvergedReasonFlags(FEProblemBase &fe_problem, std::string prefix)
Set flags that will instruct the user on the reason their simulation diverged from PETSc's perspectiv...
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 al...
PetscErrorCode petscLinearConverged(KSP, PetscInt it, PetscReal, KSPConvergedReason *reason, void *ctx)
void setMFFDTypeFromParams(FEProblemBase &fe_problem, const InputParameters ¶ms)
Sets the FE problem's matrix-free finite difference type from the input params.
void dontAddCommonSNESOptions(FEProblemBase &fe_problem)
Function to ensure that common SNES options are not added to the PetscOptions storage object to be la...
MultiMooseEnum getCommonPetscFlags()
A helper function to produce a MultiMooseEnum with commonly used PETSc single options (flags)
void dontAddPetscFlag(const std::string &flag, PetscOptions &petsc_options)
Function to ensure that a particular petsc option is not added to the PetscOptions storage object to ...
MultiMooseEnum getCommonKSPKeys()
A helper function to produce a MultiMooseEnum with commonly used PETSc ksp option names (keys)
void processSingletonMooseWrappedOptions(FEProblemBase &fe_problem, const InputParameters ¶ms)
Process some MOOSE-wrapped PETSc options.
KSPNormType getPetscKSPNormType(Moose::MooseKSPNormType kspnorm)
bool isSNESVI(FEProblemBase &fe_problem)
check if SNES type is variational inequalities (VI) solver
void petscSetDefaults(FEProblemBase &problem)
Sets the default options for PETSc.
void dontAddCommonKSPOptions(FEProblemBase &fe_problem)
Function to ensure that common KSP options are not added to the PetscOptions storage object to be lat...
void petscSetKSPDefaults(FEProblemBase &problem, KSP ksp)
Set the default options for a KSP.
MultiMooseEnum getCommonSNESKeys()
A helper function to produce a MultiMooseEnum with commonly used PETSc snes option names (keys)
void addPetscOptionsFromCommandline(FEProblemBase *const problem=nullptr)
Insert command-line PETSc options into the active PETSc options database.
MultiMooseEnum getCommonKSPFlags()
A helper function to produce a MultiMooseEnum with commonly used PETSc ksp single options (flags)
void petscSetDefaultPCSide(FEProblemBase &problem, KSP ksp)
Setup which side we want to apply preconditioner.
InputParameters getPetscValidParams()
Returns the PETSc options that are common between Executioners and Preconditioners.
void setSinglePetscOptionIfAppropriate(const MultiMooseEnum &dont_add_these_options, const std::string &name, const std::string &value="", FEProblemBase *const problem=nullptr)
Same as setSinglePetscOption, but does not set the option if it doesn't make sense for the current si...
void registerPetscCitation(const std::string &bibtex)
Register a BibTeX entry with PETSc's citation list so that it is printed (alongside the run-specific ...
void setSinglePetscOption(const std::string &name, const std::string &value="", FEProblemBase *const problem=nullptr)
A wrapper function for dealing with different versions of PetscOptionsSetValue.
PCSide getPetscPCSide(Moose::PCSideType pcs)
std::set< std::string > getPetscValidLineSearches()
Returns the valid petsc line search options as a set of strings.
MultiMooseEnum getCommonSNESFlags()
A helper function to produce a MultiMooseEnum with commonly used PETSc snes single options (flags)
PetscErrorCode petscNonlinearConverged(SNES, PetscInt it, PetscReal, PetscReal, PetscReal, SNESConvergedReason *reason, void *ctx)
void setSolveTypeFromParams(FEProblemBase &fe_problem, const InputParameters ¶ms)
Sets the FE problem's solve type from the input params.
void dontAddNonlinearConvergedReason(FEProblemBase &fe_problem)
Function to ensure that -snes_converged_reason is not added to the PetscOptions storage object to be ...
void storePetscOptions(FEProblemBase &fe_problem, const std::string &prefix, const ParallelParamObject ¶m_object)
Stores the PETSc options supplied from the parameter object on the problem.
MultiMooseEnum getCommonPetscKeys()
A helper function to produce a MultiMooseEnum with commonly used PETSc iname options (keys in key-val...
void setLineSearchFromParams(FEProblemBase &fe_problem, const InputParameters ¶ms)
Sets the FE problem's line search from the input params.
void addPetscFlagsToPetscOptions(const MultiMooseEnum &petsc_flags, std::string prefix, const ParallelParamObject ¶m_object, PetscOptions &petsc_options)
Populate flags in a given PetscOptions object using a vector of input arguments.
std::unique_ptr< PetscMatrix< Number > > createMatrixFromFile(const libMesh::Parallel::Communicator &comm, Mat &petsc_mat, const std::string &binary_mat_file, unsigned int mat_number_to_load=1)
Create a matrix from a binary file.
void addPetscPairsToPetscOptions(const std::vector< std::pair< MooseEnumItem, std::string > > &petsc_pair_options, const unsigned int mesh_dimension, std::string prefix, const ParallelParamObject ¶m_object, PetscOptions &petsc_options)
Populate name and value pairs in a given PetscOptions object using vectors of input arguments.
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
PCSideType
Preconditioning side.
@ PCS_DEFAULT
Use whatever we have in PETSc.
@ ST_FD
Use finite differences to compute Jacobian.
@ ST_LINEAR
Solving a linear problem.
@ ST_NEWTON
Full Newton Solve.
@ ST_JFNK
Jacobian-Free Newton Krylov.
@ ST_PJFNK
Preconditioned Jacobian-Free Newton Krylov.
MooseKSPNormType
Norm type for converge test.
@ KSPN_DEFAULT
Use whatever we have in PETSc.
LineSearchType
Type of the line search.
@ LS_INVALID
means not set
MffdType
Type of the matrix-free finite-differencing parameter.
@ MFFD_INVALID
means not set
std::string name(const ElemQuality q)
const Elem & get(const ElemType type_in)
The following methods are specializations for using the libMesh::Parallel::packed_range_* routines fo...
PetscFunctionReturn(LIBMESH_PETSC_SUCCESS)
SimpleRange< IndexType > as_range(const std::pair< IndexType, IndexType > &p)
auto index_range(const T &sizable)
void libmesh_ignore(const Args &...)
PetscErrorCode PetscInt const PetscInt IS * is
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
IntRange< T > make_range(T beg, T end)