https://mooseframework.inl.gov
FEProblemBase.C
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://mooseframework.inl.gov
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #ifdef MOOSE_KOKKOS_ENABLED
12 #endif
13 
14 #include "FEProblemBase.h"
15 #include "AuxiliarySystem.h"
17 #include "MooseEnum.h"
18 #include "Factory.h"
19 #include "MooseUtils.h"
20 #include "DisplacedProblem.h"
21 #include "SystemBase.h"
22 #include "MaterialData.h"
28 #include "ComputeIndicatorThread.h"
29 #include "ComputeMarkerThread.h"
33 #include "MaxQpsThread.h"
34 #include "ActionWarehouse.h"
35 #include "Conversion.h"
36 #include "Material.h"
37 #include "FunctorMaterial.h"
38 #include "ConstantIC.h"
39 #include "Parser.h"
40 #include "ElementH1Error.h"
41 #include "Function.h"
42 #include "Convergence.h"
43 #include "NonlinearSystem.h"
44 #include "LinearSystem.h"
45 #include "SolverSystem.h"
46 #include "Distribution.h"
47 #include "Sampler.h"
48 #include "PetscSupport.h"
49 #include "RandomInterface.h"
50 #include "RandomData.h"
51 #include "MooseEigenSystem.h"
52 #include "MooseParsedFunction.h"
53 #include "MeshChangedInterface.h"
54 #include "MeshDisplacedInterface.h"
56 #include "ScalarInitialCondition.h"
58 #include "ElementPostprocessor.h"
59 #include "NodalPostprocessor.h"
60 #include "SidePostprocessor.h"
62 #include "InterfacePostprocessor.h"
63 #include "GeneralPostprocessor.h"
69 #include "Positions.h"
70 #include "Indicator.h"
71 #include "Marker.h"
72 #include "MultiApp.h"
73 #include "MultiAppTransfer.h"
74 #include "TransientMultiApp.h"
75 #include "ElementUserObject.h"
76 #include "DomainUserObject.h"
77 #include "NodalUserObject.h"
78 #include "SideUserObject.h"
79 #include "InternalSideUserObject.h"
80 #include "InterfaceUserObject.h"
81 #include "GeneralUserObject.h"
84 #include "Transfer.h"
85 #include "MultiAppTransfer.h"
86 #include "MultiMooseEnum.h"
87 #include "Predictor.h"
88 #include "Assembly.h"
89 #include "Control.h"
90 #include "XFEMInterface.h"
91 #include "ConsoleUtils.h"
92 #include "NonlocalKernel.h"
93 #include "NonlocalIntegratedBC.h"
94 #include "ShapeElementUserObject.h"
95 #include "ShapeSideUserObject.h"
96 #include "MooseVariableFE.h"
97 #include "MooseVariableScalar.h"
99 #include "TimeIntegrator.h"
100 #include "LineSearch.h"
102 #include "MaxVarNDofsPerElem.h"
103 #include "MaxVarNDofsPerNode.h"
104 #include "FVKernel.h"
105 #include "LinearFVKernel.h"
106 #include "FVTimeKernel.h"
107 #include "MooseVariableFV.h"
108 #include "MooseLinearVariableFV.h"
109 #include "FVBoundaryCondition.h"
111 #include "FVInterfaceKernel.h"
112 #include "Reporter.h"
113 #include "ADUtils.h"
114 #include "Executioner.h"
115 #include "VariadicTable.h"
118 #include "NodalBCBase.h"
119 #include "MortarUserObject.h"
120 #include "MortarUserObjectThread.h"
121 #include "RedistributeProperties.h"
122 #include "Checkpoint.h"
125 
126 #include "libmesh/exodusII_io.h"
127 #include "libmesh/quadrature.h"
128 #include "libmesh/coupling_matrix.h"
129 #include "libmesh/nonlinear_solver.h"
130 #include "libmesh/sparse_matrix.h"
131 #include "libmesh/string_to_enum.h"
132 #include "libmesh/fe_interface.h"
133 #include "libmesh/enum_norm_type.h"
134 #include "libmesh/petsc_solver_exception.h"
135 
136 #include "metaphysicl/dualnumber.h"
137 
138 // C++
139 #include <cstring> // for "Jacobian" exception test
140 
141 using namespace libMesh;
142 
143 // Anonymous namespace for helper function
144 namespace
145 {
149 bool
150 sortMooseVariables(const MooseVariableFEBase * a, const MooseVariableFEBase * b)
151 {
152  return a->number() < b->number();
153 }
154 } // namespace
155 
157 
160 {
162  params.addParam<unsigned int>("null_space_dimension", 0, "The dimension of the nullspace");
163  params.addParam<unsigned int>(
164  "transpose_null_space_dimension", 0, "The dimension of the transpose nullspace");
165  params.addParam<unsigned int>(
166  "near_null_space_dimension", 0, "The dimension of the near nullspace");
167  params.addParam<bool>("solve",
168  true,
169  "Whether or not to actually solve the Nonlinear system. "
170  "This is handy in the case that all you want to do is "
171  "execute AuxKernels, Transfers, etc. without actually "
172  "solving anything");
173  params.addParam<bool>("use_nonlinear",
174  true,
175  "Determines whether to use a Nonlinear vs a "
176  "Eigenvalue system (Automatically determined based "
177  "on executioner)");
178  params.addParam<bool>("error_on_jacobian_nonzero_reallocation",
179  "This causes PETSc to error if it had to reallocate memory in the Jacobian "
180  "matrix due to not having enough nonzeros");
181  params.addParam<bool>("ignore_zeros_in_jacobian",
182  false,
183  "Do not explicitly store zero values in "
184  "the Jacobian matrix if true");
185  params.addParam<bool>("force_restart",
186  false,
187  "EXPERIMENTAL: If true, a sub_app may use a "
188  "restart file instead of using of using the master "
189  "backup file");
190  params.addDeprecatedParam<bool>("skip_additional_restart_data",
191  false,
192  "True to skip additional data in equation system for restart.",
193  "This parameter is no longer used, as we do not load additional "
194  "vectors by default with restart");
195  params.addParam<bool>("skip_nl_system_check",
196  false,
197  "True to skip the NonlinearSystem check for work to do (e.g. Make sure "
198  "that there are variables to solve for).");
199  params.addParam<bool>("allow_initial_conditions_with_restart",
200  false,
201  "True to allow the user to specify initial conditions when restarting. "
202  "Initial conditions can override any restarted field");
203 
204  auto coverage_check_description = [](std::string scope, std::string list_param_name)
205  {
206  return "Controls, if and how a " + scope +
207  " subdomain coverage check is performed. "
208  "With 'TRUE' or 'ON' all subdomains are checked (the default). Setting 'FALSE' or 'OFF' "
209  "will disable the check for all subdomains. "
210  "To exclude a predefined set of subdomains 'SKIP_LIST' is to "
211  "be used, while the subdomains to skip are to be defined in the parameter '" +
212  list_param_name +
213  "'. To limit the check to a list of subdomains, 'ONLY_LIST' is to "
214  "be used (again, using the parameter '" +
215  list_param_name + "').";
216  };
217 
218  params.addParam<std::vector<SubdomainName>>(
219  "block",
220  {"ANY_BLOCK_ID"},
221  "List of subdomains for kernel coverage and material coverage checks. Setting this parameter "
222  "is equivalent to setting 'kernel_coverage_block_list' and 'material_coverage_block_list' as "
223  "well as using 'ONLY_LIST' as the coverage check mode.");
224 
225  MooseEnum kernel_coverage_check_modes("FALSE TRUE OFF ON SKIP_LIST ONLY_LIST", "TRUE");
226  params.addParam<MooseEnum>("kernel_coverage_check",
227  kernel_coverage_check_modes,
228  coverage_check_description("kernel", "kernel_coverage_block_list"));
229  params.addParam<std::vector<SubdomainName>>(
230  "kernel_coverage_block_list",
231  {},
232  "List of subdomains for kernel coverage check. The meaning of this list is controlled by the "
233  "parameter 'kernel_coverage_check' (whether this is the list of subdomains to be checked, "
234  "not to be checked or not taken into account).");
235  params.addParam<bool>(
236  "boundary_restricted_node_integrity_check",
237  true,
238  "Set to false to disable checking of boundary restricted nodal object variable dependencies, "
239  "e.g. are the variable dependencies defined on the selected boundaries?");
240  params.addParam<bool>("boundary_restricted_elem_integrity_check",
241  true,
242  "Set to false to disable checking of boundary restricted elemental object "
243  "variable dependencies, e.g. are the variable dependencies defined on the "
244  "selected boundaries?");
245  MooseEnum material_coverage_check_modes("FALSE TRUE OFF ON SKIP_LIST ONLY_LIST", "TRUE");
246  params.addParam<MooseEnum>(
247  "material_coverage_check",
248  material_coverage_check_modes,
249  coverage_check_description("material", "material_coverage_block_list"));
250  params.addParam<std::vector<SubdomainName>>(
251  "material_coverage_block_list",
252  {},
253  "List of subdomains for material coverage check. The meaning of this list is controlled by "
254  "the parameter 'material_coverage_check' (whether this is the list of subdomains to be "
255  "checked, not to be checked or not taken into account).");
256 
257  params.addParam<bool>("fv_bcs_integrity_check",
258  true,
259  "Set to false to disable checking of overlapping Dirichlet and Flux BCs "
260  "and/or multiple DirichletBCs per sideset");
261 
262  params.addParam<bool>(
263  "material_dependency_check", true, "Set to false to disable material dependency check");
264  params.addParam<bool>("parallel_barrier_messaging",
265  false,
266  "Displays messaging from parallel "
267  "barrier notifications when executing "
268  "or transferring to/from Multiapps "
269  "(default: false)");
270 
271  MooseEnum verbosity("false true extra", "false");
272  params.addParam<MooseEnum>("verbose_setup",
273  verbosity,
274  "Set to 'true' to have the problem report on any object created. Set "
275  "to 'extra' to also display all parameters.");
276  params.addParam<bool>("verbose_multiapps",
277  false,
278  "Set to True to enable verbose screen printing related to MultiApps");
279  params.addParam<bool>(
280  "verbose_restore",
281  false,
282  "Set to True to enable verbose screen printing related to solution restoration");
283 
284  params.addParam<FileNameNoExtension>("restart_file_base",
285  "File base name used for restart (e.g. "
286  "<path>/<filebase> or <path>/LATEST to "
287  "grab the latest file available)");
288 
289  params.addParam<std::vector<std::vector<TagName>>>(
290  "extra_tag_vectors",
291  {},
292  "Extra vectors to add to the system that can be filled by objects which compute residuals "
293  "and Jacobians (Kernels, BCs, etc.) by setting tags on them. The outer index is for which "
294  "nonlinear system the extra tag vectors should be added for");
295 
296  params.addParam<std::vector<std::vector<TagName>>>(
297  "not_zeroed_tag_vectors",
298  {},
299  "Extra vector tags which the sytem will not zero when other vector tags are zeroed. "
300  "The outer index is for which nonlinear system the extra tag vectors should be added for");
301 
302  params.addParam<std::vector<std::vector<TagName>>>(
303  "extra_tag_matrices",
304  {},
305  "Extra matrices to add to the system that can be filled "
306  "by objects which compute residuals and Jacobians "
307  "(Kernels, BCs, etc.) by setting tags on them. The outer index is for which "
308  "nonlinear system the extra tag vectors should be added for");
309 
310  params.addParam<std::vector<TagName>>(
311  "extra_tag_solutions",
312  {},
313  "Extra solution vectors to add to the system that can be used by "
314  "objects for coupling variable values stored in them.");
315 
316  params.addParam<bool>("previous_nl_solution_required",
317  false,
318  "True to indicate that this calculation requires a solution vector for "
319  "storing the previous nonlinear iteration.");
320 
321  params.addParam<std::vector<NonlinearSystemName>>(
322  "nl_sys_names", std::vector<NonlinearSystemName>{"nl0"}, "The nonlinear system names");
323 
324  params.addParam<std::vector<LinearSystemName>>("linear_sys_names", {}, "The linear system names");
325 
326  params.addParam<bool>("check_uo_aux_state",
327  false,
328  "True to turn on a check that no state presents during the evaluation of "
329  "user objects and aux kernels");
330 
331  params.addPrivateParam<MooseMesh *>("mesh");
332 
333  params.declareControllable("solve");
334 
335  params.addParam<bool>(
336  "allow_invalid_solution",
337  false,
338  "Set to true to allow convergence even though the solution has been marked as 'invalid'");
339  params.addParam<bool>("show_invalid_solution_console",
340  true,
341  "Set to true to show the invalid solution occurance summary in console");
342  params.addParam<bool>("immediately_print_invalid_solution",
343  false,
344  "Whether or not to report invalid solution warnings at the time the "
345  "warning is produced instead of after the calculation");
346 
347  params.addParam<bool>(
348  "identify_variable_groups_in_nl",
349  true,
350  "Whether to identify variable groups in nonlinear systems. This affects dof ordering");
351 
352  params.addParam<bool>(
353  "regard_general_exceptions_as_errors",
354  false,
355  "If we catch an exception during residual/Jacobian evaluaton for which we don't have "
356  "specific handling, immediately error instead of allowing the time step to be cut");
357 
358  params.addParam<bool>("use_hash_table_matrix_assembly",
359  false,
360  "Whether to assemble matrices using hash tables instead of preallocating "
361  "matrix memory. This can be a good option if the sparsity pattern changes "
362  "throughout the course of the simulation.");
363  params.addParam<bool>(
364  "restore_original_nonzero_pattern",
365  "Whether we should reset matrix memory for every Jacobian evaluation. This option is useful "
366  "if the sparsity pattern is constantly changing and you are using hash table assembly or if "
367  "you wish to continually restore the matrix to the originally preallocated sparsity pattern "
368  "computed by relationship managers.");
369 
370  params.addParamNamesToGroup(
371  "skip_nl_system_check kernel_coverage_check kernel_coverage_block_list "
372  "boundary_restricted_node_integrity_check "
373  "boundary_restricted_elem_integrity_check material_coverage_check "
374  "material_coverage_block_list fv_bcs_integrity_check "
375  "material_dependency_check check_uo_aux_state error_on_jacobian_nonzero_reallocation",
376  "Simulation checks");
377  params.addParamNamesToGroup("use_nonlinear previous_nl_solution_required nl_sys_names "
378  "ignore_zeros_in_jacobian identify_variable_groups_in_nl "
379  "use_hash_table_matrix_assembly restore_original_nonzero_pattern",
380  "Nonlinear system(s)");
381  params.addParamNamesToGroup(
382  "restart_file_base force_restart allow_initial_conditions_with_restart", "Restart");
383  params.addParamNamesToGroup(
384  "verbose_setup verbose_multiapps verbose_restore parallel_barrier_messaging", "Verbosity");
385  params.addParamNamesToGroup(
386  "null_space_dimension transpose_null_space_dimension near_null_space_dimension",
387  "Null space removal");
388  params.addParamNamesToGroup(
389  "extra_tag_vectors extra_tag_matrices extra_tag_solutions not_zeroed_tag_vectors",
390  "Contribution to tagged field data");
391  params.addParamNamesToGroup(
392  "allow_invalid_solution show_invalid_solution_console immediately_print_invalid_solution",
393  "Solution validity control");
394 
395  return params;
396 }
397 
399  : SubProblem(parameters),
400  Restartable(this, "FEProblemBase"),
401  _mesh(*getCheckedPointerParam<MooseMesh *>("mesh")),
402  _req(declareManagedRestartableDataWithContext<RestartableEquationSystems>(
403  "equation_systems", nullptr, _mesh)),
404  _initialized(false),
405  _solve(getParam<bool>("solve")),
406  _transient(false),
407  _time(declareRestartableData<Real>("time")),
408  _time_old(declareRestartableData<Real>("time_old")),
409  _t_step(declareRecoverableData<int>("t_step")),
410  _dt(declareRestartableData<Real>("dt")),
411  _dt_old(declareRestartableData<Real>("dt_old")),
412  _need_to_add_default_nonlinear_convergence(false),
413  _need_to_add_default_multiapp_fixed_point_convergence(false),
414  _need_to_add_default_steady_state_convergence(false),
415  _linear_sys_names(getParam<std::vector<LinearSystemName>>("linear_sys_names")),
416  _num_linear_sys(_linear_sys_names.size()),
417  _linear_systems(_num_linear_sys, nullptr),
418  _current_linear_sys(nullptr),
419  _using_default_nl(!isParamSetByUser("nl_sys_names")),
420  _nl_sys_names(!_using_default_nl || (_using_default_nl && !_linear_sys_names.size())
421  ? getParam<std::vector<NonlinearSystemName>>("nl_sys_names")
422  : std::vector<NonlinearSystemName>()),
423  _num_nl_sys(_nl_sys_names.size()),
424  _nl(_num_nl_sys, nullptr),
425  _current_nl_sys(nullptr),
426  _solver_systems(_num_nl_sys + _num_linear_sys, nullptr),
427  _aux(nullptr),
428  _coupling(Moose::COUPLING_DIAG),
429 #ifdef MOOSE_KOKKOS_ENABLED
430  _kokkos_assembly(*this),
431 #endif
432  _mesh_divisions(/*threaded=*/true),
433  _material_props(declareRestartableDataWithContext<MaterialPropertyStorage>(
434  "material_props", &_mesh, _material_prop_registry, *this)),
435  _bnd_material_props(declareRestartableDataWithContext<MaterialPropertyStorage>(
436  "bnd_material_props", &_mesh, _material_prop_registry, *this)),
437  _neighbor_material_props(declareRestartableDataWithContext<MaterialPropertyStorage>(
438  "neighbor_material_props", &_mesh, _material_prop_registry, *this)),
439 #ifdef MOOSE_KOKKOS_ENABLED
440  _kokkos_material_props(
441  declareRestartableDataWithContext<Moose::Kokkos::MaterialPropertyStorage>(
442  "kokkos_material_props", &_mesh, _material_prop_registry, *this)),
443  _kokkos_bnd_material_props(
444  declareRestartableDataWithContext<Moose::Kokkos::MaterialPropertyStorage>(
445  "kokkos_bnd_material_props", &_mesh, _material_prop_registry, *this)),
446  _kokkos_neighbor_material_props(
447  declareRestartableDataWithContext<Moose::Kokkos::MaterialPropertyStorage>(
448  "kokkos_neighbor_material_props", &_mesh, _material_prop_registry, *this)),
449 #endif
450  _reporter_data(_app),
451  // TODO: delete the following line after apps have been updated to not call getUserObjects
452  _all_user_objects(_app.getExecuteOnEnum()),
453  _multi_apps(_app.getExecuteOnEnum()),
454  _transient_multi_apps(_app.getExecuteOnEnum()),
455  _transfers(_app.getExecuteOnEnum(), /*threaded=*/false),
456  _to_multi_app_transfers(_app.getExecuteOnEnum(), /*threaded=*/false),
457  _from_multi_app_transfers(_app.getExecuteOnEnum(), /*threaded=*/false),
458  _between_multi_app_transfers(_app.getExecuteOnEnum(), /*threaded=*/false),
459 #ifdef LIBMESH_ENABLE_AMR
460  _adaptivity(*this),
461  _cycles_completed(0),
462 #endif
463  _displaced_mesh(nullptr),
464  _geometric_search_data(*this, _mesh),
465  _mortar_data(std::make_unique<MortarInterfaceWarehouse>(*this)),
466  _reinit_displaced_elem(false),
467  _reinit_displaced_face(false),
468  _reinit_displaced_neighbor(false),
469  _input_file_saved(false),
470  _has_dampers(false),
471  _has_constraints(false),
472  _snesmf_reuse_base(true),
473  _skip_exception_check(false),
474  _snesmf_reuse_base_set_by_user(false),
475  _has_initialized_stateful(false),
476  _const_jacobian(false),
477  _has_jacobian(false),
478  _needs_old_newton_iter(false),
479  _previous_nl_solution_required(getParam<bool>("previous_nl_solution_required")),
480  _has_nonlocal_coupling(false),
481  _calculate_jacobian_in_uo(false),
482  _kernel_coverage_check(
483  getParam<MooseEnum>("kernel_coverage_check").getEnum<CoverageCheckMode>()),
484  _kernel_coverage_blocks(getParam<std::vector<SubdomainName>>("kernel_coverage_block_list")),
485  _boundary_restricted_node_integrity_check(
486  getParam<bool>("boundary_restricted_node_integrity_check")),
487  _boundary_restricted_elem_integrity_check(
488  getParam<bool>("boundary_restricted_elem_integrity_check")),
489  _material_coverage_check(
490  getParam<MooseEnum>("material_coverage_check").getEnum<CoverageCheckMode>()),
491  _material_coverage_blocks(getParam<std::vector<SubdomainName>>("material_coverage_block_list")),
492  _fv_bcs_integrity_check(getParam<bool>("fv_bcs_integrity_check")),
493  _material_dependency_check(getParam<bool>("material_dependency_check")),
494  _uo_aux_state_check(getParam<bool>("check_uo_aux_state")),
495  _max_qps(std::numeric_limits<unsigned int>::max()),
496  _max_scalar_order(INVALID_ORDER),
497  _has_time_integrator(false),
498  _has_exception(false),
499  _parallel_barrier_messaging(getParam<bool>("parallel_barrier_messaging")),
500  _verbose_setup(getParam<MooseEnum>("verbose_setup")),
501  _verbose_multiapps(getParam<bool>("verbose_multiapps")),
502  _verbose_restore(getParam<bool>("verbose_restore")),
503  _current_execute_on_flag(EXEC_NONE),
504  _control_warehouse(_app.getExecuteOnEnum(), /*threaded=*/false),
505  _is_petsc_options_inserted(false),
506  _line_search(nullptr),
507  _using_ad_mat_props(false),
508  _current_ic_state(0),
509  _use_hash_table_matrix_assembly(getParam<bool>("use_hash_table_matrix_assembly")),
510  _error_on_jacobian_nonzero_reallocation(
511  isParamValid("error_on_jacobian_nonzero_reallocation")
512  ? getParam<bool>("error_on_jacobian_nonzero_reallocation")
513  : _app.errorOnJacobianNonzeroReallocation()),
514  _restore_original_nonzero_pattern(isParamValid("restore_original_nonzero_pattern")
515  ? getParam<bool>("restore_original_nonzero_pattern")
516  : _use_hash_table_matrix_assembly),
517  _ignore_zeros_in_jacobian(getParam<bool>("ignore_zeros_in_jacobian")),
518  _preserve_matrix_sparsity_pattern(true),
519  _force_restart(getParam<bool>("force_restart")),
520  _allow_ics_during_restart(getParam<bool>("allow_initial_conditions_with_restart")),
521  _skip_nl_system_check(getParam<bool>("skip_nl_system_check")),
522  _fail_next_system_convergence_check(false),
523  _allow_invalid_solution(getParam<bool>("allow_invalid_solution")),
524  _show_invalid_solution_console(getParam<bool>("show_invalid_solution_console")),
525  _immediately_print_invalid_solution(getParam<bool>("immediately_print_invalid_solution")),
526  _started_initial_setup(false),
527  _has_internal_edge_residual_objects(false),
528  _u_dot_requested(false),
529  _u_dotdot_requested(false),
530  _u_dot_old_requested(false),
531  _u_dotdot_old_requested(false),
532  _has_mortar(false),
533  _num_grid_steps(0),
534  _print_execution_on(),
535  _identify_variable_groups_in_nl(getParam<bool>("identify_variable_groups_in_nl")),
536  _regard_general_exceptions_as_errors(getParam<bool>("regard_general_exceptions_as_errors")),
537  _requires_nonlocal_coupling(false)
538 {
539  auto checkCoverageCheckConflict =
540  [this](const std::string & coverage_check,
541  const CoverageCheckMode & coverage_check_mode,
542  const std::vector<SubdomainName> & coverage_blocks) -> void
543  {
544  if (coverage_check_mode != CoverageCheckMode::FALSE &&
545  coverage_check_mode != CoverageCheckMode::OFF)
546  if (coverage_blocks.size() > 1)
547  if (std::find(coverage_blocks.begin(), coverage_blocks.end(), "ANY_BLOCK_ID") !=
548  coverage_blocks.end())
549  paramError(coverage_check,
550  "The list of blocks used for ",
551  coverage_check,
552  " cannot contain 'ANY_BLOCK_ID' along with other blocks. ");
553  };
554 
555  checkCoverageCheckConflict(
556  "kernel_coverage_check", _kernel_coverage_check, _kernel_coverage_blocks);
557  checkCoverageCheckConflict(
558  "material_coverage_check", _material_coverage_check, _material_coverage_blocks);
559 
560  // Initialize static do_derivatives member. We initialize this to true so that all the
561  // default AD things that we setup early in the simulation actually get their derivative
562  // vectors initalized. We will toggle this to false when doing residual evaluations
563  ADReal::do_derivatives = true;
564 
565  // Disable refinement/coarsening in EquationSystems::reinit because we already do this ourselves
567 
569  // Default constructor fine for nonlinear because it will be populated later by framework
570  // executioner/solve object parameters
571  _solver_params.resize(_num_nl_sys);
572  for (const auto i : index_range(_nl_sys_names))
573  {
574  const auto & name = _nl_sys_names[i];
577  _solver_sys_names.push_back(name);
578  }
579 
580  for (const auto i : index_range(_linear_sys_names))
581  {
582  const auto & name = _linear_sys_names[i];
585  _solver_sys_names.push_back(name);
586  // Unlike for nonlinear these are basically dummy parameters
588  }
589 
590  _nonlocal_cm.resize(numSolverSystems());
591  _cm.resize(numSolverSystems());
592 
593  _time = 0.0;
594  _time_old = 0.0;
595  _t_step = 0;
596  _dt = 0;
597  _dt_old = _dt;
598 
599  unsigned int n_threads = libMesh::n_threads();
600 
601  _real_zero.resize(n_threads, 0.);
602  _scalar_zero.resize(n_threads);
603  _zero.resize(n_threads);
604  _phi_zero.resize(n_threads);
605  _ad_zero.resize(n_threads);
606  _grad_zero.resize(n_threads);
607  _ad_grad_zero.resize(n_threads);
608  _grad_phi_zero.resize(n_threads);
609  _second_zero.resize(n_threads);
610  _ad_second_zero.resize(n_threads);
611  _second_phi_zero.resize(n_threads);
612  _point_zero.resize(n_threads);
613  _vector_zero.resize(n_threads);
616 
618 
622 
623  es().parameters.set<FEProblemBase *>("_fe_problem_base") = this;
624 
625  if (isParamValid("restart_file_base"))
626  {
627  std::string restart_file_base = getParam<FileNameNoExtension>("restart_file_base");
628 
629  // This check reverts to old behavior of providing "restart_file_base=" to mean
630  // don't restart... BISON currently relies on this. It could probably be removed.
631  // The new MooseUtils::convertLatestCheckpoint will error out if a checkpoint file
632  // is not found, which I think makes sense. Which means, without this, if you
633  // set "restart_file_base=", you'll get a "No checkpoint file found" error
634  if (restart_file_base.size())
635  {
636  restart_file_base = MooseUtils::convertLatestCheckpoint(restart_file_base);
637  setRestartFile(restart_file_base);
638  }
639  }
640 
641  // // Generally speaking, the mesh is prepared for use, and consequently remote elements are deleted
642  // // well before our Problem(s) are constructed. Historically, in MooseMesh we have a bunch of
643  // // needs_prepare type flags that make it so we never call prepare_for_use (and consequently
644  // // delete_remote_elements) again. So the below line, historically, has had no impact. HOWEVER:
645  // // I've added some code in SetupMeshCompleteAction for deleting remote elements post
646  // // EquationSystems::init. If I execute that code without default ghosting, then I get > 40 MOOSE
647  // // test failures, so we clearly have some simulations that are not yet covered properly by
648  // // relationship managers. Until that is resolved, I am going to retain default geometric ghosting
649  // if (!_default_ghosting)
650  // _mesh.getMesh().remove_ghosting_functor(_mesh.getMesh().default_ghosting());
651 
652 #if !PETSC_RELEASE_LESS_THAN(3, 12, 0)
653  // Main app should hold the default database to handle system petsc options
654  if (!_app.isUltimateMaster())
655  LibmeshPetscCall(PetscOptionsCreate(&_petsc_option_data_base));
656 #endif
657 
658  if (!_solve)
659  {
660  // If we are not solving, we do not care about seeing unused petsc options
661  Moose::PetscSupport::setSinglePetscOption("-options_left", "0");
662  // We don't want petscSetOptions being called in solve and clearing the option that was just set
664  }
665 }
666 
667 const MooseMesh &
668 FEProblemBase::mesh(bool use_displaced) const
669 {
670  if (use_displaced && !_displaced_problem)
671  mooseWarning("Displaced mesh was requested but the displaced problem does not exist. "
672  "Regular mesh will be returned");
673  return ((use_displaced && _displaced_problem) ? _displaced_problem->mesh() : mesh());
674 }
675 
676 void
678 {
679  // add vectors and their tags to system
680  auto & vectors = getParam<std::vector<std::vector<TagName>>>("extra_tag_vectors");
681  for (const auto sys_num : index_range(vectors))
682  for (auto & vector : vectors[sys_num])
683  {
684  auto tag = addVectorTag(vector);
685  _solver_systems[sys_num]->addVector(tag, false, libMesh::GHOSTED);
686  }
687 
688  auto & not_zeroed_vectors = getParam<std::vector<std::vector<TagName>>>("not_zeroed_tag_vectors");
689  for (const auto sys_num : index_range(not_zeroed_vectors))
690  for (auto & vector : not_zeroed_vectors[sys_num])
691  {
692  auto tag = addVectorTag(vector);
693  _solver_systems[sys_num]->addVector(tag, false, GHOSTED);
695  }
696 }
697 
698 void
700 {
701  auto & matrices = getParam<std::vector<std::vector<TagName>>>("extra_tag_matrices");
702  for (const auto sys_num : index_range(matrices))
703  for (auto & matrix : matrices[sys_num])
704  {
705  auto tag = addMatrixTag(matrix);
706  _solver_systems[sys_num]->addMatrix(tag);
707  }
708 
709  for (auto & sys : _solver_systems)
710  sys->sizeVariableMatrixData();
711  _aux->sizeVariableMatrixData();
712 }
713 
714 void
716 {
717  for (auto & vector : getParam<std::vector<TagName>>("extra_tag_solutions"))
718  {
719  auto tag = addVectorTag(vector, Moose::VECTOR_TAG_SOLUTION);
720  for (auto & sys : _solver_systems)
721  sys->addVector(tag, false, libMesh::GHOSTED);
722  _aux->addVector(tag, false, libMesh::GHOSTED);
723  }
724 
726  {
727  // We'll populate the zeroth state of the nonlinear iterations with the current solution for
728  // ease of use in doing things like copying solutions backwards. We're just storing pointers in
729  // the solution states containers so populating the zeroth state does not cost us the memory of
730  // a new vector
732  }
733 
735  for (auto & sys : _solver_systems)
736  sys->associateVectorToTag(*sys->system().current_local_solution.get(), tag);
737  _aux->associateVectorToTag(*_aux->system().current_local_solution.get(), tag);
738 }
739 
740 void
742 {
743  for (auto & sys : _solver_systems)
744  sys->needSolutionState(state, iteration_type);
745  _aux->needSolutionState(state, iteration_type);
746 }
747 
748 void
749 FEProblemBase::newAssemblyArray(std::vector<std::shared_ptr<SolverSystem>> & solver_systems)
750 {
751  unsigned int n_threads = libMesh::n_threads();
752 
753  _assembly.resize(n_threads);
754  for (const auto i : make_range(n_threads))
755  {
756  _assembly[i].resize(solver_systems.size());
757  for (const auto j : index_range(solver_systems))
758  _assembly[i][j] = std::make_unique<Assembly>(*solver_systems[j], i);
759  }
760 }
761 
762 void
764  std::vector<std::shared_ptr<NonlinearSystemBase>> & nls)
765 {
766  TIME_SECTION("initNullSpaceVectors", 5, "Initializing Null Space Vectors");
767 
768  unsigned int dimNullSpace = parameters.get<unsigned int>("null_space_dimension");
769  unsigned int dimTransposeNullSpace =
770  parameters.get<unsigned int>("transpose_null_space_dimension");
771  unsigned int dimNearNullSpace = parameters.get<unsigned int>("near_null_space_dimension");
772  for (unsigned int i = 0; i < dimNullSpace; ++i)
773  {
774  std::ostringstream oss;
775  oss << "_" << i;
776  // do not project, since this will be recomputed, but make it ghosted, since the near nullspace
777  // builder might march over all nodes
778  for (auto & nl : nls)
779  nl->addVector("NullSpace" + oss.str(), false, libMesh::GHOSTED);
780  }
781  _subspace_dim["NullSpace"] = dimNullSpace;
782  for (unsigned int i = 0; i < dimTransposeNullSpace; ++i)
783  {
784  std::ostringstream oss;
785  oss << "_" << i;
786  // do not project, since this will be recomputed, but make it ghosted, since the near nullspace
787  // builder might march over all nodes
788  for (auto & nl : nls)
789  nl->addVector("TransposeNullSpace" + oss.str(), false, libMesh::GHOSTED);
790  }
791  _subspace_dim["TransposeNullSpace"] = dimTransposeNullSpace;
792  for (unsigned int i = 0; i < dimNearNullSpace; ++i)
793  {
794  std::ostringstream oss;
795  oss << "_" << i;
796  // do not project, since this will be recomputed, but make it ghosted, since the near-nullspace
797  // builder might march over all semilocal nodes
798  for (auto & nl : nls)
799  nl->addVector("NearNullSpace" + oss.str(), false, libMesh::GHOSTED);
800  }
801  _subspace_dim["NearNullSpace"] = dimNearNullSpace;
802 }
803 
805 {
806  // Flush the Console stream, the underlying call to Console::mooseConsole
807  // relies on a call to Output::checkInterval that has references to
808  // _time, etc. If it is not flushed here memory problems arise if you have
809  // an unflushed stream and start destructing things.
810  _console << std::flush;
811 
812  unsigned int n_threads = libMesh::n_threads();
813  for (unsigned int i = 0; i < n_threads; i++)
814  {
815  _zero[i].release();
816  _phi_zero[i].release();
817  _scalar_zero[i].release();
818  _grad_zero[i].release();
819  _grad_phi_zero[i].release();
820  _second_zero[i].release();
821  _second_phi_zero[i].release();
822  _vector_zero[i].release();
823  _vector_curl_zero[i].release();
824  _ad_zero[i].release();
825  _ad_grad_zero[i].release();
826  _ad_second_zero[i].release();
827  }
828 
829 #if !PETSC_RELEASE_LESS_THAN(3, 12, 0)
830  if (!_app.isUltimateMaster())
831  {
832  auto ierr = PetscOptionsDestroy(&_petsc_option_data_base);
833  // Don't throw on destruction
834  CHKERRABORT(this->comm().get(), ierr);
835  }
836 #endif
837 }
838 
839 void
840 FEProblemBase::setCoordSystem(const std::vector<SubdomainName> & blocks,
841  const MultiMooseEnum & coord_sys)
842 {
843  TIME_SECTION("setCoordSystem", 5, "Setting Coordinate System");
844  _mesh.setCoordSystem(blocks, coord_sys);
845 }
846 
847 void
849 {
850  _mesh.setAxisymmetricCoordAxis(rz_coord_axis);
851 }
852 
853 const ConstElemRange &
855 {
857  {
858  std::vector<const DofMap *> dof_maps(es().n_systems());
859  for (const auto i : make_range(es().n_systems()))
860  {
861  const auto & sys = es().get_system(i);
862  dof_maps[i] = &sys.get_dof_map();
863  }
865  std::make_unique<ConstElemRange>(_mesh.getMesh().multi_evaluable_elements_begin(dof_maps),
866  _mesh.getMesh().multi_evaluable_elements_end(dof_maps));
867  }
869 }
870 
871 const ConstElemRange &
873 {
875  {
876  std::vector<const DofMap *> dof_maps(_nl.size());
877  for (const auto i : index_range(dof_maps))
878  dof_maps[i] = &_nl[i]->dofMap();
880  std::make_unique<ConstElemRange>(_mesh.getMesh().multi_evaluable_elements_begin(dof_maps),
881  _mesh.getMesh().multi_evaluable_elements_end(dof_maps));
882  }
883 
885 }
886 
887 void
889 {
890  TIME_SECTION("initialSetup", 2, "Performing Initial Setup");
891 
893 
895  mooseError("Checkpoint recovery and restart and exodus restart are all mutually exclusive.");
896 
898  mooseWarning("MOOSE may fail to catch an exception when the \"skip_exception_check\" parameter "
899  "is used. If you receive a terse MPI error during execution, remove this "
900  "parameter and rerun your simulation");
901 
902  // set state flag indicating that we are in or beyond initialSetup.
903  // This can be used to throw errors in methods that _must_ be called at construction time.
904  _started_initial_setup = true;
906 
907  // Setup the solution states (current, old, etc) in each system based on
908  // its default and the states requested of each of its variables
909  for (const auto i : index_range(_solver_systems))
910  {
911  _solver_systems[i]->initSolutionState();
912  if (getDisplacedProblem())
913  getDisplacedProblem()->solverSys(i).initSolutionState();
914  }
915  _aux->initSolutionState();
916  if (getDisplacedProblem())
917  getDisplacedProblem()->auxSys().initSolutionState();
918 
919  // always execute to get the max number of DoF per element and node needed to initialize phi_zero
920  // variables
921  dof_id_type global_max_var_n_dofs_per_elem = 0;
922  for (const auto i : index_range(_solver_systems))
923  {
924  auto & sys = *_solver_systems[i];
925  dof_id_type max_var_n_dofs_per_elem;
926  dof_id_type max_var_n_dofs_per_node;
927  {
928  TIME_SECTION("computingMaxDofs", 3, "Computing Max Dofs Per Element");
929 
930  MaxVarNDofsPerElem mvndpe(*this, sys);
931  Threads::parallel_reduce(*_mesh.getActiveLocalElementRange(), mvndpe);
932  max_var_n_dofs_per_elem = mvndpe.max();
933  _communicator.max(max_var_n_dofs_per_elem);
934 
935  MaxVarNDofsPerNode mvndpn(*this, sys);
936  Threads::parallel_reduce(*_mesh.getLocalNodeRange(), mvndpn);
937  max_var_n_dofs_per_node = mvndpn.max();
938  _communicator.max(max_var_n_dofs_per_node);
939  global_max_var_n_dofs_per_elem =
940  std::max(global_max_var_n_dofs_per_elem, max_var_n_dofs_per_elem);
941  }
942 
943  {
944  TIME_SECTION("assignMaxDofs", 5, "Assigning Maximum Dofs Per Elem");
945 
946  sys.assignMaxVarNDofsPerElem(max_var_n_dofs_per_elem);
948  if (displaced_problem)
949  displaced_problem->solverSys(i).assignMaxVarNDofsPerElem(max_var_n_dofs_per_elem);
950 
951  sys.assignMaxVarNDofsPerNode(max_var_n_dofs_per_node);
952  if (displaced_problem)
953  displaced_problem->solverSys(i).assignMaxVarNDofsPerNode(max_var_n_dofs_per_node);
954  }
955  }
956 
957  {
958  TIME_SECTION("resizingVarValues", 5, "Resizing Variable Values");
959 
960  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
961  {
962  _phi_zero[tid].resize(global_max_var_n_dofs_per_elem, std::vector<Real>(getMaxQps(), 0.));
963  _grad_phi_zero[tid].resize(global_max_var_n_dofs_per_elem,
964  std::vector<RealGradient>(getMaxQps(), RealGradient(0.)));
965  _second_phi_zero[tid].resize(global_max_var_n_dofs_per_elem,
966  std::vector<RealTensor>(getMaxQps(), RealTensor(0.)));
967  }
968  }
969 
970  // Set up stateful material property redistribution, if we suspect
971  // it may be necessary later.
973 
975  {
976  // Only load all of the vectors if we're recovering
978 
979  // This forces stateful material property loading to be an exact one-to-one match
980  if (_app.isRecovering())
981  {
983  props->setRecovering();
984 
985 #ifdef MOOSE_KOKKOS_ENABLED
986  for (auto props :
988  props->setRecovering();
989 #endif
990  }
991 
992  TIME_SECTION("restore", 3, "Restoring from backup");
993 
994  // We could have a cached backup when this app is a sub-app and has been given a Backup
995  if (!_app.hasInitialBackup())
997  else
999 
1005  if (_app.isRestarting())
1006  {
1007  if (_app.hasStartTime())
1009  else
1010  _time_old = _time;
1011  }
1012  }
1013  else
1014  {
1016 
1017  if (reader)
1018  {
1019  TIME_SECTION("copyingFromExodus", 3, "Copying Variables From Exodus");
1020 
1021  for (auto & sys : _solver_systems)
1022  sys->copyVars(*reader);
1023  _aux->copyVars(*reader);
1024  }
1025  else
1026  {
1027  if (_solver_systems[0]->hasVarCopy() || _aux->hasVarCopy())
1028  mooseError("Need Exodus reader to restart variables but the reader is not available\n"
1029  "Use either FileMesh with an Exodus mesh file or FileMeshGenerator with an "
1030  "Exodus mesh file and with use_for_exodus_restart equal to true");
1031  }
1032  }
1033 
1034  // Perform output related setups
1036 
1037  // Flush all output to _console that occur during construction and initialization of objects
1039 
1040  // Build Refinement and Coarsening maps for stateful material projections if necessary
1041  if ((_adaptivity.isOn() || _num_grid_steps) &&
1044  {
1046  mooseError("Stateful neighbor material properties do not work with mesh adaptivity");
1047 
1049  }
1050 
1051  if (!_app.isRecovering())
1052  {
1059  {
1060  if (!_app.isUltimateMaster())
1061  mooseError(
1062  "Doing extra refinements when restarting is NOT supported for sub-apps of a MultiApp");
1063 
1065  }
1066  }
1067 
1068  unsigned int n_threads = libMesh::n_threads();
1069 
1070  // Convergence initial setup
1071  {
1072  TIME_SECTION("convergenceInitialSetup", 5, "Initializing Convergence objects");
1073 
1074  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1076  }
1077 
1078  // UserObject initialSetup
1079  std::set<std::string> depend_objects_ic = _ics.getDependObjects();
1080  std::set<std::string> depend_objects_aux = _aux->getDependObjects();
1081 
1082  // This replaces all prior updateDependObjects calls on the old user object warehouses.
1083  TheWarehouse::Query uo_query = theWarehouse().query().condition<AttribSystem>("UserObject");
1084  std::vector<UserObject *> userobjs;
1085  uo_query.queryInto(userobjs);
1087  theWarehouse(), getAuxiliarySystem(), _app.getExecuteOnEnum(), userobjs, depend_objects_ic);
1088 
1089  std::map<int, std::vector<UserObject *>> group_userobjs;
1090  for (auto obj : userobjs)
1091  group_userobjs[obj->getParam<int>("execution_order_group")].push_back(obj);
1092 
1093  for (auto & [group, objs] : group_userobjs)
1094  for (auto obj : objs)
1095  obj->initialSetup();
1096 
1097  // check if jacobian calculation is done in userobject
1098  for (THREAD_ID tid = 0; tid < n_threads; ++tid)
1100 
1101  // Check whether nonlocal couling is required or not
1105 
1106  {
1107  TIME_SECTION("initializingFunctions", 5, "Initializing Functions");
1108 
1109  // Call the initialSetup methods for functions
1110  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1111  {
1112  reinitScalars(tid); // initialize scalars so they are properly sized for use as input into
1113  // ParsedFunctions
1114  _functions.initialSetup(tid);
1115  }
1116 
1117 #ifdef MOOSE_KOKKOS_ENABLED
1119 #endif
1120  }
1121 
1122  {
1123  TIME_SECTION("initializingRandomObjects", 5, "Initializing Random Objects");
1124 
1125  // Random interface objects
1126  for (const auto & it : _random_data_objects)
1127  it.second->updateSeeds(EXEC_INITIAL);
1128  }
1129 
1130  if (!_app.isRecovering())
1131  {
1133 
1134  {
1135  TIME_SECTION("ICinitialSetup", 5, "Setting Up Initial Conditions");
1136 
1137  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1138  _ics.initialSetup(tid);
1139 
1141  }
1142 
1143  projectSolution();
1144  }
1145 
1146  // Materials
1148  {
1149  TIME_SECTION("materialInitialSetup", 3, "Setting Up Materials");
1150 
1151  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1152  {
1153  // Sort the Material objects, these will be actually computed by MOOSE in reinit methods.
1154  _materials.sort(tid);
1156 
1157  // Call initialSetup on all material objects
1159 
1160  // Discrete materials may insert additional dependencies on materials during the initial
1161  // setup. Therefore we resolve the dependencies once more, now with the additional
1162  // dependencies due to discrete materials.
1164  {
1165  _materials.sort(tid);
1167  }
1168  }
1169 
1170 #ifdef MOOSE_KOKKOS_ENABLED
1171  _kokkos_materials.sort(0, true);
1172 #endif
1173 
1174  {
1175  TIME_SECTION("computingInitialStatefulProps", 3, "Computing Initial Material Values");
1176 
1178 
1182 #ifdef MOOSE_KOKKOS_ENABLED
1187 #endif
1188  }
1189  }
1190 
1191  // setRestartInPlace() is set because the property maps have now been setup and we can
1192  // dataLoad() them directly in place
1193  // setRecovering() is set because from now on we require a one-to-one mapping of
1194  // stateful properties because we shouldn't be declaring any more
1196  {
1197  props->setRestartInPlace();
1198  props->setRecovering();
1199  }
1200 
1201  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1202  {
1205  _markers.sort(tid);
1206  _markers.initialSetup(tid);
1207  }
1208 
1209 #ifdef LIBMESH_ENABLE_AMR
1210 
1211  if (!_app.isRecovering())
1212  {
1213  unsigned int n = adaptivity().getInitialSteps();
1214  if (n && !_app.isUltimateMaster() && _app.isRestarting())
1215  mooseError("Cannot perform initial adaptivity during restart on sub-apps of a MultiApp!");
1216 
1217  initialAdaptMesh();
1218  }
1219 
1220 #endif // LIBMESH_ENABLE_AMR
1221 
1222  if (!_app.isRecovering() && !_app.isRestarting())
1223  {
1224  // During initial setup the solution is copied to the older solution states (old, older, etc)
1226 
1227  // Check if there are old state initial conditions
1228  auto ics = _ics.getActiveObjects();
1229  auto fv_ics = _fv_ics.getActiveObjects();
1230  auto scalar_ics = _scalar_ics.getActiveObjects();
1231  unsigned short ic_state_max = 0;
1232 
1233  auto findMax = [&ic_state_max](const auto & obj_list)
1234  {
1235  for (auto ic : obj_list.getActiveObjects())
1236  ic_state_max = std::max(ic_state_max, ic->getState());
1237  };
1238  findMax(_ics);
1239  findMax(_fv_ics);
1240  findMax(_scalar_ics);
1241 
1242  // if there are old state ICs, compute them and write to old states accordingly
1243  if (ic_state_max > 0)
1244  {
1245  // state 0 copy (we'll overwrite current state when evaluating ICs and need to restore it once
1246  // we're done with the old/older state ICs)
1247  std::vector<std::unique_ptr<NumericVector<Real>>> state0_sys_buffers(_solver_systems.size());
1248  std::unique_ptr<NumericVector<Real>> state0_aux_buffer;
1249 
1250  // save state 0
1251  for (const auto i : index_range(_solver_systems))
1252  state0_sys_buffers[i] = _solver_systems[i]->solutionState(0).clone();
1253 
1254  state0_aux_buffer = _aux->solutionState(0).clone();
1255 
1256  // compute old state ICs
1257  for (_current_ic_state = 1; _current_ic_state <= ic_state_max; _current_ic_state++)
1258  {
1259  projectSolution();
1260 
1261  for (auto & sys : _solver_systems)
1262  sys->solutionState(_current_ic_state) = sys->solutionState(0);
1263 
1264  _aux->solutionState(_current_ic_state) = _aux->solutionState(0);
1265  }
1266  _current_ic_state = 0;
1267 
1268  // recover state 0
1269  for (const auto i : index_range(_solver_systems))
1270  {
1271  _solver_systems[i]->solutionState(0) = *state0_sys_buffers[i];
1272  _solver_systems[i]->solutionState(0).close();
1273  _solver_systems[i]->update();
1274  }
1275  _aux->solutionState(0) = *state0_aux_buffer;
1276  _aux->solutionState(0).close();
1277  _aux->update();
1278  }
1279  }
1280 
1281  if (!_app.isRecovering())
1282  {
1283  if (haveXFEM())
1284  updateMeshXFEM();
1285  }
1286 
1287  // Call initialSetup on the solver systems
1288  for (auto & sys : _solver_systems)
1289  sys->initialSetup();
1290 
1291  // Auxilary variable initialSetup calls
1292  _aux->initialSetup();
1293 
1294  if (_displaced_problem)
1295  // initialSetup for displaced systems
1296  _displaced_problem->initialSetup();
1297 
1298  for (auto & sys : _solver_systems)
1299  sys->setSolution(*(sys->system().current_local_solution.get()));
1300 
1301  // Update the nearest node searches (has to be called after the problem is all set up)
1302  // We do this here because this sets up the Element's DoFs to ghost
1304 
1306  if (_displaced_mesh)
1308 
1309  // We need to move the mesh in order to build a map between mortar secondary and primary
1310  // interfaces. This map will then be used by the AgumentSparsityOnInterface ghosting functor to
1311  // know which dofs we need ghosted when we call EquationSystems::reinit
1312  if (_displaced_problem && _mortar_data->hasDisplacedObjects())
1313  {
1314  _displaced_problem->updateMesh();
1315  // if displacements were applied to the mesh, the mortar mesh should be updated too
1316  updateMortarMesh();
1317  }
1318 
1319  // Possibly reinit one more time to get ghosting correct
1321 
1322  if (_displaced_mesh)
1323  _displaced_problem->updateMesh();
1324 
1325  updateGeomSearch(); // Call all of the rest of the geometric searches
1326 
1327  for (auto & sys : _solver_systems)
1328  {
1329  const auto & tis = sys->getTimeIntegrators();
1330 
1331  {
1332  TIME_SECTION("timeIntegratorInitialSetup", 5, "Initializing Time Integrator");
1333  for (auto & ti : tis)
1334  ti->initialSetup();
1335  }
1336  }
1337 
1338  // HUGE NOTE: MultiApp initialSetup() MUST... I repeat MUST be _after_ main-app restartable data
1339  // has been restored
1340 
1341  // Call initialSetup on the MultiApps
1342  if (_multi_apps.hasObjects())
1343  {
1344  TIME_SECTION("initialSetupMultiApps", 2, "Initializing MultiApps", false);
1346  }
1347 
1348  // Call initialSetup on the transfers
1349  {
1350  TIME_SECTION("initialSetupTransfers", 2, "Initializing Transfers");
1351 
1353 
1354  // Call initialSetup on the MultiAppTransfers to be executed on TO_MULTIAPP
1355  const auto & to_multi_app_objects = _to_multi_app_transfers.getActiveObjects();
1356  for (const auto & transfer : to_multi_app_objects)
1357  {
1358  transfer->setCurrentDirection(Transfer::DIRECTION::TO_MULTIAPP);
1359  transfer->initialSetup();
1360  }
1361 
1362  // Call initialSetup on the MultiAppTransfers to be executed on FROM_MULTIAPP
1363  const auto & from_multi_app_objects = _from_multi_app_transfers.getActiveObjects();
1364  for (const auto & transfer : from_multi_app_objects)
1365  {
1366  transfer->setCurrentDirection(Transfer::DIRECTION::FROM_MULTIAPP);
1367  transfer->initialSetup();
1368  }
1369 
1370  // Call initialSetup on the MultiAppTransfers to be executed on BETWEEN_MULTIAPP
1371  const auto & between_multi_app_objects = _between_multi_app_transfers.getActiveObjects();
1372  for (const auto & transfer : between_multi_app_objects)
1373  {
1374  transfer->setCurrentDirection(Transfer::DIRECTION::BETWEEN_MULTIAPP);
1375  transfer->initialSetup();
1376  }
1377  }
1378 
1380  {
1381  TIME_SECTION("BoundaryRestrictedNodeIntegrityCheck", 5);
1382 
1383  // check that variables are defined along boundaries of boundary restricted nodal objects
1384  ConstBndNodeRange & bnd_nodes = *mesh().getBoundaryNodeRange();
1385  BoundaryNodeIntegrityCheckThread bnict(*this, uo_query);
1386  Threads::parallel_reduce(bnd_nodes, bnict);
1387 
1388  // Nodal bcs aren't threaded
1389  const auto & node_to_elem_map = _mesh.nodeToActiveSemilocalElemMap();
1390  for (const auto & bnode : bnd_nodes)
1391  {
1392  const auto boundary_id = bnode->_bnd_id;
1393  const Node * const node = bnode->_node;
1394 
1395  if (node->processor_id() != this->processor_id())
1396  continue;
1397 
1398  // Only check vertices. Variables may not be defined on non-vertex nodes (think first order
1399  // Lagrange on a second order mesh) and user-code can often handle that
1400  const Elem * const an_elem =
1401  _mesh.getMesh().elem_ptr(libmesh_map_find(node_to_elem_map, node->id()).front());
1402  if (!an_elem->is_vertex(an_elem->get_node_index(node)))
1403  continue;
1404 
1405  const auto & bnd_name = _mesh.getBoundaryName(boundary_id);
1406 
1407  for (auto & nl : _nl)
1408  {
1409  const auto & nodal_bcs = nl->getNodalBCWarehouse();
1410  if (!nodal_bcs.hasBoundaryObjects(boundary_id, 0))
1411  continue;
1412 
1413  const auto & bnd_objects = nodal_bcs.getBoundaryObjects(boundary_id, 0);
1414  for (const auto & bnd_object : bnd_objects)
1415  // Skip if this object uses geometric search because coupled variables may be defined on
1416  // paired boundaries instead of the boundary this node is on
1417  if (!bnd_object->requiresGeometricSearch() &&
1418  bnd_object->checkVariableBoundaryIntegrity())
1419  {
1420  std::set<MooseVariableFieldBase *> vars_to_omit = {
1421  &static_cast<MooseVariableFieldBase &>(
1422  const_cast<MooseVariableBase &>(bnd_object->variable()))};
1423 
1425  *bnd_object, bnd_object->checkAllVariables(*node, vars_to_omit), bnd_name);
1426  }
1427  }
1428  }
1429  }
1430 
1432  {
1433  TIME_SECTION("BoundaryRestrictedElemIntegrityCheck", 5);
1434 
1435  // check that variables are defined along boundaries of boundary restricted elemental objects
1436  ConstBndElemRange & bnd_elems = *mesh().getBoundaryElementRange();
1437  BoundaryElemIntegrityCheckThread beict(*this, uo_query);
1438  Threads::parallel_reduce(bnd_elems, beict);
1439  }
1440 
1441  if (!_app.isRecovering())
1442  {
1444 
1446  if (!converged)
1447  mooseError("failed to converge initial MultiApp");
1448 
1449  // We'll backup the Multiapp here
1451 
1452  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1453  reinitScalars(tid);
1454 
1456 
1457  // The FEProblemBase::execute method doesn't call all the systems on EXEC_INITIAL, but it does
1458  // set/unset the current flag. Therefore, this resets the current flag to EXEC_INITIAL so that
1459  // subsequent calls (e.g., executeControls) have the proper flag.
1461  }
1462 
1463  // Here we will initialize the stateful properties once more since they may have been updated
1464  // during initialSetup by calls to computeProperties.
1465  //
1466  // It's really bad that we don't allow this during restart. It means that we can't add new
1467  // stateful materials
1468  // during restart. This is only happening because this _has_ to be below initial userobject
1469  // execution.
1470  // Otherwise this could be done up above... _before_ restoring restartable data... which would
1471  // allow you to have
1472  // this happen during restart. I honestly have no idea why this has to happen after initial user
1473  // object computation.
1474  // THAT is something we should fix... so I've opened this ticket: #5804
1475  if (!_app.isRecovering() && !_app.isRestarting())
1476  {
1479  {
1480  TIME_SECTION("computeMaterials", 2, "Computing Initial Material Properties");
1481 
1483  }
1484 #ifdef MOOSE_KOKKOS_ENABLED
1488  {
1489  TIME_SECTION("computeMaterials", 2, "Computing Initial Material Properties");
1490 
1492  }
1493 #endif
1494  }
1495 
1496  // Control Logic
1498 
1499  // Scalar variables need to reinited for the initial conditions to be available for output
1500  for (unsigned int tid = 0; tid < n_threads; tid++)
1501  reinitScalars(tid);
1502 
1503  if (_displaced_mesh)
1504  _displaced_problem->syncSolutions();
1505 
1506  // Writes all calls to _console from initialSetup() methods
1508 
1510  {
1512  for (THREAD_ID tid = 0; tid < n_threads; ++tid)
1513  for (auto & assembly : _assembly[tid])
1515  }
1516 
1517  {
1518  TIME_SECTION("lineSearchInitialSetup", 5, "Initializing Line Search");
1519 
1520  if (_line_search)
1521  _line_search->initialSetup();
1522  }
1523 
1524  // Perform Reporter get/declare check
1526 
1527  // We do this late to allow objects to get late restartable data
1530 
1532 }
1533 
1534 void
1536 {
1537  for (const auto & pp : _reporter_data.getPostprocessorNames())
1538  if (hasScalarVariable(pp))
1539  mooseError("Postprocessor \"" + pp +
1540  "\" has the same name as a scalar variable in the system.");
1541 }
1542 
1543 void
1545 {
1547 
1548  if (_t_step > 1 && _num_grid_steps)
1549  {
1550  libMesh::MeshRefinement mesh_refinement(_mesh);
1551  std::unique_ptr<libMesh::MeshRefinement> displaced_mesh_refinement(nullptr);
1552  if (_displaced_mesh)
1553  displaced_mesh_refinement = std::make_unique<libMesh::MeshRefinement>(*_displaced_mesh);
1554 
1555  for (MooseIndex(_num_grid_steps) i = 0; i < _num_grid_steps; ++i)
1556  {
1557  if (_displaced_problem)
1558  // If the DisplacedProblem is active, undisplace the DisplacedMesh in preparation for
1559  // refinement. We can't safely refine the DisplacedMesh directly, since the Hilbert keys
1560  // computed on the inconsistenly-displaced Mesh are different on different processors,
1561  // leading to inconsistent Hilbert keys. We must do this before the undisplaced Mesh is
1562  // coarsensed, so that the element and node numbering is still consistent. We also have to
1563  // make sure this is done during every step of coarsening otherwise different partitions
1564  // will be generated for the reference and displaced meshes (even for replicated)
1565  _displaced_problem->undisplaceMesh();
1566 
1567  mesh_refinement.uniformly_coarsen();
1568  if (_displaced_mesh)
1569  displaced_mesh_refinement->uniformly_coarsen();
1570 
1571  // Mark this as an intermediate change because we do not yet want to reinit_systems. E.g. we
1572  // need things to happen in the following order for the undisplaced problem:
1573  // u1) EquationSystems::reinit_solutions. This will restrict the solution vectors and then
1574  // contract the mesh
1575  // u2) MooseMesh::meshChanged. This will update the node/side lists and other
1576  // things which needs to happen after the contraction
1577  // u3) GeometricSearchData::reinit. Once the node/side lists are updated we can perform our
1578  // geometric searches which will aid in determining sparsity patterns
1579  //
1580  // We do these things for the displaced problem (if it exists)
1581  // d1) EquationSystems::reinit. Restrict the displaced problem vector copies and then contract
1582  // the mesh. It's safe to do a full reinit with the displaced because there are no
1583  // matrices that sparsity pattern calculations will be conducted for
1584  // d2) MooseMesh::meshChanged. This will update the node/side lists and other
1585  // things which needs to happen after the contraction
1586  // d3) UpdateDisplacedMeshThread::operator(). Re-displace the mesh using the *displaced*
1587  // solution vector copy because we don't know the state of the reference solution vector.
1588  // It's safe to use the displaced copy because we are outside of a non-linear solve,
1589  // and there is no concern about differences between solution and current_local_solution
1590  // d4) GeometricSearchData::reinit. With the node/side lists updated and the mesh
1591  // re-displaced, we can perform our geometric searches, which will aid in determining the
1592  // sparsity pattern of the matrix held by the libMesh::ImplicitSystem held by the
1593  // NonlinearSystem held by this
1594  meshChanged(
1595  /*intermediate_change=*/true, /*contract_mesh=*/true, /*clean_refinement_flags=*/true);
1596  }
1597 
1598  // u4) Now that all the geometric searches have been done (both undisplaced and displaced),
1599  // we're ready to update the sparsity pattern
1600  es().reinit_systems();
1601  }
1602 
1603  if (_line_search)
1604  _line_search->timestepSetup();
1605 
1606  // Random interface objects
1607  for (const auto & it : _random_data_objects)
1608  it.second->updateSeeds(EXEC_TIMESTEP_BEGIN);
1609 
1610  unsigned int n_threads = libMesh::n_threads();
1611  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1612  {
1615  }
1616 
1617 #ifdef MOOSE_KOKKOS_ENABLED
1619 #endif
1620 
1621  _aux->timestepSetup();
1622  for (auto & sys : _solver_systems)
1623  sys->timestepSetup();
1624 
1625  if (_displaced_problem)
1626  // timestepSetup for displaced systems
1627  _displaced_problem->timestepSetup();
1628 
1629  for (THREAD_ID tid = 0; tid < n_threads; tid++)
1630  {
1633  _markers.timestepSetup(tid);
1634  }
1635 
1636  std::vector<UserObject *> userobjs;
1637  theWarehouse().query().condition<AttribSystem>("UserObject").queryIntoUnsorted(userobjs);
1638  for (auto obj : userobjs)
1639  obj->timestepSetup();
1640 
1641  // Timestep setup of output objects
1643 
1646  _has_nonlocal_coupling = true;
1647 }
1648 
1649 unsigned int
1651 {
1653  mooseError("Max QPS uninitialized");
1654  return _max_qps;
1655 }
1656 
1657 Order
1659 {
1660  return _max_scalar_order;
1661 }
1662 
1663 void
1665 {
1666  TIME_SECTION("checkNonlocalCoupling", 5, "Checking Nonlocal Coupling");
1667 
1668  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
1669  for (auto & nl : _nl)
1670  {
1671  const auto & all_kernels = nl->getKernelWarehouse();
1672  const auto & kernels = all_kernels.getObjects(tid);
1673  for (const auto & kernel : kernels)
1674  {
1675  std::shared_ptr<NonlocalKernel> nonlocal_kernel =
1677  if (nonlocal_kernel)
1678  {
1681  _nonlocal_kernels.addObject(kernel, tid);
1682  }
1683  }
1684  const MooseObjectWarehouse<IntegratedBCBase> & all_integrated_bcs =
1685  nl->getIntegratedBCWarehouse();
1686  const auto & integrated_bcs = all_integrated_bcs.getObjects(tid);
1687  for (const auto & integrated_bc : integrated_bcs)
1688  {
1689  std::shared_ptr<NonlocalIntegratedBC> nonlocal_integrated_bc =
1691  if (nonlocal_integrated_bc)
1692  {
1695  _nonlocal_integrated_bcs.addObject(integrated_bc, tid);
1696  }
1697  }
1698  }
1699 }
1700 
1701 void
1703 {
1704  std::set<const MooseVariableFEBase *> uo_jacobian_moose_vars;
1705  {
1706  std::vector<ShapeElementUserObject *> objs;
1707  theWarehouse()
1708  .query()
1710  .condition<AttribThread>(tid)
1711  .queryInto(objs);
1712 
1713  for (const auto & uo : objs)
1714  {
1715  _calculate_jacobian_in_uo = uo->computeJacobianFlag();
1716  const auto & mv_deps = uo->jacobianMooseVariables();
1717  uo_jacobian_moose_vars.insert(mv_deps.begin(), mv_deps.end());
1718  }
1719  }
1720  {
1721  std::vector<ShapeSideUserObject *> objs;
1722  theWarehouse()
1723  .query()
1725  .condition<AttribThread>(tid)
1726  .queryInto(objs);
1727  for (const auto & uo : objs)
1728  {
1729  _calculate_jacobian_in_uo = uo->computeJacobianFlag();
1730  const auto & mv_deps = uo->jacobianMooseVariables();
1731  uo_jacobian_moose_vars.insert(mv_deps.begin(), mv_deps.end());
1732  }
1733  }
1734 
1735  _uo_jacobian_moose_vars[tid].assign(uo_jacobian_moose_vars.begin(), uo_jacobian_moose_vars.end());
1736  std::sort(
1737  _uo_jacobian_moose_vars[tid].begin(), _uo_jacobian_moose_vars[tid].end(), sortMooseVariables);
1738 }
1739 
1740 void
1741 FEProblemBase::setVariableAllDoFMap(const std::vector<const MooseVariableFEBase *> & moose_vars)
1742 {
1743  for (unsigned int i = 0; i < moose_vars.size(); ++i)
1744  {
1745  VariableName var_name = moose_vars[i]->name();
1746  auto & sys = _solver_systems[moose_vars[i]->sys().number()];
1747  sys->setVariableGlobalDoFs(var_name);
1748  _var_dof_map[var_name] = sys->getVariableGlobalDoFs();
1749  }
1750 }
1751 
1752 void
1753 FEProblemBase::prepare(const Elem * elem, const THREAD_ID tid)
1754 {
1755  for (const auto i : index_range(_solver_systems))
1756  {
1757  _assembly[tid][i]->reinit(elem);
1758  _solver_systems[i]->prepare(tid);
1759 
1760  if (i < _num_nl_sys)
1761  {
1762  // This method is called outside of residual/Jacobian callbacks during initial condition
1763  // evaluation
1765  _assembly[tid][i]->prepareJacobianBlock();
1766  _assembly[tid][i]->prepareResidual();
1768  _assembly[tid][i]->prepareNonlocal();
1769  }
1770  }
1771  _aux->prepare(tid);
1772 
1773  if (_displaced_problem &&
1774  // _reinit_displaced_neighbor applies to interface type objects which will do computations
1775  // based on both elem and neighbor. Consequently, despite what you might think by its name, we
1776  // must make sure we prepare the displaced elem
1778  {
1779  _displaced_problem->prepare(_displaced_mesh->elemPtr(elem->id()), tid);
1781  _displaced_problem->prepareNonlocal(tid);
1782  }
1783 }
1784 
1785 void
1787 {
1788  for (auto & nl : _nl)
1789  nl->prepareFace(tid, true);
1790  _aux->prepareFace(tid, false);
1791 
1793  _displaced_problem->prepareFace(_displaced_mesh->elemPtr(elem->id()), tid);
1794 }
1795 
1796 void
1797 FEProblemBase::prepare(const Elem * elem,
1798  unsigned int ivar,
1799  unsigned int jvar,
1800  const std::vector<dof_id_type> & dof_indices,
1801  const THREAD_ID tid)
1802 {
1803  for (const auto i : index_range(_nl))
1804  {
1805  _assembly[tid][i]->reinit(elem);
1806  _nl[i]->prepare(tid);
1807  }
1808 
1809  _aux->prepare(tid);
1810  const auto current_nl_sys_num = _current_nl_sys->number();
1811  _assembly[tid][current_nl_sys_num]->prepareBlock(ivar, jvar, dof_indices);
1813  if (_nonlocal_cm[current_nl_sys_num](ivar, jvar) != 0)
1814  {
1815  MooseVariableFEBase & jv = _current_nl_sys->getVariable(tid, jvar);
1816  _assembly[tid][current_nl_sys_num]->prepareBlockNonlocal(
1817  ivar, jvar, dof_indices, jv.allDofIndices());
1818  }
1819 
1821  {
1822  _displaced_problem->prepare(_displaced_mesh->elemPtr(elem->id()), ivar, jvar, dof_indices, tid);
1824  if (_nonlocal_cm[current_nl_sys_num](ivar, jvar) != 0)
1825  {
1826  MooseVariableFEBase & jv = _current_nl_sys->getVariable(tid, jvar);
1827  _displaced_problem->prepareBlockNonlocal(ivar, jvar, dof_indices, jv.allDofIndices(), tid);
1828  }
1829  }
1830 }
1831 
1832 void
1834 {
1835  SubdomainID did = elem->subdomain_id();
1836  for (const auto i : index_range(_solver_systems))
1837  {
1838  _assembly[tid][i]->setCurrentSubdomainID(did);
1839  if (_displaced_problem &&
1841  _displaced_problem->assembly(tid, i).setCurrentSubdomainID(did);
1842  }
1843 }
1844 
1845 void
1846 FEProblemBase::setNeighborSubdomainID(const Elem * elem, unsigned int side, const THREAD_ID tid)
1847 {
1848  SubdomainID did = elem->neighbor_ptr(side)->subdomain_id();
1849  for (const auto i : index_range(_nl))
1850  {
1851  _assembly[tid][i]->setCurrentNeighborSubdomainID(did);
1852  if (_displaced_problem &&
1854  _displaced_problem->assembly(tid, i).setCurrentNeighborSubdomainID(did);
1855  }
1856 }
1857 
1858 void
1859 FEProblemBase::setNeighborSubdomainID(const Elem * elem, const THREAD_ID tid)
1860 {
1861  SubdomainID did = elem->subdomain_id();
1862  for (const auto i : index_range(_nl))
1863  {
1864  _assembly[tid][i]->setCurrentNeighborSubdomainID(did);
1865  if (_displaced_problem &&
1867  _displaced_problem->assembly(tid, i).setCurrentNeighborSubdomainID(did);
1868  }
1869 }
1870 
1871 void
1873 {
1874  _assembly[tid][_current_nl_sys->number()]->prepare();
1876  _assembly[tid][_current_nl_sys->number()]->prepareNonlocal();
1877 
1879  {
1880  _displaced_problem->prepareAssembly(tid);
1882  _displaced_problem->prepareNonlocal(tid);
1883  }
1884 }
1885 
1886 void
1888 {
1889  _assembly[tid][_current_nl_sys->number()]->addResidual(Assembly::GlobalDataKey{},
1891 
1892  if (_displaced_problem)
1893  _displaced_problem->addResidual(tid);
1894 }
1895 
1896 void
1898 {
1899  _assembly[tid][_current_nl_sys->number()]->addResidualNeighbor(Assembly::GlobalDataKey{},
1901 
1902  if (_displaced_problem)
1903  _displaced_problem->addResidualNeighbor(tid);
1904 }
1905 
1906 void
1908 {
1909  _assembly[tid][_current_nl_sys->number()]->addResidualLower(Assembly::GlobalDataKey{},
1911 
1912  if (_displaced_problem)
1913  _displaced_problem->addResidualLower(tid);
1914 }
1915 
1916 void
1918 {
1919  _assembly[tid][_current_nl_sys->number()]->addResidualScalar(Assembly::GlobalDataKey{},
1921 }
1922 
1923 void
1925 {
1927  if (_displaced_problem)
1928  _displaced_problem->cacheResidual(tid);
1929 }
1930 
1931 void
1933 {
1935  if (_displaced_problem)
1936  _displaced_problem->cacheResidualNeighbor(tid);
1937 }
1938 
1939 void
1941 {
1943  if (_displaced_problem)
1944  _displaced_problem->addCachedResidual(tid);
1945 }
1946 
1947 void
1949 {
1951  _assembly[tid][_current_nl_sys->number()]->addCachedResidualDirectly(
1953 
1955  _assembly[tid][_current_nl_sys->number()]->addCachedResidualDirectly(
1957 
1958  // We do this because by adding the cached residual directly, we cannot ensure that all of the
1959  // cached residuals are emptied after only the two add calls above
1960  _assembly[tid][_current_nl_sys->number()]->clearCachedResiduals(Assembly::GlobalDataKey{});
1961 
1962  if (_displaced_problem)
1963  _displaced_problem->addCachedResidualDirectly(residual, tid);
1964 }
1965 
1966 void
1968 {
1969  _assembly[tid][_current_nl_sys->number()]->setResidual(
1970  residual,
1972  getVectorTag(_nl[_current_nl_sys->number()]->residualVectorTag()));
1973  if (_displaced_problem)
1974  _displaced_problem->setResidual(residual, tid);
1975 }
1976 
1977 void
1979 {
1980  _assembly[tid][_current_nl_sys->number()]->setResidualNeighbor(
1982  if (_displaced_problem)
1983  _displaced_problem->setResidualNeighbor(residual, tid);
1984 }
1985 
1986 void
1988 {
1989  _assembly[tid][_current_nl_sys->number()]->addJacobian(Assembly::GlobalDataKey{});
1991  _assembly[tid][_current_nl_sys->number()]->addJacobianNonlocal(Assembly::GlobalDataKey{});
1992  if (_displaced_problem)
1993  {
1994  _displaced_problem->addJacobian(tid);
1996  _displaced_problem->addJacobianNonlocal(tid);
1997  }
1998 }
1999 
2000 void
2002 {
2003  _assembly[tid][_current_nl_sys->number()]->addJacobianNeighbor(Assembly::GlobalDataKey{});
2004  if (_displaced_problem)
2005  _displaced_problem->addJacobianNeighbor(tid);
2006 }
2007 
2008 void
2010 {
2011  _assembly[tid][_current_nl_sys->number()]->addJacobianNeighborLowerD(Assembly::GlobalDataKey{});
2012  if (_displaced_problem)
2013  _displaced_problem->addJacobianNeighborLowerD(tid);
2014 }
2015 
2016 void
2018 {
2019  _assembly[tid][_current_nl_sys->number()]->addJacobianLowerD(Assembly::GlobalDataKey{});
2020  if (_displaced_problem)
2021  _displaced_problem->addJacobianLowerD(tid);
2022 }
2023 
2024 void
2026 {
2027  _assembly[tid][_current_nl_sys->number()]->addJacobianScalar(Assembly::GlobalDataKey{});
2028 }
2029 
2030 void
2031 FEProblemBase::addJacobianOffDiagScalar(unsigned int ivar, const THREAD_ID tid /* = 0*/)
2032 {
2033  _assembly[tid][_current_nl_sys->number()]->addJacobianOffDiagScalar(ivar,
2035 }
2036 
2037 void
2039 {
2041  if (_displaced_problem)
2042  _displaced_problem->cacheJacobian(tid);
2043 }
2044 
2045 void
2047 {
2049  if (_displaced_problem)
2050  _displaced_problem->cacheJacobianNeighbor(tid);
2051 }
2052 
2053 void
2055 {
2057  if (_displaced_problem)
2058  _displaced_problem->addCachedJacobian(tid);
2059 }
2060 
2061 void
2063  unsigned int ivar,
2064  unsigned int jvar,
2065  const DofMap & dof_map,
2066  std::vector<dof_id_type> & dof_indices,
2067  const std::set<TagID> & tags,
2068  const THREAD_ID tid)
2069 {
2070  _assembly[tid][_current_nl_sys->number()]->addJacobianBlockTags(
2071  jacobian, ivar, jvar, dof_map, dof_indices, Assembly::GlobalDataKey{}, tags);
2072 
2074  if (_nonlocal_cm[_current_nl_sys->number()](ivar, jvar) != 0)
2075  {
2076  MooseVariableFEBase & jv = _current_nl_sys->getVariable(tid, jvar);
2077  _assembly[tid][_current_nl_sys->number()]->addJacobianBlockNonlocalTags(
2078  jacobian,
2079  ivar,
2080  jvar,
2081  dof_map,
2082  dof_indices,
2083  jv.allDofIndices(),
2085  tags);
2086  }
2087 
2088  if (_displaced_problem)
2089  {
2090  _displaced_problem->addJacobianBlockTags(jacobian, ivar, jvar, dof_map, dof_indices, tags, tid);
2092  if (_nonlocal_cm[_current_nl_sys->number()](ivar, jvar) != 0)
2093  {
2094  MooseVariableFEBase & jv = _current_nl_sys->getVariable(tid, jvar);
2095  _displaced_problem->addJacobianBlockNonlocal(
2096  jacobian, ivar, jvar, dof_map, dof_indices, jv.allDofIndices(), tags, tid);
2097  }
2098  }
2099 }
2100 
2101 void
2103  unsigned int ivar,
2104  unsigned int jvar,
2105  const DofMap & dof_map,
2106  std::vector<dof_id_type> & dof_indices,
2107  std::vector<dof_id_type> & neighbor_dof_indices,
2108  const std::set<TagID> & tags,
2109  const THREAD_ID tid)
2110 {
2111  _assembly[tid][_current_nl_sys->number()]->addJacobianNeighborTags(jacobian,
2112  ivar,
2113  jvar,
2114  dof_map,
2115  dof_indices,
2116  neighbor_dof_indices,
2118  tags);
2119  if (_displaced_problem)
2120  _displaced_problem->addJacobianNeighbor(
2121  jacobian, ivar, jvar, dof_map, dof_indices, neighbor_dof_indices, tags, tid);
2122 }
2123 
2124 void
2125 FEProblemBase::prepareShapes(unsigned int var, const THREAD_ID tid)
2126 {
2127  _assembly[tid][_current_nl_sys->number()]->copyShapes(var);
2128 }
2129 
2130 void
2131 FEProblemBase::prepareFaceShapes(unsigned int var, const THREAD_ID tid)
2132 {
2133  _assembly[tid][_current_nl_sys->number()]->copyFaceShapes(var);
2134 }
2135 
2136 void
2138 {
2139  _assembly[tid][_current_nl_sys->number()]->copyNeighborShapes(var);
2140 }
2141 
2142 void
2144 {
2145  if (_mesh.elemPtr(elem_id)->processor_id() != processor_id())
2146  _ghosted_elems.insert(elem_id);
2147 }
2148 
2149 void
2151 {
2152  _mesh.addGhostedBoundary(boundary_id);
2153  if (_displaced_problem)
2154  _displaced_mesh->addGhostedBoundary(boundary_id);
2155 }
2156 
2157 void
2159 {
2160  TIME_SECTION("ghostGhostedBoundaries", 3, "Ghosting Ghosted Boundaries");
2161 
2163 
2164  if (_displaced_problem)
2166 }
2167 
2168 void
2169 FEProblemBase::sizeZeroes(unsigned int /*size*/, const THREAD_ID /*tid*/)
2170 {
2171  mooseDoOnce(mooseWarning(
2172  "This function is deprecated and no longer performs any function. Please do not call it."));
2173 }
2174 
2175 bool
2177 {
2178  std::vector<Point> & points = _dirac_kernel_info.getPoints()[elem].first;
2179 
2180  unsigned int n_points = points.size();
2181 
2182  if (n_points)
2183  {
2184  if (n_points > _max_qps)
2185  {
2186  _max_qps = n_points;
2187 
2192  unsigned int max_qpts = getMaxQps();
2193  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
2194  {
2195  // the highest available order in libMesh is 43
2196  _scalar_zero[tid].resize(FORTYTHIRD, 0);
2197  _zero[tid].resize(max_qpts, 0);
2198  _grad_zero[tid].resize(max_qpts, RealGradient(0.));
2199  _second_zero[tid].resize(max_qpts, RealTensor(0.));
2200  _vector_zero[tid].resize(max_qpts, RealGradient(0.));
2201  _vector_curl_zero[tid].resize(max_qpts, RealGradient(0.));
2202  }
2203  }
2204 
2205  for (const auto i : index_range(_nl))
2206  {
2207  _assembly[tid][i]->reinitAtPhysical(elem, points);
2208  _nl[i]->prepare(tid);
2209  }
2210  _aux->prepare(tid);
2211 
2212  reinitElem(elem, tid);
2213  }
2214 
2215  _assembly[tid][_current_nl_sys->number()]->prepare();
2217  _assembly[tid][_current_nl_sys->number()]->prepareNonlocal();
2218 
2219  bool have_points = n_points > 0;
2221  {
2222  have_points |= _displaced_problem->reinitDirac(_displaced_mesh->elemPtr(elem->id()), tid);
2224  _displaced_problem->prepareNonlocal(tid);
2225  }
2226 
2227  return have_points;
2228 }
2229 
2230 void
2231 FEProblemBase::reinitElem(const Elem * elem, const THREAD_ID tid)
2232 {
2233  for (auto & sys : _solver_systems)
2234  sys->reinitElem(elem, tid);
2235  _aux->reinitElem(elem, tid);
2236 
2238  _displaced_problem->reinitElem(_displaced_mesh->elemPtr(elem->id()), tid);
2239 }
2240 
2241 void
2243  const std::vector<Point> & phys_points_in_elem,
2244  const THREAD_ID tid)
2245 {
2246  mooseAssert(_mesh.queryElemPtr(elem->id()) == elem,
2247  "Are you calling this method with a displaced mesh element?");
2248 
2249  for (const auto i : index_range(_solver_systems))
2250  {
2251  _assembly[tid][i]->reinitAtPhysical(elem, phys_points_in_elem);
2252  _solver_systems[i]->prepare(tid);
2253  _assembly[tid][i]->prepare();
2255  _assembly[tid][i]->prepareNonlocal();
2256  }
2257  _aux->prepare(tid);
2258 
2259  reinitElem(elem, tid);
2260 }
2261 
2262 void
2263 FEProblemBase::reinitElemFace(const Elem * const elem,
2264  const unsigned int side,
2265  const BoundaryID,
2266  const THREAD_ID tid)
2267 {
2269  "reinitElemFace with a BoundaryID argument is deprecated because the boundary id was never "
2270  "used. Please call reinitElemFace without the BoundaryID argument instead");
2271 
2272  reinitElemFace(elem, side, tid);
2273 }
2274 
2275 void
2276 FEProblemBase::reinitElemFace(const Elem * const elem, const unsigned int side, const THREAD_ID tid)
2277 {
2278  for (const auto i : index_range(_solver_systems))
2279  {
2280  _assembly[tid][i]->reinit(elem, side);
2281  _solver_systems[i]->reinitElemFace(elem, side, tid);
2282  }
2283  _aux->reinitElemFace(elem, side, tid);
2284 
2286  _displaced_problem->reinitElemFace(_displaced_mesh->elemPtr(elem->id()), side, tid);
2287 }
2288 
2289 void
2291  const THREAD_ID tid,
2292  const std::vector<Point> * const pts,
2293  const std::vector<Real> * const weights)
2294 {
2295  SubProblem::reinitLowerDElem(lower_d_elem, tid, pts, weights);
2296 
2298  _displaced_problem->reinitLowerDElem(
2299  _displaced_mesh->elemPtr(lower_d_elem->id()), tid, pts, weights);
2300 }
2301 
2302 void
2303 FEProblemBase::reinitNode(const Node * node, const THREAD_ID tid)
2304 {
2306  _displaced_problem->reinitNode(&_displaced_mesh->nodeRef(node->id()), tid);
2307 
2308  for (const auto i : index_range(_nl))
2309  {
2310  _assembly[tid][i]->reinit(node);
2311  _nl[i]->reinitNode(node, tid);
2312  }
2313  _aux->reinitNode(node, tid);
2314 }
2315 
2316 void
2317 FEProblemBase::reinitNodeFace(const Node * node, BoundaryID bnd_id, const THREAD_ID tid)
2318 {
2320  _displaced_problem->reinitNodeFace(&_displaced_mesh->nodeRef(node->id()), bnd_id, tid);
2321 
2322  for (const auto i : index_range(_nl))
2323  {
2324  _assembly[tid][i]->reinit(node);
2325  _nl[i]->reinitNodeFace(node, bnd_id, tid);
2326  }
2327  _aux->reinitNodeFace(node, bnd_id, tid);
2328 }
2329 
2330 void
2331 FEProblemBase::reinitNodes(const std::vector<dof_id_type> & nodes, const THREAD_ID tid)
2332 {
2334  _displaced_problem->reinitNodes(nodes, tid);
2335 
2336  for (auto & nl : _nl)
2337  nl->reinitNodes(nodes, tid);
2338  _aux->reinitNodes(nodes, tid);
2339 }
2340 
2341 void
2342 FEProblemBase::reinitNodesNeighbor(const std::vector<dof_id_type> & nodes, const THREAD_ID tid)
2343 {
2345  _displaced_problem->reinitNodesNeighbor(nodes, tid);
2346 
2347  for (auto & nl : _nl)
2348  nl->reinitNodesNeighbor(nodes, tid);
2349  _aux->reinitNodesNeighbor(nodes, tid);
2350 }
2351 
2352 void
2353 FEProblemBase::reinitScalars(const THREAD_ID tid, bool reinit_for_derivative_reordering /*=false*/)
2354 {
2355  TIME_SECTION("reinitScalars", 3, "Reinitializing Scalar Variables");
2356 
2358  _displaced_problem->reinitScalars(tid, reinit_for_derivative_reordering);
2359 
2360  for (auto & nl : _nl)
2361  nl->reinitScalars(tid, reinit_for_derivative_reordering);
2362  _aux->reinitScalars(tid, reinit_for_derivative_reordering);
2363 
2364  // This is called outside of residual/Jacobian call-backs
2365  for (auto & assembly : _assembly[tid])
2367 }
2368 
2369 void
2371 {
2372  _assembly[tid][_current_nl_sys->number()]->prepareOffDiagScalar();
2373  if (_displaced_problem)
2374  _displaced_problem->reinitOffDiagScalars(tid);
2375 }
2376 
2377 void
2378 FEProblemBase::reinitNeighbor(const Elem * elem, unsigned int side, const THREAD_ID tid)
2379 {
2380  setNeighborSubdomainID(elem, side, tid);
2381 
2382  const Elem * neighbor = elem->neighbor_ptr(side);
2383  unsigned int neighbor_side = neighbor->which_neighbor_am_i(elem);
2384 
2385  for (const auto i : index_range(_nl))
2386  {
2387  _assembly[tid][i]->reinitElemAndNeighbor(elem, side, neighbor, neighbor_side);
2388  _nl[i]->prepareNeighbor(tid);
2389  // Called during stateful material property evaluation outside of solve
2390  _assembly[tid][i]->prepareNeighbor();
2391  }
2392  _aux->prepareNeighbor(tid);
2393 
2394  for (auto & nl : _nl)
2395  {
2396  nl->reinitElemFace(elem, side, tid);
2397  nl->reinitNeighborFace(neighbor, neighbor_side, tid);
2398  }
2399  _aux->reinitElemFace(elem, side, tid);
2400  _aux->reinitNeighborFace(neighbor, neighbor_side, tid);
2401 
2403  {
2404  // There are cases like for cohesive zone modeling without significant sliding where we cannot
2405  // use FEInterface::inverse_map in Assembly::reinitElemAndNeighbor in the displaced problem
2406  // because the physical points coming from the element don't actually lie on the neighbor.
2407  // Moreover, what's the point of doing another physical point inversion in other cases? We only
2408  // care about the reference points which we can just take from the undisplaced computation
2409  const auto & displaced_ref_pts = _assembly[tid][0]->qRuleNeighbor()->get_points();
2410 
2411  _displaced_problem->reinitNeighbor(
2412  _displaced_mesh->elemPtr(elem->id()), side, tid, &displaced_ref_pts);
2413  }
2414 }
2415 
2416 void
2418  unsigned int side,
2419  const THREAD_ID tid)
2420 {
2421  reinitNeighbor(elem, side, tid);
2422 
2423  const Elem * lower_d_elem = _mesh.getLowerDElem(elem, side);
2424  if (lower_d_elem && _mesh.interiorLowerDBlocks().count(lower_d_elem->subdomain_id()) > 0)
2425  reinitLowerDElem(lower_d_elem, tid);
2426  else
2427  {
2428  // with mesh refinement, lower-dimensional element might be defined on neighbor side
2429  auto & neighbor = _assembly[tid][0]->neighbor();
2430  auto & neighbor_side = _assembly[tid][0]->neighborSide();
2431  const Elem * lower_d_elem_neighbor = _mesh.getLowerDElem(neighbor, neighbor_side);
2432  if (lower_d_elem_neighbor &&
2433  _mesh.interiorLowerDBlocks().count(lower_d_elem_neighbor->subdomain_id()) > 0)
2434  {
2435  auto qps = _assembly[tid][0]->qPointsFaceNeighbor().stdVector();
2436  std::vector<Point> reference_points;
2437  FEMap::inverse_map(
2438  lower_d_elem_neighbor->dim(), lower_d_elem_neighbor, qps, reference_points);
2439  reinitLowerDElem(lower_d_elem_neighbor, tid, &reference_points);
2440  }
2441  }
2442 
2444  _displaced_problem->reinitElemNeighborAndLowerD(
2445  _displaced_mesh->elemPtr(elem->id()), side, tid);
2446 }
2447 
2448 void
2449 FEProblemBase::reinitNeighborPhys(const Elem * neighbor,
2450  unsigned int neighbor_side,
2451  const std::vector<Point> & physical_points,
2452  const THREAD_ID tid)
2453 {
2454  mooseAssert(_mesh.queryElemPtr(neighbor->id()) == neighbor,
2455  "Are you calling this method with a displaced mesh element?");
2456 
2457  for (const auto i : index_range(_nl))
2458  {
2459  // Reinits shape the functions at the physical points
2460  _assembly[tid][i]->reinitNeighborAtPhysical(neighbor, neighbor_side, physical_points);
2461 
2462  // Sets the neighbor dof indices
2463  _nl[i]->prepareNeighbor(tid);
2464  }
2465  _aux->prepareNeighbor(tid);
2466 
2467  // Resizes Re and Ke
2468  _assembly[tid][_current_nl_sys->number()]->prepareNeighbor();
2469 
2470  // Compute the values of each variable at the points
2471  for (auto & nl : _nl)
2472  nl->reinitNeighborFace(neighbor, neighbor_side, tid);
2473  _aux->reinitNeighborFace(neighbor, neighbor_side, tid);
2474 }
2475 
2476 void
2477 FEProblemBase::reinitNeighborPhys(const Elem * neighbor,
2478  const std::vector<Point> & physical_points,
2479  const THREAD_ID tid)
2480 {
2481  mooseAssert(_mesh.queryElemPtr(neighbor->id()) == neighbor,
2482  "Are you calling this method with a displaced mesh element?");
2483 
2484  for (const auto i : index_range(_nl))
2485  {
2486  // Reinits shape the functions at the physical points
2487  _assembly[tid][i]->reinitNeighborAtPhysical(neighbor, physical_points);
2488 
2489  // Sets the neighbor dof indices
2490  _nl[i]->prepareNeighbor(tid);
2491  }
2492  _aux->prepareNeighbor(tid);
2493 
2494  // Resizes Re and Ke
2495  _assembly[tid][_current_nl_sys->number()]->prepareNeighbor();
2496 
2497  // Compute the values of each variable at the points
2498  for (auto & nl : _nl)
2499  nl->reinitNeighbor(neighbor, tid);
2500  _aux->reinitNeighbor(neighbor, tid);
2501 }
2502 
2503 void
2504 FEProblemBase::getDiracElements(std::set<const Elem *> & elems)
2505 {
2506  // First add in the undisplaced elements
2507  elems = _dirac_kernel_info.getElements();
2508 
2509  if (_displaced_problem)
2510  {
2511  std::set<const Elem *> displaced_elements;
2512  _displaced_problem->getDiracElements(displaced_elements);
2513 
2514  { // Use the ids from the displaced elements to get the undisplaced elements
2515  // and add them to the list
2516  for (const auto & elem : displaced_elements)
2517  elems.insert(_mesh.elemPtr(elem->id()));
2518  }
2519  }
2520 }
2521 
2522 void
2524 {
2526 
2527  if (_displaced_problem)
2528  _displaced_problem->clearDiracInfo();
2529 }
2530 
2531 void
2533 {
2534  _all_materials.subdomainSetup(subdomain, tid);
2535  // Call the subdomain methods of the output system, these are not threaded so only call it once
2536  if (tid == 0)
2538 
2539  for (auto & nl : _nl)
2540  nl->subdomainSetup(subdomain, tid);
2541 
2542  // FIXME: call displaced_problem->subdomainSetup() ?
2543  // When adding possibility with materials being evaluated on displaced mesh
2544 }
2545 
2546 void
2548 {
2549  _all_materials.neighborSubdomainSetup(subdomain, tid);
2550 }
2551 
2552 void
2553 FEProblemBase::addFunction(const std::string & type,
2554  const std::string & name,
2555  InputParameters & parameters)
2556 {
2557  parallel_object_only();
2558 
2559  parameters.set<SubProblem *>("_subproblem") = this;
2560 
2561  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
2562  {
2563  std::shared_ptr<Function> func = _factory.create<Function>(type, name, parameters, tid);
2564  logAdd("Function", name, type, parameters);
2565  _functions.addObject(func, tid);
2566 
2567  if (auto * const functor = dynamic_cast<Moose::FunctorBase<Real> *>(func.get()))
2568  {
2569  this->addFunctor(name, *functor, tid);
2570  if (_displaced_problem)
2571  _displaced_problem->addFunctor(name, *functor, tid);
2572  }
2573  else
2574  mooseError("Unrecognized function functor type");
2575  }
2576 }
2577 
2578 void
2579 FEProblemBase::addConvergence(const std::string & type,
2580  const std::string & name,
2581  InputParameters & parameters)
2582 {
2583  parallel_object_only();
2584 
2585  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
2586  {
2587  std::shared_ptr<Convergence> conv = _factory.create<Convergence>(type, name, parameters, tid);
2588  _convergences.addObject(conv, tid);
2589  }
2590 }
2591 
2592 void
2594 {
2595  const std::string class_name = "DefaultNonlinearConvergence";
2596  InputParameters params = _factory.getValidParams(class_name);
2597  params.applyParameters(params_to_apply);
2598  params.applyParameters(parameters());
2599  params.set<bool>("added_as_default") = true;
2600  for (const auto & conv_name : getNonlinearConvergenceNames())
2601  addConvergence(class_name, conv_name, params);
2602 }
2603 
2604 void
2606 {
2607  const std::string class_name = "DefaultMultiAppFixedPointConvergence";
2608  InputParameters params = _factory.getValidParams(class_name);
2609  params.applyParameters(params_to_apply);
2610  params.applyParameters(parameters());
2611  params.set<bool>("added_as_default") = true;
2613 }
2614 
2615 void
2617 {
2618  const std::string class_name = "DefaultSteadyStateConvergence";
2619  InputParameters params = _factory.getValidParams(class_name);
2620  params.applyParameters(params_to_apply);
2621  params.applyParameters(parameters());
2622  params.set<bool>("added_as_default") = true;
2623  addConvergence(class_name, getSteadyStateConvergenceName(), params);
2624 }
2625 
2626 bool
2627 FEProblemBase::hasFunction(const std::string & name, const THREAD_ID tid)
2628 {
2629  return _functions.hasActiveObject(name, tid);
2630 }
2631 
2632 Function &
2633 FEProblemBase::getFunction(const std::string & name, const THREAD_ID tid)
2634 {
2635  // This thread lock is necessary since this method will create functions
2636  // for all threads if one is missing.
2637  Threads::spin_mutex::scoped_lock lock(get_function_mutex);
2638 
2639  if (!hasFunction(name, tid))
2640  {
2641  // If we didn't find a function, it might be a default function, attempt to construct one now
2642  std::istringstream ss(name);
2643  Real real_value;
2644 
2645  // First see if it's just a constant. If it is, build a ConstantFunction
2646  if (ss >> real_value && ss.eof())
2647  {
2648  InputParameters params = _factory.getValidParams("ConstantFunction");
2649  params.set<Real>("value") = real_value;
2650  addFunction("ConstantFunction", ss.str(), params);
2651  }
2652  else
2653  {
2655  std::string vars = "x,y,z,t,NaN,pi,e";
2656  if (fp.Parse(name, vars) == -1) // -1 for success
2657  {
2658  // It parsed ok, so build a MooseParsedFunction
2659  InputParameters params = _factory.getValidParams("ParsedFunction");
2660  params.set<std::string>("expression") = name;
2661  addFunction("ParsedFunction", name, params);
2662  }
2663  }
2664 
2665  // Try once more
2666  if (!hasFunction(name, tid))
2667  mooseError("Unable to find function " + name);
2668  }
2669 
2670  auto * const ret = dynamic_cast<Function *>(_functions.getActiveObject(name, tid).get());
2671  if (!ret)
2672  mooseError("No function named ", name, " of appropriate type");
2673 
2674  return *ret;
2675 }
2676 
2677 bool
2678 FEProblemBase::hasConvergence(const std::string & name, const THREAD_ID tid) const
2679 {
2680  return _convergences.hasActiveObject(name, tid);
2681 }
2682 
2683 Convergence &
2684 FEProblemBase::getConvergence(const std::string & name, const THREAD_ID tid) const
2685 {
2686  auto * const ret = dynamic_cast<Convergence *>(_convergences.getActiveObject(name, tid).get());
2687  if (!ret)
2688  mooseError("The Convergence object '", name, "' does not exist.");
2689 
2690  return *ret;
2691 }
2692 
2693 const std::vector<std::shared_ptr<Convergence>> &
2695 {
2696  return _convergences.getActiveObjects(tid);
2697 }
2698 
2699 void
2700 FEProblemBase::addMeshDivision(const std::string & type,
2701  const std::string & name,
2702  InputParameters & parameters)
2703 {
2704  parallel_object_only();
2705  parameters.set<FEProblemBase *>("_fe_problem_base") = this;
2706  parameters.set<SubProblem *>("_subproblem") = this;
2707  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
2708  {
2709  std::shared_ptr<MeshDivision> func = _factory.create<MeshDivision>(type, name, parameters, tid);
2710  _mesh_divisions.addObject(func, tid);
2711  }
2712 }
2713 
2714 MeshDivision &
2715 FEProblemBase::getMeshDivision(const std::string & name, const THREAD_ID tid) const
2716 {
2717  auto * const ret = dynamic_cast<MeshDivision *>(_mesh_divisions.getActiveObject(name, tid).get());
2718  if (!ret)
2719  mooseError("No MeshDivision object named ", name, " of appropriate type");
2720  return *ret;
2721 }
2722 
2723 void
2725 {
2726  _line_search->lineSearch();
2727 }
2728 
2730 FEProblemBase::getNonlinearSystem(const unsigned int sys_num)
2731 {
2732  mooseDeprecated("FEProblemBase::getNonlinearSystem() is deprecated, please use "
2733  "FEProblemBase::getNonlinearSystemBase() \n");
2734 
2735  mooseAssert(sys_num < _nl.size(), "System number greater than the number of nonlinear systems");
2736  auto nl_sys = std::dynamic_pointer_cast<NonlinearSystem>(_nl[sys_num]);
2737 
2738  if (!nl_sys)
2739  mooseError("This is not a NonlinearSystem");
2740 
2741  return *nl_sys;
2742 }
2743 
2744 void
2745 FEProblemBase::addDistribution(const std::string & type,
2746  const std::string & name,
2747  InputParameters & parameters)
2748 {
2749  parameters.set<std::string>("type") = type;
2750  addObject<Distribution>(type, name, parameters, /* threaded = */ false);
2751 }
2752 
2753 Distribution &
2754 FEProblemBase::getDistribution(const std::string & name)
2755 {
2756  std::vector<Distribution *> objs;
2757  theWarehouse()
2758  .query()
2759  .condition<AttribSystem>("Distribution")
2760  .condition<AttribName>(name)
2761  .queryInto(objs);
2762  if (objs.empty())
2763  mooseError("Unable to find Distribution with name '" + name + "'");
2764  return *(objs[0]);
2765 }
2766 
2767 void
2768 FEProblemBase::addSampler(const std::string & type,
2769  const std::string & name,
2770  InputParameters & parameters)
2771 {
2772  const auto samplers = addObject<Sampler>(type, name, parameters);
2773  for (auto & sampler : samplers)
2774  sampler->init();
2775 }
2776 
2777 Sampler &
2778 FEProblemBase::getSampler(const std::string & name, const THREAD_ID tid)
2779 {
2780  std::vector<Sampler *> objs;
2781  theWarehouse()
2782  .query()
2783  .condition<AttribSystem>("Sampler")
2784  .condition<AttribThread>(tid)
2785  .condition<AttribName>(name)
2786  .queryInto(objs);
2787  if (objs.empty())
2788  mooseError(
2789  "Unable to find Sampler with name '" + name +
2790  "', if you are attempting to access this object in the constructor of another object then "
2791  "the object being retrieved must occur prior to the caller within the input file.");
2792  return *(objs[0]);
2793 }
2794 
2795 bool
2796 FEProblemBase::duplicateVariableCheck(const std::string & var_name,
2797  const FEType & type,
2798  bool is_aux,
2799  const std::set<SubdomainID> * const active_subdomains)
2800 {
2801  std::set<SubdomainID> subdomainIDs;
2802  if (active_subdomains->size() == 0)
2803  {
2804  const auto subdomains = _mesh.meshSubdomains();
2805  subdomainIDs.insert(subdomains.begin(), subdomains.end());
2806  }
2807  else
2808  subdomainIDs.insert(active_subdomains->begin(), active_subdomains->end());
2809 
2810  for (auto & sys : _solver_systems)
2811  {
2812  SystemBase * curr_sys_ptr = sys.get();
2813  SystemBase * other_sys_ptr = _aux.get();
2814  std::string error_prefix = "";
2815  if (is_aux)
2816  {
2817  curr_sys_ptr = _aux.get();
2818  other_sys_ptr = sys.get();
2819  error_prefix = "aux";
2820  }
2821 
2822  if (other_sys_ptr->hasVariable(var_name))
2823  mooseError("Cannot have an auxiliary variable and a solver variable with the same name: ",
2824  var_name);
2825 
2826  if (curr_sys_ptr->hasVariable(var_name))
2827  {
2828  const Variable & var =
2829  curr_sys_ptr->system().variable(curr_sys_ptr->system().variable_number(var_name));
2830 
2831  // variable type
2832  if (var.type() != type)
2833  {
2834  const auto stringifyType = [](FEType t)
2835  { return Moose::stringify(t.family) + " of order " + Moose::stringify(t.order); };
2836 
2837  mooseError("Mismatching types are specified for ",
2838  error_prefix,
2839  "variable with name '",
2840  var_name,
2841  "': '",
2842  stringifyType(var.type()),
2843  "' and '",
2844  stringifyType(type),
2845  "'");
2846  }
2847 
2848  // block-restriction
2849  if (!(active_subdomains->size() == 0 && var.active_subdomains().size() == 0))
2850  {
2851  const auto varActiveSubdomains = var.active_subdomains();
2852  std::set<SubdomainID> varSubdomainIDs;
2853  if (varActiveSubdomains.size() == 0)
2854  {
2855  const auto subdomains = _mesh.meshSubdomains();
2856  varSubdomainIDs.insert(subdomains.begin(), subdomains.end());
2857  }
2858  else
2859  varSubdomainIDs.insert(varActiveSubdomains.begin(), varActiveSubdomains.end());
2860 
2861  // Is subdomainIDs a subset of varSubdomainIDs? With this we allow the case that the newly
2862  // requested block restriction is only a subset of the existing one.
2863  const auto isSubset = std::includes(varSubdomainIDs.begin(),
2864  varSubdomainIDs.end(),
2865  subdomainIDs.begin(),
2866  subdomainIDs.end());
2867 
2868  if (!isSubset)
2869  {
2870  // helper function: make a string from a set of subdomain ids
2871  const auto stringifySubdomains = [this](std::set<SubdomainID> subdomainIDs)
2872  {
2873  std::stringstream s;
2874  for (auto const i : subdomainIDs)
2875  {
2876  // do we need to insert a comma?
2877  if (s.tellp() != 0)
2878  s << ", ";
2879 
2880  // insert subdomain name and id -or- only the id (if no name is given)
2881  const auto subdomainName = _mesh.getSubdomainName(i);
2882  if (subdomainName.empty())
2883  s << i;
2884  else
2885  s << subdomainName << " (" << i << ")";
2886  }
2887  return s.str();
2888  };
2889 
2890  const std::string msg = "Mismatching block-restrictions are specified for " +
2891  error_prefix + "variable with name '" + var_name + "': {" +
2892  stringifySubdomains(varSubdomainIDs) + "} and {" +
2893  stringifySubdomains(subdomainIDs) + "}";
2894 
2895  mooseError(msg);
2896  }
2897  }
2898 
2899  return true;
2900  }
2901  }
2902 
2903  return false;
2904 }
2905 
2906 void
2907 FEProblemBase::addVariable(const std::string & var_type,
2908  const std::string & var_name,
2909  InputParameters & params)
2910 {
2911  parallel_object_only();
2912 
2913  const auto order = Utility::string_to_enum<Order>(params.get<MooseEnum>("order"));
2914  const auto family = Utility::string_to_enum<FEFamily>(params.get<MooseEnum>("family"));
2915  const auto fe_type = FEType(order, family);
2916 
2917  const auto active_subdomains_vector =
2918  _mesh.getSubdomainIDs(params.get<std::vector<SubdomainName>>("block"));
2919  const std::set<SubdomainID> active_subdomains(active_subdomains_vector.begin(),
2920  active_subdomains_vector.end());
2921 
2922  if (duplicateVariableCheck(var_name, fe_type, /* is_aux = */ false, &active_subdomains))
2923  return;
2924 
2925  params.set<FEProblemBase *>("_fe_problem_base") = this;
2926  params.set<Moose::VarKindType>("_var_kind") = Moose::VarKindType::VAR_SOLVER;
2927  SolverSystemName sys_name = params.get<SolverSystemName>("solver_sys");
2928 
2929  const auto solver_system_number = solverSysNum(sys_name);
2930  logAdd("Variable", var_name, var_type, params);
2931  _solver_systems[solver_system_number]->addVariable(var_type, var_name, params);
2932  if (_displaced_problem)
2933  // MooseObjects need to be unique so change the name here
2934  _displaced_problem->addVariable(var_type, var_name, params, solver_system_number);
2935 
2936  _solver_var_to_sys_num[var_name] = solver_system_number;
2937 
2938  markFamilyPRefinement(params);
2939 }
2940 
2941 std::pair<bool, unsigned int>
2942 FEProblemBase::determineSolverSystem(const std::string & var_name,
2943  const bool error_if_not_found) const
2944 {
2945  auto map_it = _solver_var_to_sys_num.find(var_name);
2946  const bool var_in_sys = map_it != _solver_var_to_sys_num.end();
2947  if (var_in_sys)
2948  mooseAssert(_solver_systems[map_it->second]->hasVariable(var_name) ||
2949  _solver_systems[map_it->second]->hasScalarVariable(var_name),
2950  "If the variable is in our FEProblem solver system map, then it must be in the "
2951  "solver system we expect");
2952  else if (error_if_not_found)
2953  {
2954  if (_aux->hasVariable(var_name) || _aux->hasScalarVariable(var_name))
2955  mooseError("No solver variable named ",
2956  var_name,
2957  " found. Did you specify an auxiliary variable when you meant to specify a "
2958  "solver variable?");
2959  else
2960  mooseError("Unknown variable '",
2961  var_name,
2962  "'. It does not exist in the solver system(s) or auxiliary system");
2963  }
2964 
2965  return std::make_pair(var_in_sys, var_in_sys ? map_it->second : libMesh::invalid_uint);
2966 }
2967 
2968 void
2970  const std::string & name,
2971  InputParameters & parameters,
2972  const unsigned int nl_sys_num,
2973  const std::string & base_name,
2974  bool & reinit_displaced)
2975 {
2976  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
2977  {
2978  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
2979  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
2980  reinit_displaced = true;
2981  }
2982  else
2983  {
2984  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
2985  {
2986  // We allow Kernels to request that they use_displaced_mesh,
2987  // but then be overridden when no displacements variables are
2988  // provided in the Mesh block. If that happened, update the value
2989  // of use_displaced_mesh appropriately for this Kernel.
2990  if (parameters.have_parameter<bool>("use_displaced_mesh"))
2991  parameters.set<bool>("use_displaced_mesh") = false;
2992  }
2993 
2994  parameters.set<SubProblem *>("_subproblem") = this;
2995  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
2996  }
2997 
2998  logAdd(base_name, name, ro_name, parameters);
2999 }
3000 
3001 void
3002 FEProblemBase::setAuxKernelParamsAndLog(const std::string & ak_name,
3003  const std::string & name,
3004  InputParameters & parameters,
3005  const std::string & base_name)
3006 {
3007  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3008  {
3009  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3010  parameters.set<SystemBase *>("_sys") = &_displaced_problem->auxSys();
3011  parameters.set<SystemBase *>("_nl_sys") = &_displaced_problem->solverSys(0);
3012  if (!parameters.get<std::vector<BoundaryName>>("boundary").empty())
3013  _reinit_displaced_face = true;
3014  else
3015  _reinit_displaced_elem = true;
3016  }
3017  else
3018  {
3019  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3020  {
3021  // We allow AuxKernels to request that they use_displaced_mesh,
3022  // but then be overridden when no displacements variables are
3023  // provided in the Mesh block. If that happened, update the value
3024  // of use_displaced_mesh appropriately for this AuxKernel.
3025  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3026  parameters.set<bool>("use_displaced_mesh") = false;
3027  }
3028 
3029  parameters.set<SubProblem *>("_subproblem") = this;
3030  parameters.set<SystemBase *>("_sys") = _aux.get();
3031  parameters.set<SystemBase *>("_nl_sys") = _solver_systems[0].get();
3032  }
3033 
3034  logAdd(base_name, name, ak_name, parameters);
3035 }
3036 
3037 void
3038 FEProblemBase::addKernel(const std::string & kernel_name,
3039  const std::string & name,
3040  InputParameters & parameters)
3041 {
3042  parallel_object_only();
3043  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3044  if (!isSolverSystemNonlinear(nl_sys_num))
3045  mooseError("You are trying to add a Kernel to a linear variable/system, which is not "
3046  "supported at the moment!");
3048  kernel_name, name, parameters, nl_sys_num, "Kernel", _reinit_displaced_elem);
3049 
3050  _nl[nl_sys_num]->addKernel(kernel_name, name, parameters);
3051 }
3052 
3053 void
3054 FEProblemBase::addHDGKernel(const std::string & kernel_name,
3055  const std::string & name,
3056  InputParameters & parameters)
3057 {
3058  parallel_object_only();
3059  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3060  if (!isSolverSystemNonlinear(nl_sys_num))
3061  mooseError("You are trying to add a HDGKernel to a linear variable/system, which is not "
3062  "supported at the moment!");
3064  kernel_name, name, parameters, nl_sys_num, "HDGKernel", _reinit_displaced_elem);
3065 
3066  _nl[nl_sys_num]->addHDGKernel(kernel_name, name, parameters);
3067 }
3068 
3069 void
3070 FEProblemBase::addNodalKernel(const std::string & kernel_name,
3071  const std::string & name,
3072  InputParameters & parameters)
3073 {
3074  parallel_object_only();
3075 
3076  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3077  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3078  {
3079  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3080  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
3081  _reinit_displaced_elem = true;
3082  }
3083  else
3084  {
3085  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3086  {
3087  // We allow NodalKernels to request that they use_displaced_mesh,
3088  // but then be overridden when no displacements variables are
3089  // provided in the Mesh block. If that happened, update the value
3090  // of use_displaced_mesh appropriately for this NodalKernel.
3091  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3092  parameters.set<bool>("use_displaced_mesh") = false;
3093  }
3094 
3095  parameters.set<SubProblem *>("_subproblem") = this;
3096  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
3097  }
3098  logAdd("NodalKernel", name, kernel_name, parameters);
3099  _nl[nl_sys_num]->addNodalKernel(kernel_name, name, parameters);
3100 }
3101 
3102 void
3103 FEProblemBase::addScalarKernel(const std::string & kernel_name,
3104  const std::string & name,
3105  InputParameters & parameters)
3106 {
3107  parallel_object_only();
3108 
3109  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3110  if (!isSolverSystemNonlinear(nl_sys_num))
3111  mooseError("You are trying to add a ScalarKernel to a linear variable/system, which is not "
3112  "supported at the moment!");
3113 
3114  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3115  {
3116  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3117  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
3118  }
3119  else
3120  {
3121  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3122  {
3123  // We allow ScalarKernels to request that they use_displaced_mesh,
3124  // but then be overridden when no displacements variables are
3125  // provided in the Mesh block. If that happened, update the value
3126  // of use_displaced_mesh appropriately for this ScalarKernel.
3127  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3128  parameters.set<bool>("use_displaced_mesh") = false;
3129  }
3130 
3131  parameters.set<SubProblem *>("_subproblem") = this;
3132  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
3133  }
3134 
3135  logAdd("ScalarKernel", name, kernel_name, parameters);
3136  _nl[nl_sys_num]->addScalarKernel(kernel_name, name, parameters);
3137 }
3138 
3139 void
3140 FEProblemBase::addBoundaryCondition(const std::string & bc_name,
3141  const std::string & name,
3142  InputParameters & parameters)
3143 {
3144  parallel_object_only();
3145 
3146  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3147  if (!isSolverSystemNonlinear(nl_sys_num))
3148  mooseError(
3149  "You are trying to add a BoundaryCondition to a linear variable/system, which is not "
3150  "supported at the moment!");
3151 
3153  bc_name, name, parameters, nl_sys_num, "BoundaryCondition", _reinit_displaced_face);
3154  _nl[nl_sys_num]->addBoundaryCondition(bc_name, name, parameters);
3155 }
3156 
3157 void
3158 FEProblemBase::addConstraint(const std::string & c_name,
3159  const std::string & name,
3160  InputParameters & parameters)
3161 {
3162  parallel_object_only();
3163 
3164  _has_constraints = true;
3165 
3166  auto determine_var_param_name = [&parameters, this]()
3167  {
3168  if (parameters.isParamValid("variable"))
3169  return "variable";
3170  else
3171  {
3172  // must be a mortar constraint
3173  const bool has_secondary_var = parameters.isParamValid("secondary_variable");
3174  const bool has_primary_var = parameters.isParamValid("primary_variable");
3175  if (!has_secondary_var && !has_primary_var)
3176  mooseError(
3177  "Either a 'secondary_variable' or 'primary_variable' parameter must be supplied for '",
3179  "'");
3180  return has_secondary_var ? "secondary_variable" : "primary_variable";
3181  }
3182  };
3183 
3184  const auto nl_sys_num =
3185  determineSolverSystem(parameters.varName(determine_var_param_name(), name), true).second;
3186  if (!isSolverSystemNonlinear(nl_sys_num))
3187  mooseError("You are trying to add a Constraint to a linear variable/system, which is not "
3188  "supported at the moment!");
3189 
3190  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3191  {
3192  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3193  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
3194  _reinit_displaced_face = true;
3195  }
3196  else
3197  {
3198  // It might _want_ to use a displaced mesh... but we're not so set it to false
3199  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3200  parameters.set<bool>("use_displaced_mesh") = false;
3201 
3202  parameters.set<SubProblem *>("_subproblem") = this;
3203  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
3204  }
3205 
3206  logAdd("Constraint", name, c_name, parameters);
3207  _nl[nl_sys_num]->addConstraint(c_name, name, parameters);
3208 }
3209 
3210 void
3211 FEProblemBase::addAuxVariable(const std::string & var_type,
3212  const std::string & var_name,
3213  InputParameters & params)
3214 {
3215  parallel_object_only();
3216 
3217  const auto order = Utility::string_to_enum<Order>(params.get<MooseEnum>("order"));
3218  const auto family = Utility::string_to_enum<FEFamily>(params.get<MooseEnum>("family"));
3219  const auto fe_type = FEType(order, family);
3220 
3221  const auto active_subdomains_vector =
3222  _mesh.getSubdomainIDs(params.get<std::vector<SubdomainName>>("block"));
3223  const std::set<SubdomainID> active_subdomains(active_subdomains_vector.begin(),
3224  active_subdomains_vector.end());
3225 
3226  if (duplicateVariableCheck(var_name, fe_type, /* is_aux = */ true, &active_subdomains))
3227  return;
3228 
3229  params.set<FEProblemBase *>("_fe_problem_base") = this;
3231 
3232  logAdd("AuxVariable", var_name, var_type, params);
3233  _aux->addVariable(var_type, var_name, params);
3234  if (_displaced_problem)
3235  // MooseObjects need to be unique so change the name here
3236  _displaced_problem->addAuxVariable(var_type, var_name, params);
3237 
3238  markFamilyPRefinement(params);
3239 }
3240 
3241 void
3242 FEProblemBase::addAuxVariable(const std::string & var_name,
3243  const FEType & type,
3244  const std::set<SubdomainID> * const active_subdomains)
3245 {
3246  parallel_object_only();
3247 
3248  mooseDeprecated("Please use the addAuxVariable(var_type, var_name, params) API instead");
3249 
3250  if (duplicateVariableCheck(var_name, type, /* is_aux = */ true, active_subdomains))
3251  return;
3252 
3253  std::string var_type;
3254  if (type == FEType(0, MONOMIAL))
3255  var_type = "MooseVariableConstMonomial";
3256  else if (type.family == SCALAR)
3257  var_type = "MooseVariableScalar";
3258  else if (FEInterface::field_type(type) == TYPE_VECTOR)
3259  var_type = "VectorMooseVariable";
3260  else
3261  var_type = "MooseVariable";
3262 
3263  InputParameters params = _factory.getValidParams(var_type);
3264  params.set<FEProblemBase *>("_fe_problem_base") = this;
3266  params.set<MooseEnum>("order") = type.order.get_order();
3267  params.set<MooseEnum>("family") = Moose::stringify(type.family);
3268 
3269  if (active_subdomains)
3270  for (const SubdomainID & id : *active_subdomains)
3271  params.set<std::vector<SubdomainName>>("block").push_back(Moose::stringify(id));
3272 
3273  logAdd("AuxVariable", var_name, var_type, params);
3274  _aux->addVariable(var_type, var_name, params);
3275  if (_displaced_problem)
3276  _displaced_problem->addAuxVariable("MooseVariable", var_name, params);
3277 
3278  markFamilyPRefinement(params);
3279 }
3280 
3281 void
3282 FEProblemBase::addAuxArrayVariable(const std::string & var_name,
3283  const FEType & type,
3284  unsigned int components,
3285  const std::set<SubdomainID> * const active_subdomains)
3286 {
3287  parallel_object_only();
3288 
3289  mooseDeprecated("Please use the addAuxVariable(var_type, var_name, params) API instead");
3290 
3291  if (duplicateVariableCheck(var_name, type, /* is_aux = */ true, active_subdomains))
3292  return;
3293 
3294  InputParameters params = _factory.getValidParams("ArrayMooseVariable");
3295  params.set<FEProblemBase *>("_fe_problem_base") = this;
3297  params.set<MooseEnum>("order") = type.order.get_order();
3298  params.set<MooseEnum>("family") = Moose::stringify(type.family);
3299  params.set<unsigned int>("components") = components;
3300 
3301  if (active_subdomains)
3302  for (const SubdomainID & id : *active_subdomains)
3303  params.set<std::vector<SubdomainName>>("block").push_back(Moose::stringify(id));
3304 
3305  logAdd("Variable", var_name, "ArrayMooseVariable", params);
3306  _aux->addVariable("ArrayMooseVariable", var_name, params);
3307  if (_displaced_problem)
3308  _displaced_problem->addAuxVariable("ArrayMooseVariable", var_name, params);
3309 
3310  markFamilyPRefinement(params);
3311 }
3312 
3313 void
3314 FEProblemBase::addAuxScalarVariable(const std::string & var_name,
3315  Order order,
3316  Real /*scale_factor*/,
3317  const std::set<SubdomainID> * const active_subdomains)
3318 {
3319  parallel_object_only();
3320 
3321  mooseDeprecated("Please use the addAuxVariable(var_type, var_name, params) API instead");
3322 
3323  if (order > _max_scalar_order)
3324  _max_scalar_order = order;
3325 
3326  FEType type(order, SCALAR);
3327  if (duplicateVariableCheck(var_name, type, /* is_aux = */ true, active_subdomains))
3328  return;
3329 
3330  InputParameters params = _factory.getValidParams("MooseVariableScalar");
3331  params.set<FEProblemBase *>("_fe_problem_base") = this;
3333 
3334  params.set<MooseEnum>("order") = type.order.get_order();
3335  params.set<MooseEnum>("family") = "SCALAR";
3336  params.set<std::vector<Real>>("scaling") = {1};
3337  if (active_subdomains)
3338  for (const SubdomainID & id : *active_subdomains)
3339  params.set<std::vector<SubdomainName>>("block").push_back(Moose::stringify(id));
3340 
3341  logAdd("ScalarVariable", var_name, "MooseVariableScalar", params);
3342  _aux->addVariable("MooseVariableScalar", var_name, params);
3343  if (_displaced_problem)
3344  _displaced_problem->addAuxVariable("MooseVariableScalar", var_name, params);
3345 }
3346 
3347 void
3348 FEProblemBase::addAuxKernel(const std::string & kernel_name,
3349  const std::string & name,
3350  InputParameters & parameters)
3351 {
3352  parallel_object_only();
3353 
3354  setAuxKernelParamsAndLog(kernel_name, name, parameters, "AuxKernel");
3355 
3356  _aux->addKernel(kernel_name, name, parameters);
3357 }
3358 
3359 void
3360 FEProblemBase::addAuxScalarKernel(const std::string & kernel_name,
3361  const std::string & name,
3362  InputParameters & parameters)
3363 {
3364  parallel_object_only();
3365 
3366  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3367  {
3368  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3369  parameters.set<SystemBase *>("_sys") = &_displaced_problem->auxSys();
3370  }
3371  else
3372  {
3373  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3374  {
3375  // We allow AuxScalarKernels to request that they use_displaced_mesh,
3376  // but then be overridden when no displacements variables are
3377  // provided in the Mesh block. If that happened, update the value
3378  // of use_displaced_mesh appropriately for this AuxScalarKernel.
3379  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3380  parameters.set<bool>("use_displaced_mesh") = false;
3381  }
3382 
3383  parameters.set<SubProblem *>("_subproblem") = this;
3384  parameters.set<SystemBase *>("_sys") = _aux.get();
3385  }
3386 
3387  logAdd("AuxScalarKernel", name, kernel_name, parameters);
3388  _aux->addScalarKernel(kernel_name, name, parameters);
3389 }
3390 
3391 void
3392 FEProblemBase::addDiracKernel(const std::string & kernel_name,
3393  const std::string & name,
3394  InputParameters & parameters)
3395 {
3396  parallel_object_only();
3397 
3398  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3399  if (!isSolverSystemNonlinear(nl_sys_num))
3400  mooseError("You are trying to add a DiracKernel to a linear variable/system, which is not "
3401  "supported at the moment!");
3402 
3403  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3404  {
3405  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3406  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
3407  _reinit_displaced_elem = true;
3408  }
3409  else
3410  {
3411  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3412  {
3413  // We allow DiracKernels to request that they use_displaced_mesh,
3414  // but then be overridden when no displacements variables are
3415  // provided in the Mesh block. If that happened, update the value
3416  // of use_displaced_mesh appropriately for this DiracKernel.
3417  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3418  parameters.set<bool>("use_displaced_mesh") = false;
3419  }
3420 
3421  parameters.set<SubProblem *>("_subproblem") = this;
3422  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
3423  }
3424 
3425  logAdd("DiracKernel", name, kernel_name, parameters);
3426  _nl[nl_sys_num]->addDiracKernel(kernel_name, name, parameters);
3427 }
3428 
3429 // DGKernels ////
3430 
3431 void
3432 FEProblemBase::addDGKernel(const std::string & dg_kernel_name,
3433  const std::string & name,
3434  InputParameters & parameters)
3435 {
3436  parallel_object_only();
3437 
3438  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3439  if (!isSolverSystemNonlinear(nl_sys_num))
3440  mooseError("You are trying to add a DGKernel to a linear variable/system, which is not "
3441  "supported at the moment!");
3442 
3443  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3444  {
3445  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3446  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
3448  }
3449  else
3450  {
3451  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3452  {
3453  // We allow DGKernels to request that they use_displaced_mesh,
3454  // but then be overridden when no displacements variables are
3455  // provided in the Mesh block. If that happened, update the value
3456  // of use_displaced_mesh appropriately for this DGKernel.
3457  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3458  parameters.set<bool>("use_displaced_mesh") = false;
3459  }
3460 
3461  parameters.set<SubProblem *>("_subproblem") = this;
3462  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
3463  }
3464 
3465  logAdd("DGKernel", name, dg_kernel_name, parameters);
3466  _nl[nl_sys_num]->addDGKernel(dg_kernel_name, name, parameters);
3467 
3469 }
3470 
3471 void
3472 FEProblemBase::addFVKernel(const std::string & fv_kernel_name,
3473  const std::string & name,
3474  InputParameters & parameters)
3475 {
3476  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3477  // FVElementalKernels are computed in the historically finite element threaded loops. They rely
3478  // on Assembly data like _current_elem. When we call reinit on the FEProblemBase we will only
3479  // reinit the DisplacedProblem and its associated Assembly objects if we mark this boolean as
3480  // true
3481  _reinit_displaced_elem = true;
3482  addObject<FVKernel>(fv_kernel_name, name, parameters);
3483 }
3484 
3485 void
3486 FEProblemBase::addFVBC(const std::string & fv_bc_name,
3487  const std::string & name,
3488  InputParameters & parameters)
3489 {
3490  addObject<FVBoundaryCondition>(fv_bc_name, name, parameters);
3491 }
3492 
3493 void
3494 FEProblemBase::addFVInterfaceKernel(const std::string & fv_ik_name,
3495  const std::string & name,
3496  InputParameters & parameters)
3497 {
3500  addObject<FVInterfaceKernel>(
3501  fv_ik_name, name, parameters, /*threaded=*/true, /*variable_param_name=*/"variable1");
3502 }
3503 
3504 void
3505 FEProblemBase::addLinearFVKernel(const std::string & kernel_name,
3506  const std::string & name,
3507  InputParameters & parameters)
3508 {
3509  addObject<LinearFVKernel>(kernel_name, name, parameters);
3510 }
3511 
3512 void
3513 FEProblemBase::addLinearFVBC(const std::string & bc_name,
3514  const std::string & name,
3515  InputParameters & parameters)
3516 {
3517  addObject<LinearFVBoundaryCondition>(bc_name, name, parameters);
3518 }
3519 
3520 // InterfaceKernels ////
3521 
3522 void
3523 FEProblemBase::addInterfaceKernel(const std::string & interface_kernel_name,
3524  const std::string & name,
3525  InputParameters & parameters)
3526 {
3527  parallel_object_only();
3528 
3529  const auto nl_sys_num = determineSolverSystem(parameters.varName("variable", name), true).second;
3530  if (!isSolverSystemNonlinear(nl_sys_num))
3531  mooseError("You are trying to add a InterfaceKernel to a linear variable/system, which is not "
3532  "supported at the moment!");
3533 
3534  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
3535  {
3536  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
3537  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(nl_sys_num);
3539  }
3540  else
3541  {
3542  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
3543  {
3544  // We allow InterfaceKernels to request that they use_displaced_mesh,
3545  // but then be overridden when no displacements variables are
3546  // provided in the Mesh block. If that happened, update the value
3547  // of use_displaced_mesh appropriately for this InterfaceKernel.
3548  if (parameters.have_parameter<bool>("use_displaced_mesh"))
3549  parameters.set<bool>("use_displaced_mesh") = false;
3550  }
3551 
3552  parameters.set<SubProblem *>("_subproblem") = this;
3553  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
3554  }
3555 
3556  logAdd("InterfaceKernel", name, interface_kernel_name, parameters);
3557  _nl[nl_sys_num]->addInterfaceKernel(interface_kernel_name, name, parameters);
3558 
3560 }
3561 
3562 void
3563 FEProblemBase::checkICRestartError(const std::string & ic_name,
3564  const std::string & name,
3565  const VariableName & var_name)
3566 {
3568  {
3569  std::string restart_method = "";
3570  if (_app.isRestarting())
3571  restart_method =
3572  "a checkpoint restart, by IC object '" + ic_name + "' for variable '" + name + "'";
3573  else if (_app.getExReaderForRestart())
3574  {
3575  std::vector<std::string> restarted_vars = _app.getExReaderForRestart()->get_elem_var_names();
3576  const auto nodal_vars = _app.getExReaderForRestart()->get_nodal_var_names();
3577  const auto global_vars = _app.getExReaderForRestart()->get_global_var_names();
3578  restarted_vars.insert(restarted_vars.end(), nodal_vars.begin(), nodal_vars.end());
3579  restarted_vars.insert(restarted_vars.end(), global_vars.begin(), global_vars.end());
3580 
3581  if (std::find(restarted_vars.begin(), restarted_vars.end(), var_name) != restarted_vars.end())
3582  restart_method = "an Exodus restart, by IC object '" + ic_name + "' for variable '" + name +
3583  "' that is also being restarted";
3584  }
3585  if (!restart_method.empty())
3586  mooseError(
3587  "Initial conditions have been specified during ",
3588  restart_method,
3589  ".\nThis is only allowed if you specify 'allow_initial_conditions_with_restart' to "
3590  "the [Problem], as initial conditions can override restarted fields");
3591  }
3592 }
3593 
3594 void
3595 FEProblemBase::addInitialCondition(const std::string & ic_name,
3596  const std::string & name,
3597  InputParameters & parameters)
3598 {
3599  parallel_object_only();
3600 
3601  // before we start to mess with the initial condition, we need to check parameters for errors.
3603  const std::string & var_name = parameters.get<VariableName>("variable");
3604 
3605  // Forbid initial conditions on a restarted problem, as they would override the restart
3606  checkICRestartError(ic_name, name, var_name);
3607 
3608  parameters.set<SubProblem *>("_subproblem") = this;
3609 
3610  // field IC
3611  if (hasVariable(var_name))
3612  {
3613  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
3614  {
3617  parameters.set<SystemBase *>("_sys") = &var.sys();
3618  std::shared_ptr<InitialConditionBase> ic;
3619  if (dynamic_cast<MooseVariable *>(&var))
3620  ic = _factory.create<InitialCondition>(ic_name, name, parameters, tid);
3621  else if (dynamic_cast<VectorMooseVariable *>(&var))
3622  ic = _factory.create<VectorInitialCondition>(ic_name, name, parameters, tid);
3623  else if (dynamic_cast<ArrayMooseVariable *>(&var))
3624  ic = _factory.create<ArrayInitialCondition>(ic_name, name, parameters, tid);
3625  else if (dynamic_cast<MooseVariableFVReal *>(&var))
3626  ic = _factory.create<InitialCondition>(ic_name, name, parameters, tid);
3627  else if (dynamic_cast<MooseLinearVariableFVReal *>(&var))
3628  ic = _factory.create<InitialCondition>(ic_name, name, parameters, tid);
3629  else
3630  mooseError("Your FE variable in initial condition ",
3631  name,
3632  " must be either of scalar or vector type");
3633  logAdd("IC", name, ic_name, parameters);
3634  _ics.addObject(ic, tid);
3635  }
3636  }
3637 
3638  // scalar IC
3639  else if (hasScalarVariable(var_name))
3640  {
3641  MooseVariableScalar & var = getScalarVariable(0, var_name);
3642  parameters.set<SystemBase *>("_sys") = &var.sys();
3643  std::shared_ptr<ScalarInitialCondition> ic =
3645  logAdd("ScalarIC", name, ic_name, parameters);
3646  _scalar_ics.addObject(ic);
3647  }
3648 
3649  else
3650  mooseError(
3651  "Variable '", var_name, "' requested in initial condition '", name, "' does not exist.");
3652 }
3653 
3654 void
3655 FEProblemBase::addFVInitialCondition(const std::string & ic_name,
3656  const std::string & name,
3657  InputParameters & parameters)
3658 {
3659  parallel_object_only();
3660 
3661  // before we start to mess with the initial condition, we need to check parameters for errors.
3663  const std::string & var_name = parameters.get<VariableName>("variable");
3664 
3665  // Forbid initial conditions on a restarted problem, as they would override the restart
3666  checkICRestartError(ic_name, name, var_name);
3667 
3668  parameters.set<SubProblem *>("_subproblem") = this;
3669 
3670  // field IC
3671  if (hasVariable(var_name))
3672  {
3673  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
3674  {
3675  auto & var = getVariable(
3677  parameters.set<SystemBase *>("_sys") = &var.sys();
3678  std::shared_ptr<FVInitialConditionBase> ic;
3679  if (var.isFV())
3680  ic = _factory.create<FVInitialCondition>(ic_name, name, parameters, tid);
3681  else
3682  mooseError(
3683  "Your variable for an FVInitialCondition needs to be an a finite volume variable!");
3684  _fv_ics.addObject(ic, tid);
3685  }
3686  }
3687  else
3688  mooseError("Variable '",
3689  var_name,
3690  "' requested in finite volume initial condition '",
3691  name,
3692  "' does not exist.");
3693 }
3694 
3695 void
3697 {
3698  TIME_SECTION("projectSolution", 2, "Projecting Initial Solutions")
3699 
3700  FloatingPointExceptionGuard fpe_guard(_app);
3701 
3703  ComputeInitialConditionThread cic(*this);
3704  Threads::parallel_reduce(elem_range, cic);
3705 
3706  if (haveFV())
3707  {
3709  ElemInfoRange elem_info_range(_mesh.ownedElemInfoBegin(), _mesh.ownedElemInfoEnd());
3710 
3711  ComputeFVInitialConditionThread cfvic(*this);
3712  Threads::parallel_reduce(elem_info_range, cfvic);
3713  }
3714 
3715  // Need to close the solution vector here so that boundary ICs take precendence
3716  for (auto & nl : _nl)
3717  nl->solution().close();
3718  _aux->solution().close();
3719 
3720  // now run boundary-restricted initial conditions
3721  ConstBndNodeRange & bnd_nodes = *_mesh.getBoundaryNodeRange();
3723  Threads::parallel_reduce(bnd_nodes, cbic);
3724 
3725  for (auto & nl : _nl)
3726  nl->solution().close();
3727  _aux->solution().close();
3728 
3729  // Also, load values into the SCALAR dofs
3730  // Note: We assume that all SCALAR dofs are on the
3731  // processor with highest ID
3732  if (processor_id() == (n_processors() - 1) && _scalar_ics.hasActiveObjects())
3733  {
3734  const auto & ics = _scalar_ics.getActiveObjects();
3735  for (const auto & ic : ics)
3736  {
3737  MooseVariableScalar & var = ic->variable();
3738  var.reinit();
3739 
3740  DenseVector<Number> vals(var.order());
3741  ic->compute(vals);
3742 
3743  const unsigned int n_scalar_dofs = var.dofIndices().size();
3744  for (unsigned int i = 0; i < n_scalar_dofs; i++)
3745  {
3746  const auto global_index = var.dofIndices()[i];
3747  var.sys().solution().set(global_index, vals(i));
3748  var.setValue(i, vals(i));
3749  }
3750  }
3751  }
3752 
3753  for (auto & sys : _solver_systems)
3754  {
3755  sys->solution().close();
3756  sys->solution().localize(*sys->system().current_local_solution, sys->dofMap().get_send_list());
3757  }
3758 
3759  _aux->solution().close();
3760  _aux->solution().localize(*_aux->sys().current_local_solution, _aux->dofMap().get_send_list());
3761 }
3762 
3763 void
3765  ConstElemRange & elem_range,
3766  ConstBndNodeRange & bnd_nodes,
3767  const std::optional<std::set<VariableName>> & target_vars)
3768 {
3769  if (target_vars)
3770  {
3771  ComputeInitialConditionThread cic(*this, &(*target_vars));
3772  Threads::parallel_reduce(elem_range, cic);
3773  }
3774  else
3775  {
3776  ComputeInitialConditionThread cic(*this);
3777  Threads::parallel_reduce(elem_range, cic);
3778  }
3779 
3780  // Need to close the solution vector here so that boundary ICs take precendence
3781  for (auto & nl : _nl)
3782  nl->solution().close();
3783  _aux->solution().close();
3784 
3785  if (target_vars)
3786  {
3787  ComputeBoundaryInitialConditionThread cbic(*this, &(*target_vars));
3788  Threads::parallel_reduce(bnd_nodes, cbic);
3789  }
3790  else
3791  {
3793  Threads::parallel_reduce(bnd_nodes, cbic);
3794  }
3795 
3796  for (auto & nl : _nl)
3797  nl->solution().close();
3798  _aux->solution().close();
3799 
3800  // Also, load values into the SCALAR dofs
3801  // Note: We assume that all SCALAR dofs are on the
3802  // processor with highest ID
3803  if (processor_id() == (n_processors() - 1) && _scalar_ics.hasActiveObjects())
3804  {
3805  const auto & ics = _scalar_ics.getActiveObjects();
3806  for (const auto & ic : ics)
3807  {
3808  MooseVariableScalar & var = ic->variable();
3809 
3810  if (target_vars && !target_vars->count(var.name()))
3811  continue;
3812 
3813  var.reinit();
3814 
3815  DenseVector<Number> vals(var.order());
3816  ic->compute(vals);
3817 
3818  const unsigned int n_scalar_dofs = var.dofIndices().size();
3819  for (unsigned int i = 0; i < n_scalar_dofs; i++)
3820  {
3821  const auto global_index = var.dofIndices()[i];
3822  var.sys().solution().set(global_index, vals(i));
3823  var.setValue(i, vals(i));
3824  }
3825  }
3826  }
3827 
3828  for (auto & nl : _nl)
3829  {
3830  nl->solution().close();
3831  nl->solution().localize(*nl->system().current_local_solution, nl->dofMap().get_send_list());
3832  }
3833 
3834  _aux->solution().close();
3835  _aux->solution().localize(*_aux->sys().current_local_solution, _aux->dofMap().get_send_list());
3836 }
3837 
3838 void
3840  Number (*func)(const Point &,
3841  const libMesh::Parameters &,
3842  const std::string &,
3843  const std::string &),
3844  Gradient (*func_grad)(const Point &,
3845  const libMesh::Parameters &,
3846  const std::string &,
3847  const std::string &),
3848  const libMesh::Parameters & params,
3849  const VariableName & target_var)
3850 {
3851  mooseAssert(!Threads::in_threads,
3852  "We're performing a projection based on data from just the thread 0 variable, so any "
3853  "modifications to the variable solution must have been thread joined already");
3854 
3855  const auto & var = getStandardVariable(0, target_var);
3856  const auto var_num = var.number();
3857  const auto sn = systemNumForVariable(target_var);
3858  auto & sys = getSystemBase(sn);
3859 
3860  // Let libmesh handle the projection
3861  System & libmesh_sys = getSystem(target_var);
3862  auto temp_vec = libmesh_sys.current_local_solution->zero_clone();
3863  libmesh_sys.project_vector(func, func_grad, params, *temp_vec);
3864  temp_vec->close();
3865 
3866  // Get the dof indices to copy
3867  DofMap & dof_map = sys.dofMap();
3868  std::set<dof_id_type> dof_indices;
3869  std::vector<dof_id_type> elem_dof_indices;
3870 
3871  for (const auto & elem : elem_range)
3872  {
3873  dof_map.dof_indices(elem, elem_dof_indices, var_num);
3874  dof_indices.insert(elem_dof_indices.begin(), elem_dof_indices.end());
3875  }
3876  std::vector<dof_id_type> dof_indices_v(dof_indices.begin(), dof_indices.end());
3877 
3878  // Copy the projected values into the solution vector
3879  std::vector<Real> dof_vals;
3880  temp_vec->get(dof_indices_v, dof_vals);
3881  mooseAssert(sys.solution().closed(),
3882  "The solution should be closed before mapping our projection");
3883  sys.solution().insert(dof_vals, dof_indices_v);
3884  sys.solution().close();
3885  sys.solution().localize(*libmesh_sys.current_local_solution, sys.dofMap().get_send_list());
3886 }
3887 
3888 std::shared_ptr<MaterialBase>
3891  const THREAD_ID tid,
3892  bool no_warn)
3893 {
3894  switch (type)
3895  {
3897  name += "_neighbor";
3898  break;
3900  name += "_face";
3901  break;
3902  default:
3903  break;
3904  }
3905 
3906  std::shared_ptr<MaterialBase> material = _all_materials[type].getActiveObject(name, tid);
3907  if (!no_warn && material->getParam<bool>("compute") && type == Moose::BLOCK_MATERIAL_DATA)
3908  mooseWarning("You are retrieving a Material object (",
3909  material->name(),
3910  "), but its compute flag is set to true. This indicates that MOOSE is "
3911  "computing this property which may not be desired and produce un-expected "
3912  "results.");
3913 
3914  return material;
3915 }
3916 
3917 MaterialData &
3919  const THREAD_ID tid,
3920  const MooseObject * object) const
3921 {
3922  switch (type)
3923  {
3925  if (object)
3926  _material_props.addConsumer(type, object);
3927  return _material_props.getMaterialData(tid);
3929  if (object)
3935  if (object)
3938  }
3939 
3940  mooseError("FEProblemBase::getMaterialData(): Invalid MaterialDataType ", type);
3941 }
3942 
3943 const std::set<const MooseObject *> &
3945 {
3946  switch (type)
3947  {
3956  }
3957 
3958  mooseError("FEProblemBase::getMaterialPropertyStorageConsumers(): Invalid MaterialDataType ",
3959  type);
3960 }
3961 
3962 void
3964 {
3965  if (_ignore_zeros_in_jacobian && preserve)
3966  paramWarning(
3967  "ignore_zeros_in_jacobian",
3968  "We likely cannot preserve the sparsity pattern if ignoring zeros in the Jacobian, which "
3969  "leads to removing those entries from the Jacobian sparsity pattern");
3971 }
3972 
3973 bool
3975 {
3976  return allowInvalidSolution() || // invalid solutions are always allowed
3977  !_app.solutionInvalidity().hasInvalidSolutionError(); // if not allowed, check for errors
3978 }
3979 
3980 void
3981 FEProblemBase::addFunctorMaterial(const std::string & functor_material_name,
3982  const std::string & name,
3983  InputParameters & parameters)
3984 {
3985  parallel_object_only();
3986 
3987  auto add_functor_materials = [&](const auto & parameters, const auto & name)
3988  {
3989  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
3990  {
3991  // Create the general Block/Boundary MaterialBase object
3992  std::shared_ptr<MaterialBase> material =
3993  _factory.create<MaterialBase>(functor_material_name, name, parameters, tid);
3994  logAdd("FunctorMaterial", name, functor_material_name, parameters);
3995  _all_materials.addObject(material, tid);
3996  _materials.addObject(material, tid);
3997  }
3998  };
3999 
4000  parameters.set<SubProblem *>("_subproblem") = this;
4001  add_functor_materials(parameters, name);
4002  if (_displaced_problem)
4003  {
4004  auto disp_params = parameters;
4005  disp_params.set<SubProblem *>("_subproblem") = _displaced_problem.get();
4006  add_functor_materials(disp_params, name + "_displaced");
4007  }
4008 }
4009 
4010 void
4011 FEProblemBase::addMaterial(const std::string & mat_name,
4012  const std::string & name,
4013  InputParameters & parameters)
4014 {
4015  addMaterialHelper({&_materials}, mat_name, name, parameters);
4016 }
4017 
4018 void
4019 FEProblemBase::addInterfaceMaterial(const std::string & mat_name,
4020  const std::string & name,
4021  InputParameters & parameters)
4022 {
4024 }
4025 
4026 void
4027 FEProblemBase::addMaterialHelper(std::vector<MaterialWarehouse *> warehouses,
4028  const std::string & mat_name,
4029  const std::string & name,
4030  InputParameters & parameters)
4031 {
4032  parallel_object_only();
4033 
4034  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
4035  {
4036  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
4038  }
4039  else
4040  {
4041  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
4042  {
4043  // We allow Materials to request that they use_displaced_mesh,
4044  // but then be overridden when no displacements variables are
4045  // provided in the Mesh block. If that happened, update the value
4046  // of use_displaced_mesh appropriately for this Material.
4047  if (parameters.have_parameter<bool>("use_displaced_mesh"))
4048  parameters.set<bool>("use_displaced_mesh") = false;
4049  }
4050 
4051  parameters.set<SubProblem *>("_subproblem") = this;
4052  }
4053 
4054  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
4055  {
4056  // Create the general Block/Boundary MaterialBase object
4057  std::shared_ptr<MaterialBase> material =
4058  _factory.create<MaterialBase>(mat_name, name, parameters, tid);
4059  logAdd("Material", name, mat_name, parameters);
4060  bool discrete = !material->getParam<bool>("compute");
4061 
4062  // If the object is boundary restricted or if it is a functor material we do not create the
4063  // neighbor and face objects
4064  if (material->boundaryRestricted() || dynamic_cast<FunctorMaterial *>(material.get()))
4065  {
4066  _all_materials.addObject(material, tid);
4067  if (discrete)
4068  _discrete_materials.addObject(material, tid);
4069  else
4070  for (auto && warehouse : warehouses)
4071  warehouse->addObject(material, tid);
4072  }
4073 
4074  // Non-boundary restricted require face and neighbor objects
4075  else
4076  {
4077  // TODO: we only need to do this if we have needs for face materials (e.g.
4078  // FV, DG, etc.) - but currently we always do it. Figure out how to fix
4079  // this.
4080 
4081  // The name of the object being created, this is changed multiple times as objects are
4082  // created below
4083  std::string object_name;
4084 
4085  // Create a copy of the supplied parameters to the setting for "_material_data_type" isn't
4086  // used from a previous tid loop
4087  InputParameters current_parameters = parameters;
4088 
4089  // face material
4090  current_parameters.set<Moose::MaterialDataType>("_material_data_type") =
4092  object_name = name + "_face";
4093  std::shared_ptr<MaterialBase> face_material =
4094  _factory.create<MaterialBase>(mat_name, object_name, current_parameters, tid);
4095 
4096  // neighbor material
4097  current_parameters.set<Moose::MaterialDataType>("_material_data_type") =
4099  current_parameters.set<bool>("_neighbor") = true;
4100  object_name = name + "_neighbor";
4101  std::shared_ptr<MaterialBase> neighbor_material =
4102  _factory.create<MaterialBase>(mat_name, object_name, current_parameters, tid);
4103 
4104  // Store the material objects
4105  _all_materials.addObjects(material, neighbor_material, face_material, tid);
4106 
4107  if (discrete)
4108  _discrete_materials.addObjects(material, neighbor_material, face_material, tid);
4109  else
4110  for (auto && warehouse : warehouses)
4111  warehouse->addObjects(material, neighbor_material, face_material, tid);
4112 
4113  // Names of all controllable parameters for this Material object
4114  const std::string & base = parameters.getBase();
4115  MooseObjectParameterName name(MooseObjectName(base, material->name()), "*");
4116  const auto param_names =
4118 
4119  // Connect parameters of the primary Material object to those on the face and neighbor
4120  // objects
4121  for (const auto & p_name : param_names)
4122  {
4123  MooseObjectParameterName primary_name(MooseObjectName(base, material->name()),
4124  p_name.parameter());
4125  MooseObjectParameterName face_name(MooseObjectName(base, face_material->name()),
4126  p_name.parameter());
4127  MooseObjectParameterName neighbor_name(MooseObjectName(base, neighbor_material->name()),
4128  p_name.parameter());
4130  primary_name, face_name, false);
4132  primary_name, neighbor_name, false);
4133  }
4134  }
4135  }
4136 }
4137 
4138 void
4139 FEProblemBase::prepareMaterials(const std::unordered_set<unsigned int> & consumer_needed_mat_props,
4140  const SubdomainID blk_id,
4141  const THREAD_ID tid)
4142 {
4143  std::set<MooseVariableFEBase *> needed_moose_vars;
4144  std::unordered_set<unsigned int> needed_mat_props;
4145 
4146  if (_all_materials.hasActiveBlockObjects(blk_id, tid))
4147  {
4148  _all_materials.updateVariableDependency(needed_moose_vars, tid);
4149  _all_materials.updateBlockMatPropDependency(blk_id, needed_mat_props, tid);
4150  }
4151 
4152  const auto & ids = _mesh.getSubdomainBoundaryIds(blk_id);
4153  for (const auto id : ids)
4154  {
4155  _materials.updateBoundaryVariableDependency(id, needed_moose_vars, tid);
4156  _materials.updateBoundaryMatPropDependency(id, needed_mat_props, tid);
4157  }
4158 
4159  const auto & current_active_elemental_moose_variables = getActiveElementalMooseVariables(tid);
4160  needed_moose_vars.insert(current_active_elemental_moose_variables.begin(),
4161  current_active_elemental_moose_variables.end());
4162 
4163  needed_mat_props.insert(consumer_needed_mat_props.begin(), consumer_needed_mat_props.end());
4164 
4165  setActiveElementalMooseVariables(needed_moose_vars, tid);
4166  setActiveMaterialProperties(needed_mat_props, tid);
4167 }
4168 
4169 void
4170 FEProblemBase::reinitMaterials(SubdomainID blk_id, const THREAD_ID tid, bool swap_stateful)
4171 {
4172  if (hasActiveMaterialProperties(tid))
4173  {
4174  auto && elem = _assembly[tid][0]->elem();
4175  unsigned int n_points = _assembly[tid][0]->qRule()->n_points();
4176 
4177  auto & material_data = _material_props.getMaterialData(tid);
4178  material_data.resize(n_points);
4179 
4180  // Only swap if requested
4181  if (swap_stateful)
4182  material_data.swap(*elem);
4183 
4184  if (_discrete_materials.hasActiveBlockObjects(blk_id, tid))
4185  material_data.reset(_discrete_materials.getActiveBlockObjects(blk_id, tid));
4186 
4187  if (_materials.hasActiveBlockObjects(blk_id, tid))
4188  material_data.reinit(_materials.getActiveBlockObjects(blk_id, tid));
4189  }
4190 }
4191 
4192 void
4194  const THREAD_ID tid,
4195  const bool swap_stateful,
4196  const std::deque<MaterialBase *> * const reinit_mats)
4197 {
4198  // we reinit more often than needed here because we dont have a way to check whether
4199  // we need to compute the face materials on a particular (possibly external) face
4200  if (hasActiveMaterialProperties(tid))
4201  {
4202  auto && elem = _assembly[tid][0]->elem();
4203  unsigned int side = _assembly[tid][0]->side();
4204  unsigned int n_points = _assembly[tid][0]->qRuleFace()->n_points();
4205 
4206  auto & bnd_material_data = _bnd_material_props.getMaterialData(tid);
4207  bnd_material_data.resize(n_points);
4208 
4209  if (swap_stateful && !bnd_material_data.isSwapped())
4210  bnd_material_data.swap(*elem, side);
4211 
4212  if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
4213  bnd_material_data.reset(
4214  _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(blk_id, tid));
4215 
4216  if (reinit_mats)
4217  bnd_material_data.reinit(*reinit_mats);
4218  else if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
4219  bnd_material_data.reinit(
4220  _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(blk_id, tid));
4221  }
4222 }
4223 
4224 void
4226  const SubdomainID blk_id,
4227  const THREAD_ID tid,
4228  const bool swap_stateful,
4229  const std::deque<MaterialBase *> * const reinit_mats)
4230 {
4231  if (hasActiveMaterialProperties(tid) && (needBoundaryMaterialOnSide(boundary_id, tid) ||
4232  needInterfaceMaterialOnSide(boundary_id, tid) ||
4233  needInternalNeighborSideMaterial(blk_id, tid)))
4234  {
4235  const auto * const elem = _assembly[tid][0]->elem();
4236  unsigned int side = _assembly[tid][0]->side();
4237  unsigned int n_points = _assembly[tid][0]->qRuleFace()->n_points();
4238 
4239  auto & bnd_material_data = _bnd_material_props.getMaterialData(tid);
4240  bnd_material_data.resize(n_points);
4241 
4242  if (swap_stateful && !bnd_material_data.isSwapped())
4243  bnd_material_data.swap(*elem, side);
4244 
4245  if (_discrete_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
4246  bnd_material_data.reset(
4247  _discrete_materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(blk_id, tid));
4248 
4249  if (reinit_mats)
4250  bnd_material_data.reinit(*reinit_mats);
4251  else if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
4252  bnd_material_data.reinit(
4253  _materials[Moose::FACE_MATERIAL_DATA].getActiveBlockObjects(blk_id, tid));
4254  }
4255 }
4256 
4257 void
4259  const BoundaryID boundary_id,
4260  const SubdomainID blk_id,
4261  const THREAD_ID tid,
4262  const bool swap_stateful,
4263  const std::deque<MaterialBase *> * const reinit_mats)
4264 {
4265  // Since objects don't declare whether they need the face or neighbor (side) material properties,
4266  // we use the same criteria for skipping material property computations as for face material
4267  // properties This could be a future optimization.
4268  if (hasActiveMaterialProperties(tid) && (needBoundaryMaterialOnSide(boundary_id, tid) ||
4269  needInterfaceMaterialOnSide(boundary_id, tid) ||
4270  needInternalNeighborSideMaterial(blk_id, tid)))
4271  reinitMaterialsNeighbor(blk_id, tid, swap_stateful, reinit_mats);
4272 }
4273 
4274 void
4276  const THREAD_ID tid,
4277  const bool swap_stateful,
4278  const std::deque<MaterialBase *> * const reinit_mats)
4279 {
4280  if (hasActiveMaterialProperties(tid))
4281  {
4282  // NOTE: this will not work with h-adaptivity
4283  // lindsayad: why not?
4284 
4285  const Elem * neighbor = _assembly[tid][0]->neighbor();
4286  unsigned int neighbor_side = neighbor->which_neighbor_am_i(_assembly[tid][0]->elem());
4287 
4288  mooseAssert(neighbor, "neighbor should be non-null");
4289  mooseAssert(blk_id == neighbor->subdomain_id(),
4290  "The provided blk_id " << blk_id << " and neighbor subdomain ID "
4291  << neighbor->subdomain_id() << " do not match.");
4292 
4293  unsigned int n_points = _assembly[tid][0]->qRuleNeighbor()->n_points();
4294 
4295  auto & neighbor_material_data = _neighbor_material_props.getMaterialData(tid);
4296  neighbor_material_data.resize(n_points);
4297 
4298  // Only swap if requested
4299  if (swap_stateful)
4300  neighbor_material_data.swap(*neighbor, neighbor_side);
4301 
4302  if (_discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
4303  neighbor_material_data.reset(
4304  _discrete_materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(blk_id, tid));
4305 
4306  if (reinit_mats)
4307  neighbor_material_data.reinit(*reinit_mats);
4308  else if (_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
4309  neighbor_material_data.reinit(
4310  _materials[Moose::NEIGHBOR_MATERIAL_DATA].getActiveBlockObjects(blk_id, tid));
4311  }
4312 }
4313 
4314 void
4316  const THREAD_ID tid,
4317  const bool swap_stateful,
4318  const std::deque<MaterialBase *> * const reinit_mats)
4319 {
4320  if (hasActiveMaterialProperties(tid) && needBoundaryMaterialOnSide(boundary_id, tid))
4321  {
4322  auto && elem = _assembly[tid][0]->elem();
4323  unsigned int side = _assembly[tid][0]->side();
4324  unsigned int n_points = _assembly[tid][0]->qRuleFace()->n_points();
4325 
4326  auto & bnd_material_data = _bnd_material_props.getMaterialData(tid);
4327  bnd_material_data.resize(n_points);
4328 
4329  if (swap_stateful && !bnd_material_data.isSwapped())
4330  bnd_material_data.swap(*elem, side);
4331 
4332  if (_discrete_materials.hasActiveBoundaryObjects(boundary_id, tid))
4333  bnd_material_data.reset(_discrete_materials.getActiveBoundaryObjects(boundary_id, tid));
4334 
4335  if (reinit_mats)
4336  bnd_material_data.reinit(*reinit_mats);
4337  else if (_materials.hasActiveBoundaryObjects(boundary_id, tid))
4338  bnd_material_data.reinit(_materials.getActiveBoundaryObjects(boundary_id, tid));
4339  }
4340 }
4341 
4342 void
4344  const THREAD_ID tid,
4345  bool swap_stateful)
4346 {
4347  if (hasActiveMaterialProperties(tid) && needInterfaceMaterialOnSide(boundary_id, tid))
4348  {
4349  const Elem * const & elem = _assembly[tid][0]->elem();
4350  unsigned int side = _assembly[tid][0]->side();
4351  unsigned int n_points = _assembly[tid][0]->qRuleFace()->n_points();
4352 
4353  auto & bnd_material_data = _bnd_material_props.getMaterialData(tid);
4354  bnd_material_data.resize(n_points);
4355 
4356  if (swap_stateful && !bnd_material_data.isSwapped())
4357  bnd_material_data.swap(*elem, side);
4358 
4359  if (_interface_materials.hasActiveBoundaryObjects(boundary_id, tid))
4360  bnd_material_data.reinit(_interface_materials.getActiveBoundaryObjects(boundary_id, tid));
4361  }
4362 }
4363 
4364 void
4366 {
4367  auto && elem = _assembly[tid][0]->elem();
4369 }
4370 
4371 void
4373 {
4374  auto && elem = _assembly[tid][0]->elem();
4375  unsigned int side = _assembly[tid][0]->side();
4376  _bnd_material_props.getMaterialData(tid).swapBack(*elem, side);
4377 }
4378 
4379 void
4381 {
4382  // NOTE: this will not work with h-adaptivity
4383  const Elem * neighbor = _assembly[tid][0]->neighbor();
4384  unsigned int neighbor_side =
4385  neighbor ? neighbor->which_neighbor_am_i(_assembly[tid][0]->elem()) : libMesh::invalid_uint;
4386 
4387  if (!neighbor)
4388  {
4389  if (haveFV())
4390  {
4391  // If neighbor is null, then we're on the neighbor side of a mesh boundary, e.g. we're off
4392  // the mesh in ghost-land. If we're using the finite volume method, then variable values and
4393  // consequently material properties have well-defined values in this ghost region outside of
4394  // the mesh and we really do want to reinit our neighbor materials in this case. Since we're
4395  // off in ghost land it's safe to do swaps with `MaterialPropertyStorage` using the elem and
4396  // elem_side keys
4397  neighbor = _assembly[tid][0]->elem();
4398  neighbor_side = _assembly[tid][0]->side();
4399  mooseAssert(neighbor, "We should have an appropriate value for elem coming from Assembly");
4400  }
4401  else
4402  mooseError("neighbor is null in Assembly!");
4403  }
4404 
4405  _neighbor_material_props.getMaterialData(tid).swapBack(*neighbor, neighbor_side);
4406 }
4407 
4408 void
4409 FEProblemBase::logAdd(const std::string & system,
4410  const std::string & name,
4411  const std::string & type,
4412  const InputParameters & params) const
4413 {
4414  if (_verbose_setup != "false")
4415  _console << "[DBG] Adding " << system << " '" << name << "' of type " << type << std::endl;
4416  if (_verbose_setup == "extra")
4417  _console << params << std::endl;
4418 }
4419 
4420 void
4422  const std::string & object_name,
4423  const std::string & var_param_name)
4424 {
4425  // Due to objects like SolutionUserObject which manipulate libmesh objects
4426  // and variables directly at the back end, we need a default option here
4427  // which is going to be the pointer to the first solver system within this
4428  // problem
4429  unsigned int sys_num = 0;
4430  if (parameters.isParamValid(var_param_name))
4431  {
4432  const auto variable_name = parameters.varName(var_param_name, object_name);
4433  if (this->hasVariable(variable_name) || this->hasScalarVariable(variable_name))
4434  sys_num = getSystem(variable_name).number();
4435  }
4436  if (parameters.isParamValid("solver_sys"))
4437  {
4438  const auto var_sys_num = sys_num;
4439  sys_num = getSystemBase(parameters.get<SolverSystemName>("solver_sys")).number();
4440  if (sys_num != var_sys_num && parameters.isParamValid(var_param_name))
4441  mooseError("We dont support setting 'variable' to a variable that is not set to the same "
4442  "system as the 'solver_sys' parameter");
4443  }
4444 
4445  if (_displaced_problem && parameters.have_parameter<bool>("use_displaced_mesh") &&
4446  parameters.get<bool>("use_displaced_mesh"))
4447  {
4448  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
4449  if (sys_num == _aux->number())
4450  parameters.set<SystemBase *>("_sys") = &_displaced_problem->systemBaseAuxiliary();
4451  else
4452  parameters.set<SystemBase *>("_sys") = &_displaced_problem->solverSys(sys_num);
4453  }
4454  else
4455  {
4456  // The object requested use_displaced_mesh, but it was overridden
4457  // due to there being no displacements variables in the [Mesh] block.
4458  // If that happened, update the value of use_displaced_mesh appropriately.
4459  if (!_displaced_problem && parameters.have_parameter<bool>("use_displaced_mesh") &&
4460  parameters.get<bool>("use_displaced_mesh"))
4461  parameters.set<bool>("use_displaced_mesh") = false;
4462 
4463  parameters.set<SubProblem *>("_subproblem") = this;
4464 
4465  if (sys_num == _aux->number())
4466  parameters.set<SystemBase *>("_sys") = _aux.get();
4467  else
4468  parameters.set<SystemBase *>("_sys") = _solver_systems[sys_num].get();
4469  }
4470 }
4471 
4472 void
4473 FEProblemBase::addPostprocessor(const std::string & pp_name,
4474  const std::string & name,
4475  InputParameters & parameters)
4476 {
4477  // Check for name collision
4478  if (hasUserObject(name))
4479  mooseError("A ",
4481  " already exists. You may not add a Postprocessor by the same name.");
4482 
4483  addUserObject(pp_name, name, parameters);
4484 }
4485 
4486 void
4487 FEProblemBase::addVectorPostprocessor(const std::string & pp_name,
4488  const std::string & name,
4489  InputParameters & parameters)
4490 {
4491  // Check for name collision
4492  if (hasUserObject(name))
4493  mooseError("A ",
4495  " already exists. You may not add a VectorPostprocessor by the same name.");
4496 
4497  addUserObject(pp_name, name, parameters);
4498 }
4499 
4500 void
4501 FEProblemBase::addReporter(const std::string & type,
4502  const std::string & name,
4503  InputParameters & parameters)
4504 {
4505  // Check for name collision
4506  if (hasUserObject(name))
4507  mooseError("A ",
4509  " already exists. You may not add a Reporter by the same name.");
4510 
4512 }
4513 
4514 std::vector<std::shared_ptr<UserObject>>
4515 FEProblemBase::addUserObject(const std::string & user_object_name,
4516  const std::string & name,
4517  InputParameters & parameters)
4518 {
4519  parallel_object_only();
4520 
4521  std::vector<std::shared_ptr<UserObject>> uos;
4522 
4523  // Add the _subproblem and _sys parameters depending on use_displaced_mesh
4525 
4526  for (const auto tid : make_range(libMesh::n_threads()))
4527  {
4528  // Create the UserObject
4529  std::shared_ptr<UserObject> user_object =
4530  _factory.create<UserObject>(user_object_name, name, parameters, tid);
4531  logAdd("UserObject", name, user_object_name, parameters);
4532  uos.push_back(user_object);
4533 
4534  if (tid != 0)
4535  user_object->setPrimaryThreadCopy(uos[0].get());
4536 
4537  // TODO: delete this line after apps have been updated to not call getUserObjects
4538  _all_user_objects.addObject(user_object, tid);
4539 
4540  theWarehouse().add(user_object);
4541 
4542  // Attempt to create all the possible UserObject types
4543  auto euo = std::dynamic_pointer_cast<ElementUserObject>(user_object);
4544  auto suo = std::dynamic_pointer_cast<SideUserObject>(user_object);
4545  auto isuo = std::dynamic_pointer_cast<InternalSideUserObject>(user_object);
4546  auto iuo = std::dynamic_pointer_cast<InterfaceUserObjectBase>(user_object);
4547  auto nuo = std::dynamic_pointer_cast<NodalUserObject>(user_object);
4548  auto duo = std::dynamic_pointer_cast<DomainUserObject>(user_object);
4549  auto guo = std::dynamic_pointer_cast<GeneralUserObject>(user_object);
4550  auto tguo = std::dynamic_pointer_cast<ThreadedGeneralUserObject>(user_object);
4551  auto muo = std::dynamic_pointer_cast<MortarUserObject>(user_object);
4552 
4553  // Account for displaced mesh use
4554  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
4555  {
4556  // Whether to re-init or not depends on the attributes of the base classes.
4557  // For example, InterfaceUOBase has "_current_side_elem" and "_neighbor_elem"
4558  // so it needs to reinit on displaced neighbors and faces
4559  // _reinit_displaced_elem -> _current_elem will be reinited
4560  // _reinit_displaced_face -> _current_elem, lowerD if any and _current_side_elem to be
4561  // reinited _reinit_displaced_neighbor -> _current_elem, lowerD if any and _current_neighbor
4562  // to be reinited Note that as soon as you use materials on the displaced mesh, all three get
4563  // turned on.
4564  if (euo || nuo || duo)
4565  _reinit_displaced_elem = true;
4566  if (suo || duo || isuo || iuo)
4567  _reinit_displaced_face = true;
4568  if (iuo || duo || isuo)
4570  }
4571 
4572  // These objects only require one thread
4573  if ((guo && !tguo) || muo)
4574  break;
4575  }
4576 
4577  // Add as a Functor if it is one. We usually need to add the user object from thread 0 as the
4578  // registered functor for all threads because when user objects are thread joined, generally only
4579  // the primary thread copy ends up with all the data
4580  for (const auto tid : make_range(libMesh::n_threads()))
4581  {
4582  const decltype(uos)::size_type uo_index = uos.front()->needThreadedCopy() ? tid : 0;
4583  if (const auto functor = dynamic_cast<Moose::FunctorBase<Real> *>(uos[uo_index].get()))
4584  {
4585  this->addFunctor(name, *functor, tid);
4586  if (_displaced_problem)
4587  _displaced_problem->addFunctor(name, *functor, tid);
4588  }
4589  }
4590 
4591  return uos;
4592 }
4593 
4594 const UserObject &
4595 FEProblemBase::getUserObjectBase(const std::string & name, const THREAD_ID tid /* = 0 */) const
4596 {
4597  std::vector<UserObject *> objs;
4598  theWarehouse()
4599  .query()
4600  .condition<AttribSystem>("UserObject")
4601  .condition<AttribThread>(tid)
4602  .condition<AttribName>(name)
4603  .queryInto(objs);
4604  if (objs.empty())
4605  mooseError("Unable to find user object with name '" + name + "'");
4606  mooseAssert(objs.size() == 1, "Should only find one UO");
4607  return *(objs[0]);
4608 }
4609 
4610 const Positions &
4611 FEProblemBase::getPositionsObject(const std::string & name) const
4612 {
4613  std::vector<Positions *> objs;
4614  theWarehouse()
4615  .query()
4616  .condition<AttribSystem>("UserObject")
4617  .condition<AttribName>(name)
4618  .queryInto(objs);
4619  if (objs.empty())
4620  mooseError("Unable to find Positions object with name '" + name + "'");
4621  mooseAssert(objs.size() == 1, "Should only find one Positions");
4622  return *(objs[0]);
4623 }
4624 
4625 bool
4626 FEProblemBase::hasUserObject(const std::string & name) const
4627 {
4628  std::vector<UserObject *> objs;
4629  theWarehouse()
4630  .query()
4631  .condition<AttribSystem>("UserObject")
4632  .condition<AttribThread>(0)
4633  .condition<AttribName>(name)
4634  .queryInto(objs);
4635  return !objs.empty();
4636 }
4637 
4638 bool
4639 FEProblemBase::hasPostprocessorValueByName(const PostprocessorName & name) const
4640 {
4642 }
4643 
4644 const PostprocessorValue &
4645 FEProblemBase::getPostprocessorValueByName(const PostprocessorName & name,
4646  std::size_t t_index) const
4647 {
4649  t_index);
4650 }
4651 
4652 void
4653 FEProblemBase::setPostprocessorValueByName(const PostprocessorName & name,
4654  const PostprocessorValue & value,
4655  std::size_t t_index)
4656 {
4658  PostprocessorReporterName(name), value, t_index);
4659 }
4660 
4661 bool
4662 FEProblemBase::hasPostprocessor(const std::string & name) const
4663 {
4664  mooseDeprecated("FEProblemBase::hasPostprocssor is being removed; use "
4665  "hasPostprocessorValueByName instead.");
4667 }
4668 
4671  const std::string & vector_name,
4672  std::size_t t_index) const
4673 {
4675  VectorPostprocessorReporterName(object_name, vector_name), t_index);
4676 }
4677 
4678 void
4680  const std::string & vector_name,
4681  const VectorPostprocessorValue & value,
4682  std::size_t t_index)
4683 {
4685  VectorPostprocessorReporterName(object_name, vector_name), value, t_index);
4686 }
4687 
4688 const VectorPostprocessor &
4690  const THREAD_ID tid) const
4691 {
4692  return getUserObject<VectorPostprocessor>(object_name, tid);
4693 }
4694 
4695 void
4697 {
4698  for (const auto & it : _multi_apps)
4699  {
4700  const auto & objects = it.second.getActiveObjects();
4701  for (const auto & obj : objects)
4702  obj->parentOutputPositionChanged();
4703  }
4704 }
4705 
4706 void
4708 {
4710  computeMarkers();
4711 }
4712 
4713 void
4715 {
4716  // Initialize indicator aux variable fields
4718  {
4719  TIME_SECTION("computeIndicators", 1, "Computing Indicators");
4720 
4721  // Internal side indicators may lead to creating a much larger sparsity pattern than dictated by
4722  // the actual finite element scheme (e.g. CFEM)
4723  const auto old_do_derivatives = ADReal::do_derivatives;
4724  ADReal::do_derivatives = false;
4725 
4726  std::vector<std::string> fields;
4727 
4728  // Indicator Fields
4729  const auto & indicators = _indicators.getActiveObjects();
4730  for (const auto & indicator : indicators)
4731  fields.push_back(indicator->name());
4732 
4733  // InternalSideIndicator Fields
4734  const auto & internal_indicators = _internal_side_indicators.getActiveObjects();
4735  for (const auto & internal_indicator : internal_indicators)
4736  fields.push_back(internal_indicator->name());
4737 
4738  _aux->zeroVariables(fields);
4739 
4740  // compute Indicators
4741  ComputeIndicatorThread cit(*this);
4742  Threads::parallel_reduce(*_mesh.getActiveLocalElementRange(), cit);
4743  _aux->solution().close();
4744  _aux->update();
4745 
4746  ComputeIndicatorThread finalize_cit(*this, true);
4747  Threads::parallel_reduce(*_mesh.getActiveLocalElementRange(), finalize_cit);
4748  _aux->solution().close();
4749  _aux->update();
4750 
4751  ADReal::do_derivatives = old_do_derivatives;
4752  }
4753 }
4754 
4755 void
4757 {
4758  if (_markers.hasActiveObjects())
4759  {
4760  TIME_SECTION("computeMarkers", 1, "Computing Markers");
4761 
4762  std::vector<std::string> fields;
4763 
4764  // Marker Fields
4765  const auto & markers = _markers.getActiveObjects();
4766  for (const auto & marker : markers)
4767  fields.push_back(marker->name());
4768 
4769  _aux->zeroVariables(fields);
4770 
4772 
4773  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
4774  {
4775  const auto & markers = _markers.getActiveObjects(tid);
4776  for (const auto & marker : markers)
4777  marker->markerSetup();
4778  }
4779 
4780  ComputeMarkerThread cmt(*this);
4781  Threads::parallel_reduce(*_mesh.getActiveLocalElementRange(), cmt);
4782 
4783  _aux->solution().close();
4784  _aux->update();
4785  }
4786 }
4787 
4788 const ExecFlagType &
4790 {
4791  return _current_execute_on_flag;
4792 }
4793 
4794 void
4796 {
4797  _current_execute_on_flag = flag;
4798 }
4799 
4800 void
4802 {
4803 }
4804 
4805 void
4807 {
4808  SubProblem::customSetup(exec_type);
4809 
4810  if (_line_search)
4811  _line_search->customSetup(exec_type);
4812 
4813  unsigned int n_threads = libMesh::n_threads();
4814  for (THREAD_ID tid = 0; tid < n_threads; tid++)
4815  {
4816  _all_materials.customSetup(exec_type, tid);
4817  _functions.customSetup(exec_type, tid);
4818  }
4819 
4820 #ifdef MOOSE_KOKKOS_ENABLED
4821  _kokkos_functions.customSetup(exec_type);
4822 #endif
4823 
4824  _aux->customSetup(exec_type);
4825  for (auto & nl : _nl)
4826  nl->customSetup(exec_type);
4827 
4828  if (_displaced_problem)
4829  _displaced_problem->customSetup(exec_type);
4830 
4831  for (THREAD_ID tid = 0; tid < n_threads; tid++)
4832  {
4833  _internal_side_indicators.customSetup(exec_type, tid);
4834  _indicators.customSetup(exec_type, tid);
4835  _markers.customSetup(exec_type, tid);
4836  }
4837 
4838  std::vector<UserObject *> userobjs;
4839  theWarehouse().query().condition<AttribSystem>("UserObject").queryIntoUnsorted(userobjs);
4840  for (auto obj : userobjs)
4841  obj->customSetup(exec_type);
4842 
4843  _app.getOutputWarehouse().customSetup(exec_type);
4844 }
4845 
4846 void
4848 {
4849  // Set the current flag
4850  setCurrentExecuteOnFlag(exec_type);
4851 
4852  if (exec_type != EXEC_INITIAL)
4853  executeControls(exec_type);
4854 
4855  // intentially call this after executing controls because the setups may rely on the controls
4856  // FIXME: we skip the following flags because they have dedicated setup functions in
4857  // SetupInterface and it may not be appropriate to call them here.
4858  if (!(exec_type == EXEC_INITIAL || exec_type == EXEC_TIMESTEP_BEGIN ||
4859  exec_type == EXEC_SUBDOMAIN || exec_type == EXEC_NONLINEAR || exec_type == EXEC_LINEAR))
4860  customSetup(exec_type);
4861 
4862  // Samplers; EXEC_INITIAL is not called because the Sampler::init() method that is called after
4863  // construction makes the first Sampler::execute() call. This ensures that the random number
4864  // generator object is the correct state prior to any other object (e.g., Transfers) attempts to
4865  // extract data from the Sampler. That is, if the Sampler::execute() call is delayed to here
4866  // then it is not in the correct state for other objects.
4867  if (exec_type != EXEC_INITIAL)
4868  executeSamplers(exec_type);
4869 
4870  // Pre-aux UserObjects
4871  computeUserObjects(exec_type, Moose::PRE_AUX);
4872 
4873  // Systems (includes system time derivative and aux kernel calculations)
4874  computeSystems(exec_type);
4875  // With the auxiliary system solution computed, sync the displaced problem auxiliary solution
4876  // before computation of post-aux user objects. The undisplaced auxiliary system current local
4877  // solution is updated (via System::update) within the AuxiliarySystem class's variable
4878  // computation methods (e.g. computeElementalVarsHelper, computeNodalVarsHelper), so it is safe to
4879  // use it here
4880  if (_displaced_problem)
4881  _displaced_problem->syncAuxSolution(*getAuxiliarySystem().currentSolution());
4882 
4883  // Post-aux UserObjects
4884  computeUserObjects(exec_type, Moose::POST_AUX);
4885 
4886  // Return the current flag to None
4888 
4890  {
4891  // we will only check aux variables and postprocessors
4892  // checking more reporter data can be added in the future if needed
4893  std::unique_ptr<NumericVector<Number>> x = _aux->currentSolution()->clone();
4895 
4896  // call THIS execute one more time for checking the possible states
4897  _checking_uo_aux_state = true;
4898  FEProblemBase::execute(exec_type);
4899  _checking_uo_aux_state = false;
4900 
4901  const Real check_tol = 1e-8;
4902 
4903  const Real xnorm = x->l2_norm();
4904  *x -= *_aux->currentSolution();
4905  if (x->l2_norm() > check_tol * xnorm)
4906  {
4907  const auto & sys = _aux->system();
4908  const unsigned int n_vars = sys.n_vars();
4909  std::multimap<Real, std::string, std::greater<Real>> ordered_map;
4910  for (const auto i : make_range(n_vars))
4911  {
4912  const Real vnorm = sys.calculate_norm(*x, i, DISCRETE_L2);
4913  ordered_map.emplace(vnorm, sys.variable_name(i));
4914  }
4915 
4916  std::ostringstream oss;
4917  for (const auto & [error_norm, var_name] : ordered_map)
4918  oss << " {" << var_name << ", " << error_norm << "},\n";
4919 
4920  mooseError("Aux kernels, user objects appear to have states for aux variables on ",
4921  exec_type,
4922  ".\nVariable error norms in descending order:\n",
4923  oss.str());
4924  }
4925 
4927  if (pp_values.size() != new_pp_values.size())
4928  mooseError("Second execution for uo/aux state check should not change the number of "
4929  "real reporter values");
4930 
4931  const Real ppnorm = pp_values.l2_norm();
4932  pp_values -= new_pp_values;
4933  if (pp_values.l2_norm() > check_tol * ppnorm)
4934  {
4935  const auto pp_names = getReporterData().getAllRealReporterFullNames();
4936  std::multimap<Real, std::string, std::greater<Real>> ordered_map;
4937  for (const auto i : index_range(pp_names))
4938  ordered_map.emplace(std::abs(pp_values(i)), pp_names[i]);
4939 
4940  std::ostringstream oss;
4941  for (const auto & [error_norm, pp_name] : ordered_map)
4942  oss << " {" << pp_name << ", " << error_norm << "},\n";
4943 
4944  mooseError("Aux kernels, user objects appear to have states for real reporter values on ",
4945  exec_type,
4946  ".\nErrors of real reporter values in descending order:\n",
4947  oss.str());
4948  }
4949  }
4950 }
4951 
4952 // Finalize, threadJoin, and update PP values of Elemental/Nodal/Side/InternalSideUserObjects
4953 void
4955 {
4956  std::vector<UserObject *> objs;
4957  query.queryInto(objs);
4958  if (!isgen)
4959  {
4960  // join all threaded user objects (i.e. not regular general user objects) to the primary
4961  // thread
4962  for (auto obj : objs)
4963  if (obj->primaryThreadCopy())
4964  obj->primaryThreadCopy()->threadJoin(*obj);
4965  }
4966 
4967  query.condition<AttribThread>(0).queryInto(objs);
4968 
4969  // finalize objects and retrieve/store any postprocessor values
4970  for (auto obj : objs)
4971  {
4972  if (isgen && dynamic_cast<ThreadedGeneralUserObject *>(obj))
4973  continue;
4974  if (isgen)
4975  {
4976  // general user objects are not run in their own threaded loop object - so run them here
4977  if (shouldPrintExecution(0))
4978  _console << "[DBG] Initializing, executing & finalizing general UO '" << obj->name()
4979  << "' on " << _current_execute_on_flag.name() << std::endl;
4980  obj->initialize();
4981  obj->execute();
4982  }
4983 
4984  obj->finalize();
4985 
4986  // These have to be stored piecemeal (with every call to this function) because general
4987  // postprocessors (which run last after other userobjects have been completed) might depend on
4988  // them being stored. This wouldn't be a problem if all userobjects satisfied the dependency
4989  // resolver interface and could be sorted appropriately with the general userobjects, but they
4990  // don't.
4991  auto pp = dynamic_cast<const Postprocessor *>(obj);
4992  if (pp)
4993  {
4994  _reporter_data.finalize(obj->name());
4995  setPostprocessorValueByName(obj->name(), pp->getValue());
4996  }
4997 
4998  auto vpp = dynamic_cast<VectorPostprocessor *>(obj);
4999  if (vpp)
5000  _reporter_data.finalize(obj->name());
5001 
5002  // Update Reporter data
5003  auto reporter = dynamic_cast<Reporter *>(obj);
5004  if (reporter)
5005  _reporter_data.finalize(obj->name());
5006  }
5007 }
5008 
5009 void
5011  const Moose::AuxGroup & group,
5012  const std::string & name)
5013 {
5014  const auto old_exec_flag = _current_execute_on_flag;
5017  .query()
5018  .condition<AttribSystem>("UserObject")
5019  .condition<AttribExecOns>(type)
5020  .condition<AttribName>(name);
5022  _current_execute_on_flag = old_exec_flag;
5023 }
5024 
5025 void
5027 {
5029  theWarehouse().query().condition<AttribSystem>("UserObject").condition<AttribExecOns>(type);
5031 }
5032 
5033 void
5035  const Moose::AuxGroup & group,
5036  TheWarehouse::Query & primary_query)
5037 {
5038  try
5039  {
5040  TIME_SECTION("computeUserObjects", 1, "Computing User Objects");
5041 
5042  // Add group to query
5043  if (group == Moose::PRE_IC)
5044  primary_query.condition<AttribPreIC>(true);
5045  else if (group == Moose::PRE_AUX)
5046  primary_query.condition<AttribPreAux>(type);
5047  else if (group == Moose::POST_AUX)
5048  primary_query.condition<AttribPostAux>(type);
5049 
5050  // query everything first to obtain a list of execution groups
5051  std::vector<UserObject *> uos;
5052  primary_query.clone().queryIntoUnsorted(uos);
5053  std::set<int> execution_groups;
5054  for (const auto & uo : uos)
5055  execution_groups.insert(uo->getParam<int>("execution_order_group"));
5056 
5057  // iterate over execution order groups
5058  for (const auto execution_group : execution_groups)
5059  {
5060  auto query = primary_query.clone().condition<AttribExecutionOrderGroup>(execution_group);
5061 
5062  std::vector<GeneralUserObject *> genobjs;
5063  query.clone().condition<AttribInterfaces>(Interfaces::GeneralUserObject).queryInto(genobjs);
5064 
5065  std::vector<UserObject *> userobjs;
5066  query.clone()
5071  .queryInto(userobjs);
5072 
5073  std::vector<UserObject *> tgobjs;
5074  query.clone()
5076  .queryInto(tgobjs);
5077 
5078  std::vector<UserObject *> nodal;
5079  query.clone().condition<AttribInterfaces>(Interfaces::NodalUserObject).queryInto(nodal);
5080 
5081  std::vector<MortarUserObject *> mortar;
5082  query.clone().condition<AttribInterfaces>(Interfaces::MortarUserObject).queryInto(mortar);
5083 
5084  if (userobjs.empty() && genobjs.empty() && tgobjs.empty() && nodal.empty() && mortar.empty())
5085  continue;
5086 
5087  // Start the timer here since we have at least one active user object
5088  std::string compute_uo_tag = "computeUserObjects(" + Moose::stringify(type) + ")";
5089 
5090  // Perform Residual/Jacobian setups
5091  if (type == EXEC_LINEAR)
5092  {
5093  for (auto obj : userobjs)
5094  obj->residualSetup();
5095  for (auto obj : nodal)
5096  obj->residualSetup();
5097  for (auto obj : mortar)
5098  obj->residualSetup();
5099  for (auto obj : tgobjs)
5100  obj->residualSetup();
5101  for (auto obj : genobjs)
5102  obj->residualSetup();
5103  }
5104  else if (type == EXEC_NONLINEAR)
5105  {
5106  for (auto obj : userobjs)
5107  obj->jacobianSetup();
5108  for (auto obj : nodal)
5109  obj->jacobianSetup();
5110  for (auto obj : mortar)
5111  obj->jacobianSetup();
5112  for (auto obj : tgobjs)
5113  obj->jacobianSetup();
5114  for (auto obj : genobjs)
5115  obj->jacobianSetup();
5116  }
5117 
5118  for (auto obj : userobjs)
5119  obj->initialize();
5120 
5121  // Execute Side/InternalSide/Interface/Elemental/DomainUserObjects
5122  if (!userobjs.empty())
5123  {
5124  // non-nodal user objects have to be run separately before the nodal user objects run
5125  // because some nodal user objects (NodalNormal related) depend on elemental user objects
5126  // :-(
5127  ComputeUserObjectsThread cppt(*this, query);
5128  Threads::parallel_reduce(*_mesh.getActiveLocalElementRange(), cppt);
5129 
5130  // There is one instance in rattlesnake where an elemental user object's finalize depends
5131  // on a side user object having been finalized first :-(
5138  }
5139 
5140  // if any userobject may have written to variables we need to close the aux solution
5141  for (const auto & uo : userobjs)
5142  if (auto euo = dynamic_cast<const ElementUserObject *>(uo);
5143  euo && euo->hasWritableCoupledVariables())
5144  {
5145  _aux->solution().close();
5146  _aux->system().update();
5147  break;
5148  }
5149 
5150  // Execute NodalUserObjects
5151  // BISON has an axial reloc elemental user object that has a finalize func that depends on a
5152  // nodal user object's prev value. So we can't initialize this until after elemental objects
5153  // have been finalized :-(
5154  for (auto obj : nodal)
5155  obj->initialize();
5156  if (query.clone().condition<AttribInterfaces>(Interfaces::NodalUserObject).count() > 0)
5157  {
5158  ComputeNodalUserObjectsThread cnppt(*this, query);
5159  Threads::parallel_reduce(*_mesh.getLocalNodeRange(), cnppt);
5161  }
5162 
5163  // if any userobject may have written to variables we need to close the aux solution
5164  for (const auto & uo : nodal)
5165  if (auto nuo = dynamic_cast<const NodalUserObject *>(uo);
5166  nuo && nuo->hasWritableCoupledVariables())
5167  {
5168  _aux->solution().close();
5169  _aux->system().update();
5170  break;
5171  }
5172 
5173  // Execute MortarUserObjects
5174  {
5175  for (auto obj : mortar)
5176  obj->initialize();
5177  if (!mortar.empty())
5178  {
5179  auto create_and_run_mortar_functors = [this, type, &mortar](const bool displaced)
5180  {
5181  // go over mortar interfaces and construct functors
5182  const auto & mortar_interfaces = getMortarInterfaces(displaced);
5183  for (const auto & [primary_secondary_boundary_pair, mortar_generation_ptr] :
5184  mortar_interfaces)
5185  {
5186  auto mortar_uos_to_execute =
5187  getMortarUserObjects(primary_secondary_boundary_pair.first,
5188  primary_secondary_boundary_pair.second,
5189  displaced,
5190  mortar);
5191 
5192  auto * const subproblem = displaced
5193  ? static_cast<SubProblem *>(_displaced_problem.get())
5194  : static_cast<SubProblem *>(this);
5195  MortarUserObjectThread muot(mortar_uos_to_execute,
5196  *mortar_generation_ptr,
5197  *subproblem,
5198  *this,
5199  displaced,
5200  subproblem->assembly(0, 0));
5201 
5202  muot();
5203  }
5204  };
5205 
5206  create_and_run_mortar_functors(false);
5207  if (_displaced_problem)
5208  create_and_run_mortar_functors(true);
5209  }
5210  for (auto obj : mortar)
5211  obj->finalize();
5212  }
5213 
5214  // Execute threaded general user objects
5215  for (auto obj : tgobjs)
5216  obj->initialize();
5217  std::vector<GeneralUserObject *> tguos_zero;
5218  query.clone()
5219  .condition<AttribThread>(0)
5220  .condition<AttribInterfaces>(Interfaces::ThreadedGeneralUserObject)
5221  .queryInto(tguos_zero);
5222  for (auto obj : tguos_zero)
5223  {
5224  std::vector<GeneralUserObject *> tguos;
5225  auto q = query.clone()
5226  .condition<AttribName>(obj->name())
5227  .condition<AttribInterfaces>(Interfaces::ThreadedGeneralUserObject);
5228  q.queryInto(tguos);
5229 
5231  Threads::parallel_reduce(GeneralUserObjectRange(tguos.begin(), tguos.end()), ctguot);
5232  joinAndFinalize(q);
5233  }
5234 
5235  // Execute general user objects
5237  true);
5238  }
5239  }
5240  catch (...)
5241  {
5242  handleException("computeUserObjectsInternal");
5243  }
5244 }
5245 
5246 void
5248 {
5249  if (_control_warehouse[exec_type].hasActiveObjects())
5250  {
5251  TIME_SECTION("executeControls", 1, "Executing Controls");
5252 
5254 
5255  auto controls_wh = _control_warehouse[exec_type];
5256  // Add all of the dependencies into the resolver and sort them
5257  for (const auto & it : controls_wh.getActiveObjects())
5258  {
5259  // Make sure an item with no dependencies comes out too!
5260  resolver.addItem(it);
5261 
5262  std::vector<std::string> & dependent_controls = it->getDependencies();
5263  for (const auto & depend_name : dependent_controls)
5264  {
5265  if (controls_wh.hasActiveObject(depend_name))
5266  {
5267  auto dep_control = controls_wh.getActiveObject(depend_name);
5268  resolver.addEdge(dep_control, it);
5269  }
5270  else
5271  mooseError("The Control \"",
5272  depend_name,
5273  "\" was not created, did you make a "
5274  "spelling mistake or forget to include it "
5275  "in your input file?");
5276  }
5277  }
5278 
5279  const auto & ordered_controls = resolver.getSortedValues();
5280 
5281  if (!ordered_controls.empty())
5282  {
5283  _control_warehouse.setup(exec_type);
5284  // Run the controls in the proper order
5285  for (const auto & control : ordered_controls)
5286  control->execute();
5287  }
5288  }
5289 }
5290 
5291 void
5293 {
5294  // TODO: This should be done in a threaded loop, but this should be super quick so for now
5295  // do a serial loop.
5296  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
5297  {
5298  std::vector<Sampler *> objects;
5299  theWarehouse()
5300  .query()
5301  .condition<AttribSystem>("Sampler")
5302  .condition<AttribThread>(tid)
5303  .condition<AttribExecOns>(exec_type)
5304  .queryInto(objects);
5305 
5306  if (!objects.empty())
5307  {
5308  TIME_SECTION("executeSamplers", 1, "Executing Samplers");
5309  FEProblemBase::objectSetupHelper<Sampler>(objects, exec_type);
5310  FEProblemBase::objectExecuteHelper<Sampler>(objects);
5311  }
5312  }
5313 }
5314 
5315 void
5317 {
5318  TIME_SECTION("updateActiveObjects", 5, "Updating Active Objects");
5319 
5320  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
5321  {
5322  for (auto & nl : _nl)
5323  nl->updateActive(tid);
5324  _aux->updateActive(tid);
5327  _markers.updateActive(tid);
5329  _materials.updateActive(tid);
5331  }
5332 
5340 
5341 #ifdef MOOSE_KOKKOS_ENABLED
5343 #endif
5344 }
5345 
5346 void
5348 {
5349  //<< "Object " << a->name() << " -> " << b->name() << std::endl;
5350 }
5351 
5352 void
5354 {
5355  TIME_SECTION("reinitBecauseOfGhostingOrNewGeomObjects",
5356  3,
5357  "Reinitializing Because of Geometric Search Objects");
5358 
5359  // Need to see if _any_ processor has ghosted elems or geometry objects.
5360  bool needs_reinit = !_ghosted_elems.empty();
5361  needs_reinit = needs_reinit || !_geometric_search_data._nearest_node_locators.empty() ||
5362  (_mortar_data->hasObjects() && mortar_changed);
5363  needs_reinit =
5364  needs_reinit || (_displaced_problem &&
5365  (!_displaced_problem->geomSearchData()._nearest_node_locators.empty() ||
5366  (_mortar_data->hasDisplacedObjects() && mortar_changed)));
5367  _communicator.max(needs_reinit);
5368 
5369  if (needs_reinit)
5370  {
5371  // Call reinit to get the ghosted vectors correct now that some geometric search has been done
5372  es().reinit();
5373 
5374  if (_displaced_mesh)
5375  _displaced_problem->es().reinit();
5376  }
5377 }
5378 
5379 void
5380 FEProblemBase::addDamper(const std::string & damper_name,
5381  const std::string & name,
5382  InputParameters & parameters)
5383 {
5384  parallel_object_only();
5385 
5386  const auto nl_sys_num =
5387  parameters.isParamValid("variable")
5388  ? determineSolverSystem(parameters.varName("variable", name), true).second
5389  : (unsigned int)0;
5390 
5391  if (!isSolverSystemNonlinear(nl_sys_num))
5392  mooseError("You are trying to add a DGKernel to a linear variable/system, which is not "
5393  "supported at the moment!");
5394 
5395  parameters.set<SubProblem *>("_subproblem") = this;
5396  parameters.set<SystemBase *>("_sys") = _nl[nl_sys_num].get();
5397 
5398  _has_dampers = true;
5399  logAdd("Damper", name, damper_name, parameters);
5400  _nl[nl_sys_num]->addDamper(damper_name, name, parameters);
5401 }
5402 
5403 void
5405 {
5406  for (auto & nl : _nl)
5407  nl->setupDampers();
5408 }
5409 
5410 void
5411 FEProblemBase::addIndicator(const std::string & indicator_name,
5412  const std::string & name,
5413  InputParameters & parameters)
5414 {
5415  parallel_object_only();
5416 
5417  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
5418  {
5419  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
5420  parameters.set<SystemBase *>("_sys") = &_displaced_problem->auxSys();
5421  _reinit_displaced_elem = true;
5422  }
5423  else
5424  {
5425  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
5426  {
5427  // We allow Indicators to request that they use_displaced_mesh,
5428  // but then be overridden when no displacements variables are
5429  // provided in the Mesh block. If that happened, update the value
5430  // of use_displaced_mesh appropriately for this Indicator.
5431  if (parameters.have_parameter<bool>("use_displaced_mesh"))
5432  parameters.set<bool>("use_displaced_mesh") = false;
5433  }
5434 
5435  parameters.set<SubProblem *>("_subproblem") = this;
5436  parameters.set<SystemBase *>("_sys") = _aux.get();
5437  }
5438 
5439  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
5440  {
5441  std::shared_ptr<Indicator> indicator =
5442  _factory.create<Indicator>(indicator_name, name, parameters, tid);
5443  logAdd("Indicator", name, indicator_name, parameters);
5444  std::shared_ptr<InternalSideIndicatorBase> isi =
5446  if (isi)
5448  else
5449  _indicators.addObject(indicator, tid);
5450  }
5451 }
5452 
5453 void
5454 FEProblemBase::addMarker(const std::string & marker_name,
5455  const std::string & name,
5456  InputParameters & parameters)
5457 {
5458  parallel_object_only();
5459 
5460  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
5461  {
5462  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
5463  parameters.set<SystemBase *>("_sys") = &_displaced_problem->auxSys();
5464  _reinit_displaced_elem = true;
5465  }
5466  else
5467  {
5468  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
5469  {
5470  // We allow Markers to request that they use_displaced_mesh,
5471  // but then be overridden when no displacements variables are
5472  // provided in the Mesh block. If that happened, update the value
5473  // of use_displaced_mesh appropriately for this Marker.
5474  if (parameters.have_parameter<bool>("use_displaced_mesh"))
5475  parameters.set<bool>("use_displaced_mesh") = false;
5476  }
5477 
5478  parameters.set<SubProblem *>("_subproblem") = this;
5479  parameters.set<SystemBase *>("_sys") = _aux.get();
5480  }
5481 
5482  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
5483  {
5484  std::shared_ptr<Marker> marker = _factory.create<Marker>(marker_name, name, parameters, tid);
5485  logAdd("Marker", name, marker_name, parameters);
5486  _markers.addObject(marker, tid);
5487  }
5488 }
5489 
5490 void
5491 FEProblemBase::addMultiApp(const std::string & multi_app_name,
5492  const std::string & name,
5493  InputParameters & parameters)
5494 {
5495  parallel_object_only();
5496 
5497  parameters.set<MPI_Comm>("_mpi_comm") = _communicator.get();
5498 
5499  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
5500  {
5501  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
5502  parameters.set<SystemBase *>("_sys") = &_displaced_problem->auxSys();
5503  _reinit_displaced_elem = true;
5504  }
5505  else
5506  {
5507  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
5508  {
5509  // We allow MultiApps to request that they use_displaced_mesh,
5510  // but then be overridden when no displacements variables are
5511  // provided in the Mesh block. If that happened, update the value
5512  // of use_displaced_mesh appropriately for this MultiApp.
5513  if (parameters.have_parameter<bool>("use_displaced_mesh"))
5514  parameters.set<bool>("use_displaced_mesh") = false;
5515  }
5516 
5517  parameters.set<SubProblem *>("_subproblem") = this;
5518  parameters.set<SystemBase *>("_sys") = _aux.get();
5519  }
5520 
5521  std::shared_ptr<MultiApp> multi_app = _factory.create<MultiApp>(multi_app_name, name, parameters);
5522  logAdd("MultiApp", name, multi_app_name, parameters);
5523  multi_app->setupPositions();
5524 
5525  _multi_apps.addObject(multi_app);
5526 
5527  // Store TransientMultiApp objects in another container, this is needed for calling computeDT
5528  std::shared_ptr<TransientMultiApp> trans_multi_app =
5530  if (trans_multi_app)
5531  _transient_multi_apps.addObject(trans_multi_app);
5532 }
5533 
5534 bool
5536 {
5537  return _multi_apps[type].hasActiveObjects();
5538 }
5539 
5540 bool
5541 FEProblemBase::hasMultiApp(const std::string & multi_app_name) const
5542 {
5543  return _multi_apps.hasActiveObject(multi_app_name);
5544 }
5545 
5546 std::shared_ptr<MultiApp>
5547 FEProblemBase::getMultiApp(const std::string & multi_app_name) const
5548 {
5549  return _multi_apps.getObject(multi_app_name);
5550 }
5551 
5552 void
5554 {
5555  bool to_multiapp = direction == MultiAppTransfer::TO_MULTIAPP;
5556  bool from_multiapp = direction == MultiAppTransfer::FROM_MULTIAPP;
5557  std::string string_direction;
5558  if (to_multiapp)
5559  string_direction = " To ";
5560  else if (from_multiapp)
5561  string_direction = " From ";
5562  else
5563  string_direction = " Between ";
5564 
5565  const MooseObjectWarehouse<Transfer> & wh = to_multiapp ? _to_multi_app_transfers[type]
5566  : from_multiapp ? _from_multi_app_transfers[type]
5568 
5569  if (wh.hasActiveObjects())
5570  {
5571  TIME_SECTION("execMultiAppTransfers", 1, "Executing Transfers");
5572 
5573  const auto & transfers = wh.getActiveObjects();
5574 
5575  if (_verbose_multiapps)
5576  {
5577  _console << COLOR_CYAN << "\nTransfers on " << Moose::stringify(type) << string_direction
5578  << "MultiApps" << COLOR_DEFAULT << ":" << std::endl;
5579 
5581  {"Name", "Type", "From", "To"});
5582 
5583  // Build Table of Transfer Info
5584  for (const auto & transfer : transfers)
5585  {
5586  auto multiapp_transfer = dynamic_cast<MultiAppTransfer *>(transfer.get());
5587 
5588  table.addRow(multiapp_transfer->name(),
5589  multiapp_transfer->type(),
5590  multiapp_transfer->getFromName(),
5591  multiapp_transfer->getToName());
5592  }
5593 
5594  // Print it
5595  table.print(_console);
5596  }
5597 
5598  for (const auto & transfer : transfers)
5599  {
5600  transfer->setCurrentDirection(direction);
5601  transfer->execute();
5602  }
5603 
5605 
5606  if (_verbose_multiapps)
5607  _console << COLOR_CYAN << "Transfers on " << Moose::stringify(type) << " Are Finished\n"
5608  << COLOR_DEFAULT << std::endl;
5609  }
5610  else if (_multi_apps[type].getActiveObjects().size())
5611  {
5612  if (_verbose_multiapps)
5613  _console << COLOR_CYAN << "\nNo Transfers on " << Moose::stringify(type) << string_direction
5614  << "MultiApps\n"
5615  << COLOR_DEFAULT << std::endl;
5616  }
5617 }
5618 
5619 std::vector<std::shared_ptr<Transfer>>
5621 {
5622  if (direction == MultiAppTransfer::TO_MULTIAPP)
5624  else if (direction == MultiAppTransfer::FROM_MULTIAPP)
5626  else
5628 }
5629 
5630 std::vector<std::shared_ptr<Transfer>>
5632 {
5633  if (direction == MultiAppTransfer::TO_MULTIAPP)
5635  else if (direction == MultiAppTransfer::FROM_MULTIAPP)
5637  else
5639 }
5640 
5643 {
5644  if (direction == MultiAppTransfer::TO_MULTIAPP)
5645  return _to_multi_app_transfers;
5646  else if (direction == MultiAppTransfer::FROM_MULTIAPP)
5648  else
5650 }
5651 
5652 bool
5654 {
5655  // Active MultiApps
5656  const std::vector<MooseSharedPointer<MultiApp>> & multi_apps =
5658 
5659  // Do anything that needs to be done to Apps before transfers
5660  for (const auto & multi_app : multi_apps)
5661  multi_app->preTransfer(_dt, _time);
5662 
5663  // Execute Transfers _to_ MultiApps
5665 
5666  // Execute Transfers _between_ Multiapps
5668 
5669  // Execute MultiApps
5670  if (multi_apps.size())
5671  {
5672  TIME_SECTION("execMultiApps", 1, "Executing MultiApps", false);
5673 
5674  if (_verbose_multiapps)
5675  _console << COLOR_CYAN << "\nExecuting MultiApps on " << Moose::stringify(type)
5676  << COLOR_DEFAULT << std::endl;
5677 
5678  bool success = true;
5679 
5680  for (const auto & multi_app : multi_apps)
5681  {
5682  success = multi_app->solveStep(_dt, _time, auto_advance);
5683  // no need to finish executing the subapps if one fails
5684  if (!success)
5685  break;
5686  }
5687 
5689 
5690  _communicator.min(success);
5691 
5692  if (!success)
5693  return false;
5694 
5695  if (_verbose_multiapps)
5696  _console << COLOR_CYAN << "Finished Executing MultiApps on " << Moose::stringify(type) << "\n"
5697  << COLOR_DEFAULT << std::endl;
5698  }
5699 
5700  // Execute Transfers _from_ MultiApps
5702 
5703  // If we made it here then everything passed
5704  return true;
5705 }
5706 
5707 void
5709 {
5710  const auto & multi_apps = _multi_apps.getActiveObjects();
5711 
5712  for (const auto & multi_app : multi_apps)
5713  multi_app->finalize();
5714 }
5715 
5716 void
5718 {
5719  const auto & multi_apps = _multi_apps.getActiveObjects();
5720 
5721  for (const auto & multi_app : multi_apps)
5722  multi_app->postExecute();
5723 }
5724 
5725 void
5727 {
5728  const auto & multi_apps = _multi_apps[type].getActiveObjects();
5729 
5730  if (multi_apps.size())
5731  for (const auto & multi_app : multi_apps)
5732  multi_app->incrementTStep(_time);
5733 }
5734 
5735 void
5736 FEProblemBase::finishMultiAppStep(ExecFlagType type, bool recurse_through_multiapp_levels)
5737 {
5738  const auto & multi_apps = _multi_apps[type].getActiveObjects();
5739 
5740  if (multi_apps.size())
5741  {
5742  if (_verbose_multiapps)
5743  _console << COLOR_CYAN << "\nAdvancing MultiApps on " << type.name() << COLOR_DEFAULT
5744  << std::endl;
5745 
5746  for (const auto & multi_app : multi_apps)
5747  multi_app->finishStep(recurse_through_multiapp_levels);
5748 
5750 
5751  if (_verbose_multiapps)
5752  _console << COLOR_CYAN << "Finished Advancing MultiApps on " << type.name() << "\n"
5753  << COLOR_DEFAULT << std::endl;
5754  }
5755 }
5756 
5757 void
5759 {
5760  const auto & multi_apps = _multi_apps[type].getActiveObjects();
5761 
5762  if (multi_apps.size())
5763  {
5764  TIME_SECTION("backupMultiApps", 5, "Backing Up MultiApp");
5765 
5766  if (_verbose_multiapps)
5767  _console << COLOR_CYAN << "\nBacking Up MultiApps on " << type.name() << COLOR_DEFAULT
5768  << std::endl;
5769 
5770  for (const auto & multi_app : multi_apps)
5771  multi_app->backup();
5772 
5774 
5775  if (_verbose_multiapps)
5776  _console << COLOR_CYAN << "Finished Backing Up MultiApps on " << type.name() << "\n"
5777  << COLOR_DEFAULT << std::endl;
5778  }
5779 }
5780 
5781 void
5783 {
5784  const auto & multi_apps = _multi_apps[type].getActiveObjects();
5785 
5786  if (multi_apps.size())
5787  {
5788  if (_verbose_multiapps)
5789  {
5790  if (force)
5791  _console << COLOR_CYAN << "\nRestoring Multiapps on " << type.name()
5792  << " because of solve failure!" << COLOR_DEFAULT << std::endl;
5793  else
5794  _console << COLOR_CYAN << "\nRestoring MultiApps on " << type.name() << COLOR_DEFAULT
5795  << std::endl;
5796  }
5797 
5798  for (const auto & multi_app : multi_apps)
5799  multi_app->restore(force);
5800 
5802 
5803  if (_verbose_multiapps)
5804  _console << COLOR_CYAN << "Finished Restoring MultiApps on " << type.name() << "\n"
5805  << COLOR_DEFAULT << std::endl;
5806  }
5807 }
5808 
5809 Real
5811 {
5812  const auto & multi_apps = _transient_multi_apps[type].getActiveObjects();
5813 
5814  Real smallest_dt = std::numeric_limits<Real>::max();
5815 
5816  for (const auto & multi_app : multi_apps)
5817  smallest_dt = std::min(smallest_dt, multi_app->computeDT());
5818 
5819  return smallest_dt;
5820 }
5821 
5822 void
5824 {
5825  if (_transfers[type].hasActiveObjects())
5826  {
5827  TIME_SECTION("execTransfers", 3, "Executing Transfers");
5828 
5829  const auto & transfers = _transfers[type].getActiveObjects();
5830 
5831  for (const auto & transfer : transfers)
5832  transfer->execute();
5833  }
5834 }
5835 
5836 void
5837 FEProblemBase::addTransfer(const std::string & transfer_name,
5838  const std::string & name,
5839  InputParameters & parameters)
5840 {
5841  parallel_object_only();
5842 
5843  if (_displaced_problem && parameters.get<bool>("use_displaced_mesh"))
5844  {
5845  parameters.set<SubProblem *>("_subproblem") = _displaced_problem.get();
5846  parameters.set<SystemBase *>("_sys") = &_displaced_problem->auxSys();
5847  _reinit_displaced_elem = true;
5848  }
5849  else
5850  {
5851  if (_displaced_problem == nullptr && parameters.get<bool>("use_displaced_mesh"))
5852  {
5853  // We allow Transfers to request that they use_displaced_mesh,
5854  // but then be overridden when no displacements variables are
5855  // provided in the Mesh block. If that happened, update the value
5856  // of use_displaced_mesh appropriately for this Transfer.
5857  if (parameters.have_parameter<bool>("use_displaced_mesh"))
5858  parameters.set<bool>("use_displaced_mesh") = false;
5859  }
5860 
5861  parameters.set<SubProblem *>("_subproblem") = this;
5862  parameters.set<SystemBase *>("_sys") = _aux.get();
5863  }
5864 
5865  // Handle the "SAME_AS_MULTIAPP" execute option. The get method is used to test for the
5866  // flag so the set by user flag is not reset, calling set with the true flag causes the set
5867  // by user status to be reset, which should only be done if the EXEC_SAME_AS_MULTIAPP is
5868  // being applied to the object.
5870  {
5871  ExecFlagEnum & exec_enum = parameters.set<ExecFlagEnum>("execute_on", true);
5872  std::shared_ptr<MultiApp> multiapp;
5873  if (parameters.isParamValid("multi_app"))
5874  multiapp = getMultiApp(parameters.get<MultiAppName>("multi_app"));
5875  // This catches the sibling transfer case, where we want to be executing only as often as the
5876  // receiving application. A transfer 'to' a multiapp is executed before that multiapp
5877  else if (parameters.isParamValid("to_multi_app"))
5878  multiapp = getMultiApp(parameters.get<MultiAppName>("to_multi_app"));
5879  else if (parameters.isParamValid("from_multi_app"))
5880  multiapp = getMultiApp(parameters.get<MultiAppName>("from_multi_app"));
5881  // else do nothing because the user has provided invalid input. They should get a nice error
5882  // about this during transfer construction. This necessitates checking for null in this next
5883  // line, however
5884  if (multiapp)
5885  exec_enum = multiapp->getParam<ExecFlagEnum>("execute_on");
5886  }
5887 
5888  // Create the Transfer objects
5889  std::shared_ptr<Transfer> transfer = _factory.create<Transfer>(transfer_name, name, parameters);
5890  logAdd("Transfer", name, transfer_name, parameters);
5891 
5892  // Add MultiAppTransfer object
5893  std::shared_ptr<MultiAppTransfer> multi_app_transfer =
5895  if (multi_app_transfer)
5896  {
5897  if (multi_app_transfer->directions().isValueSet(MultiAppTransfer::TO_MULTIAPP))
5898  _to_multi_app_transfers.addObject(multi_app_transfer);
5899  if (multi_app_transfer->directions().isValueSet(MultiAppTransfer::FROM_MULTIAPP))
5900  _from_multi_app_transfers.addObject(multi_app_transfer);
5901  if (multi_app_transfer->directions().isValueSet(MultiAppTransfer::BETWEEN_MULTIAPP))
5902  _between_multi_app_transfers.addObject(multi_app_transfer);
5903  }
5904  else
5905  _transfers.addObject(transfer);
5906 }
5907 
5908 bool
5909 FEProblemBase::hasVariable(const std::string & var_name) const
5910 {
5911  for (auto & sys : _solver_systems)
5912  if (sys->hasVariable(var_name))
5913  return true;
5914  if (_aux->hasVariable(var_name))
5915  return true;
5916 
5917  return false;
5918 }
5919 
5920 bool
5921 FEProblemBase::hasSolverVariable(const std::string & var_name) const
5922 {
5923  for (auto & sys : _solver_systems)
5924  if (sys->hasVariable(var_name))
5925  return true;
5926 
5927  return false;
5928 }
5929 
5930 const MooseVariableFieldBase &
5932  const std::string & var_name,
5933  Moose::VarKindType expected_var_type,
5934  Moose::VarFieldType expected_var_field_type) const
5935 {
5936  return getVariableHelper(
5937  tid, var_name, expected_var_type, expected_var_field_type, _solver_systems, *_aux);
5938 }
5939 
5940 MooseVariable &
5941 FEProblemBase::getStandardVariable(const THREAD_ID tid, const std::string & var_name)
5942 {
5943  for (auto & sys : _solver_systems)
5944  if (sys->hasVariable(var_name))
5945  return sys->getFieldVariable<Real>(tid, var_name);
5946  if (_aux->hasVariable(var_name))
5947  return _aux->getFieldVariable<Real>(tid, var_name);
5948 
5949  mooseError("Unknown variable " + var_name);
5950 }
5951 
5953 FEProblemBase::getActualFieldVariable(const THREAD_ID tid, const std::string & var_name)
5954 {
5955  for (auto & sys : _solver_systems)
5956  if (sys->hasVariable(var_name))
5957  return sys->getActualFieldVariable<Real>(tid, var_name);
5958  if (_aux->hasVariable(var_name))
5959  return _aux->getActualFieldVariable<Real>(tid, var_name);
5960 
5961  mooseError("Unknown variable " + var_name);
5962 }
5963 
5965 FEProblemBase::getVectorVariable(const THREAD_ID tid, const std::string & var_name)
5966 {
5967  for (auto & sys : _solver_systems)
5968  if (sys->hasVariable(var_name))
5969  return sys->getFieldVariable<RealVectorValue>(tid, var_name);
5970  if (_aux->hasVariable(var_name))
5971  return _aux->getFieldVariable<RealVectorValue>(tid, var_name);
5972 
5973  mooseError("Unknown variable " + var_name);
5974 }
5975 
5977 FEProblemBase::getArrayVariable(const THREAD_ID tid, const std::string & var_name)
5978 {
5979  for (auto & sys : _solver_systems)
5980  if (sys->hasVariable(var_name))
5981  return sys->getFieldVariable<RealEigenVector>(tid, var_name);
5982  if (_aux->hasVariable(var_name))
5983  return _aux->getFieldVariable<RealEigenVector>(tid, var_name);
5984 
5985  mooseError("Unknown variable " + var_name);
5986 }
5987 
5988 bool
5989 FEProblemBase::hasScalarVariable(const std::string & var_name) const
5990 {
5991  for (auto & sys : _solver_systems)
5992  if (sys->hasScalarVariable(var_name))
5993  return true;
5994  if (_aux->hasScalarVariable(var_name))
5995  return true;
5996 
5997  return false;
5998 }
5999 
6001 FEProblemBase::getScalarVariable(const THREAD_ID tid, const std::string & var_name)
6002 {
6003  for (auto & sys : _solver_systems)
6004  if (sys->hasScalarVariable(var_name))
6005  return sys->getScalarVariable(tid, var_name);
6006  if (_aux->hasScalarVariable(var_name))
6007  return _aux->getScalarVariable(tid, var_name);
6008 
6009  mooseError("Unknown variable " + var_name);
6010 }
6011 
6012 System &
6013 FEProblemBase::getSystem(const std::string & var_name)
6014 {
6015  const auto [var_in_sys, sys_num] = determineSolverSystem(var_name);
6016  if (var_in_sys)
6017  return _solver_systems[sys_num]->system();
6018  else if (_aux->hasVariable(var_name) || _aux->hasScalarVariable(var_name))
6019  return _aux->system();
6020  else
6021  mooseError("Unable to find a system containing the variable " + var_name);
6022 }
6023 
6026 {
6027  return _req.get();
6028 }
6029 
6030 void
6032 {
6034 
6035  if (_displaced_problem)
6036  _displaced_problem->setActiveFEVariableCoupleableMatrixTags(mtags, tid);
6037 }
6038 
6039 void
6041 {
6043 
6044  if (_displaced_problem)
6045  _displaced_problem->setActiveFEVariableCoupleableVectorTags(vtags, tid);
6046 }
6047 
6048 void
6050  const THREAD_ID tid)
6051 {
6053 
6054  if (_displaced_problem)
6055  _displaced_problem->setActiveScalarVariableCoupleableMatrixTags(mtags, tid);
6056 }
6057 
6058 void
6060  const THREAD_ID tid)
6061 {
6063 
6064  if (_displaced_problem)
6065  _displaced_problem->setActiveScalarVariableCoupleableVectorTags(vtags, tid);
6066 }
6067 
6068 void
6069 FEProblemBase::setActiveElementalMooseVariables(const std::set<MooseVariableFEBase *> & moose_vars,
6070  const THREAD_ID tid)
6071 {
6073 
6074  if (_displaced_problem)
6075  _displaced_problem->setActiveElementalMooseVariables(moose_vars, tid);
6076 }
6077 
6078 void
6080 {
6082 
6083  if (_displaced_problem)
6084  _displaced_problem->clearActiveElementalMooseVariables(tid);
6085 }
6086 
6087 void
6089 {
6091 
6092  if (_displaced_problem)
6093  _displaced_problem->clearActiveFEVariableCoupleableMatrixTags(tid);
6094 }
6095 
6096 void
6098 {
6100 
6101  if (_displaced_problem)
6102  _displaced_problem->clearActiveFEVariableCoupleableVectorTags(tid);
6103 }
6104 
6105 void
6107 {
6109 
6110  if (_displaced_problem)
6111  _displaced_problem->clearActiveScalarVariableCoupleableMatrixTags(tid);
6112 }
6113 
6114 void
6116 {
6118 
6119  if (_displaced_problem)
6120  _displaced_problem->clearActiveScalarVariableCoupleableVectorTags(tid);
6121 }
6122 
6123 void
6124 FEProblemBase::setActiveMaterialProperties(const std::unordered_set<unsigned int> & mat_prop_ids,
6125  const THREAD_ID tid)
6126 {
6127  // mark active properties in every material
6128  for (auto & mat : _all_materials.getObjects(tid))
6129  mat->setActiveProperties(mat_prop_ids);
6130  for (auto & mat : _all_materials[Moose::FACE_MATERIAL_DATA].getObjects(tid))
6131  mat->setActiveProperties(mat_prop_ids);
6132  for (auto & mat : _all_materials[Moose::NEIGHBOR_MATERIAL_DATA].getObjects(tid))
6133  mat->setActiveProperties(mat_prop_ids);
6134 
6135  _has_active_material_properties[tid] = !mat_prop_ids.empty();
6136 }
6137 
6138 bool
6140 {
6141  return _has_active_material_properties[tid];
6142 }
6143 
6144 void
6146 {
6148 }
6149 
6150 void
6152 {
6153 #ifdef LIBMESH_ENABLE_AMR
6154  if ((_adaptivity.isOn() || _num_grid_steps) &&
6157  {
6158  // Even on a serialized Mesh, we don't keep our material
6159  // properties serialized, so we'll rely on the callback to
6160  // redistribute() to redistribute properties at the same time
6161  // libMesh is redistributing elements.
6162  auto add_redistributer = [this](MooseMesh & mesh,
6163  const std::string & redistributer_name,
6164  const bool use_displaced_mesh)
6165  {
6166  InputParameters redistribute_params = RedistributeProperties::validParams();
6167  redistribute_params.set<MooseApp *>(MooseBase::app_param) = &_app;
6168  redistribute_params.set<std::string>("for_whom") = this->name();
6169  redistribute_params.set<MooseMesh *>("mesh") = &mesh;
6170  redistribute_params.set<Moose::RelationshipManagerType>("rm_type") =
6172  redistribute_params.set<bool>("use_displaced_mesh") = use_displaced_mesh;
6173  redistribute_params.setHitNode(*parameters().getHitNode(), {});
6174 
6175  std::shared_ptr<RedistributeProperties> redistributer =
6177  "RedistributeProperties", redistributer_name, redistribute_params);
6178 
6181 
6183  redistributer->addMaterialPropertyStorage(_bnd_material_props);
6184 
6186  redistributer->addMaterialPropertyStorage(_neighbor_material_props);
6187 
6188  mesh.getMesh().add_ghosting_functor(redistributer);
6189  };
6190 
6191  add_redistributer(_mesh, "mesh_property_redistributer", false);
6192  if (_displaced_problem)
6193  add_redistributer(_displaced_problem->mesh(), "displaced_mesh_property_redistributer", true);
6194  }
6195 #endif // LIBMESH_ENABLE_AMR
6196 }
6197 
6198 void
6200 {
6201  // Find the maximum number of quadrature points
6202  {
6203  MaxQpsThread mqt(*this);
6204  Threads::parallel_reduce(*_mesh.getActiveLocalElementRange(), mqt);
6205  _max_qps = mqt.max();
6206 
6207  // If we have more shape functions or more quadrature points on
6208  // another processor, then we may need to handle those elements
6209  // ourselves later after repartitioning.
6211  }
6212 
6213  unsigned int max_qpts = getMaxQps();
6214  if (max_qpts > Moose::constMaxQpsPerElem)
6215  mooseError("Max quadrature points per element assumptions made in some code (e.g. Coupleable ",
6216  "and MaterialPropertyInterface classes) have been violated.\n",
6217  "Complain to Moose developers to have constMaxQpsPerElem increased from ",
6219  " to ",
6220  max_qpts);
6221  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
6222  {
6223  // the highest available order in libMesh is 43
6224  _scalar_zero[tid].resize(FORTYTHIRD, 0);
6225  _zero[tid].resize(max_qpts, 0);
6226  _ad_zero[tid].resize(max_qpts, 0);
6227  _grad_zero[tid].resize(max_qpts, RealGradient(0.));
6228  _ad_grad_zero[tid].resize(max_qpts, ADRealGradient(0));
6229  _second_zero[tid].resize(max_qpts, RealTensor(0.));
6230  _ad_second_zero[tid].resize(max_qpts, ADRealTensorValue(0));
6231  _vector_zero[tid].resize(max_qpts, RealGradient(0.));
6232  _vector_curl_zero[tid].resize(max_qpts, RealGradient(0.));
6233  }
6234 }
6235 
6236 void
6238 {
6239  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
6240  for (const auto i : index_range(_nl))
6241  _assembly[tid][i]->bumpVolumeQRuleOrder(order, block);
6242 
6243  if (_displaced_problem)
6244  _displaced_problem->bumpVolumeQRuleOrder(order, block);
6245 
6246  updateMaxQps();
6247 }
6248 
6249 void
6251 {
6252  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
6253  for (const auto i : index_range(_nl))
6254  _assembly[tid][i]->bumpAllQRuleOrder(order, block);
6255 
6256  if (_displaced_problem)
6257  _displaced_problem->bumpAllQRuleOrder(order, block);
6258 
6259  updateMaxQps();
6260 }
6261 
6262 void
6264  Order order,
6265  Order volume_order,
6266  Order face_order,
6267  SubdomainID block,
6268  const bool allow_negative_qweights)
6269 {
6270  if (order == INVALID_ORDER)
6271  {
6272  // automatically determine the integration order
6273  order = _solver_systems[0]->getMinQuadratureOrder();
6274  for (const auto i : make_range(std::size_t(1), _solver_systems.size()))
6275  if (order < _solver_systems[i]->getMinQuadratureOrder())
6276  order = _solver_systems[i]->getMinQuadratureOrder();
6277  if (order < _aux->getMinQuadratureOrder())
6278  order = _aux->getMinQuadratureOrder();
6279  }
6280 
6281  if (volume_order == INVALID_ORDER)
6282  volume_order = order;
6283 
6284  if (face_order == INVALID_ORDER)
6285  face_order = order;
6286 
6287  for (unsigned int tid = 0; tid < libMesh::n_threads(); ++tid)
6288  for (const auto i : index_range(_solver_systems))
6289  _assembly[tid][i]->createQRules(
6290  type, order, volume_order, face_order, block, allow_negative_qweights);
6291 
6292  if (_displaced_problem)
6293  _displaced_problem->createQRules(
6294  type, order, volume_order, face_order, block, allow_negative_qweights);
6295 
6296  updateMaxQps();
6297 }
6298 
6299 void
6301 {
6303  {
6305  mooseError("Someone told us (the FEProblemBase) to trust the user coupling matrix, but we "
6306  "haven't been provided a coupling matrix!");
6307 
6308  // We've been told to trust the user coupling matrix, so we're going to leave things alone
6309  return;
6310  }
6311 
6312  _coupling = type;
6313 }
6314 
6315 void
6317 {
6318  // TODO: Deprecate method
6320  _cm[i].reset(cm);
6321 }
6322 
6323 void
6324 FEProblemBase::setCouplingMatrix(std::unique_ptr<CouplingMatrix> cm, const unsigned int i)
6325 {
6327  _cm[i] = std::move(cm);
6328 }
6329 
6330 void
6332 {
6334  mooseError("Someone told us (the FEProblemBase) to trust the user coupling matrix, but we "
6335  "haven't been provided a coupling matrix!");
6336 
6338 }
6339 
6340 void
6342 {
6343  TIME_SECTION("setNonlocalCouplingMatrix", 5, "Setting Nonlocal Coupling Matrix");
6344 
6345  if (_nl.size() > 1)
6346  mooseError("Nonlocal kernels are weirdly stored on the FEProblem so we don't currently support "
6347  "multiple nonlinear systems with nonlocal kernels.");
6348 
6349  for (const auto nl_sys_num : index_range(_nl))
6350  {
6351  auto & nl = _nl[nl_sys_num];
6352  auto & nonlocal_cm = _nonlocal_cm[nl_sys_num];
6353  unsigned int n_vars = nl->nVariables();
6354  nonlocal_cm.resize(n_vars);
6355  const auto & vars = nl->getVariables(0);
6356  const auto & nonlocal_kernel = _nonlocal_kernels.getObjects();
6357  const auto & nonlocal_integrated_bc = _nonlocal_integrated_bcs.getObjects();
6358  for (const auto & ivar : vars)
6359  {
6360  for (const auto & kernel : nonlocal_kernel)
6361  {
6362  for (unsigned int i = ivar->number(); i < ivar->number() + ivar->count(); ++i)
6363  if (i == kernel->variable().number())
6364  for (const auto & jvar : vars)
6365  {
6366  const auto it = _var_dof_map.find(jvar->name());
6367  if (it != _var_dof_map.end())
6368  {
6369  unsigned int j = jvar->number();
6370  nonlocal_cm(i, j) = 1;
6371  }
6372  }
6373  }
6374  for (const auto & integrated_bc : nonlocal_integrated_bc)
6375  {
6376  for (unsigned int i = ivar->number(); i < ivar->number() + ivar->count(); ++i)
6377  if (i == integrated_bc->variable().number())
6378  for (const auto & jvar : vars)
6379  {
6380  const auto it = _var_dof_map.find(jvar->name());
6381  if (it != _var_dof_map.end())
6382  {
6383  unsigned int j = jvar->number();
6384  nonlocal_cm(i, j) = 1;
6385  }
6386  }
6387  }
6388  }
6389  }
6390 }
6391 
6392 bool
6393 FEProblemBase::areCoupled(const unsigned int ivar,
6394  const unsigned int jvar,
6395  const unsigned int nl_sys) const
6396 {
6397  return (*_cm[nl_sys])(ivar, jvar);
6398 }
6399 
6400 std::vector<std::pair<MooseVariableFEBase *, MooseVariableFEBase *>> &
6401 FEProblemBase::couplingEntries(const THREAD_ID tid, const unsigned int nl_sys)
6402 {
6403  return _assembly[tid][nl_sys]->couplingEntries();
6404 }
6405 
6406 std::vector<std::pair<MooseVariableFEBase *, MooseVariableFEBase *>> &
6407 FEProblemBase::nonlocalCouplingEntries(const THREAD_ID tid, const unsigned int nl_sys)
6408 {
6409  return _assembly[tid][nl_sys]->nonlocalCouplingEntries();
6410 }
6411 
6412 void
6414 {
6415  if (_initialized)
6416  return;
6417 
6418  TIME_SECTION("init", 2, "Initializing");
6419 
6420  // call executioner's preProblemInit so that it can do some setups before problem init
6422 
6423  // If we have AD and we are doing global AD indexing, then we should by default set the matrix
6424  // coupling to full. If the user has told us to trust their coupling matrix, then this call will
6425  // not do anything
6428 
6429  for (const auto i : index_range(_nl))
6430  {
6431  auto & nl = _nl[i];
6432  auto & cm = _cm[i];
6433 
6434  unsigned int n_vars = nl->nVariables();
6435  {
6436  TIME_SECTION("fillCouplingMatrix", 3, "Filling Coupling Matrix");
6437 
6438  switch (_coupling)
6439  {
6440  case Moose::COUPLING_DIAG:
6441  cm = std::make_unique<CouplingMatrix>(n_vars);
6442  for (unsigned int i = 0; i < n_vars; i++)
6443  (*cm)(i, i) = 1;
6444  break;
6445 
6446  // for full jacobian
6447  case Moose::COUPLING_FULL:
6448  cm = std::make_unique<CouplingMatrix>(n_vars);
6449  for (unsigned int i = 0; i < n_vars; i++)
6450  for (unsigned int j = 0; j < n_vars; j++)
6451  (*cm)(i, j) = 1;
6452  break;
6453 
6455  // do nothing, _cm was already set through couplingMatrix() call
6456  break;
6457  }
6458  }
6459 
6460  nl->dofMap()._dof_coupling = cm.get();
6461 
6462  // If there are no variables, make sure to pass a nullptr coupling
6463  // matrix, to avoid warnings about non-nullptr yet empty
6464  // CouplingMatrices.
6465  if (n_vars == 0)
6466  nl->dofMap()._dof_coupling = nullptr;
6467 
6468  nl->dofMap().attach_extra_sparsity_function(&extraSparsity, nl.get());
6469  nl->dofMap().attach_extra_send_list_function(&extraSendList, nl.get());
6470  _aux->dofMap().attach_extra_send_list_function(&extraSendList, _aux.get());
6471 
6472  if (!_skip_nl_system_check && _solve && n_vars == 0)
6473  mooseError("No variables specified in nonlinear system '", nl->name(), "'.");
6474  }
6475 
6476  ghostGhostedBoundaries(); // We do this again right here in case new boundaries have been added
6477 
6478  // We may have added element/nodes to the mesh in ghostGhostedBoundaries so we need to update
6479  // all of our mesh information. We need to make sure that mesh information is up-to-date before
6480  // EquationSystems::init because that will call through to updateGeomSearch (for sparsity
6481  // augmentation) and if we haven't added back boundary node information before that latter call,
6482  // then we're screwed. We'll get things like "Unable to find closest node!"
6483  _mesh.meshChanged();
6484  if (_displaced_problem)
6486 
6487  if (_mesh.doingPRefinement())
6488  {
6490  if (_displaced_problem)
6491  _displaced_problem->preparePRefinement();
6492  }
6493 
6494  // do not assemble system matrix for JFNK solve
6495  for (auto & nl : _nl)
6496  if (solverParams(nl->number())._type == Moose::ST_JFNK)
6497  nl->turnOffJacobian();
6498 
6499  for (auto & sys : _solver_systems)
6500  sys->preInit();
6501  _aux->preInit();
6502 
6503  // Build the mortar segment meshes, if they haven't been already, for a couple reasons:
6504  // 1) Get the ghosting correct for both static and dynamic meshes
6505  // 2) Make sure the mortar mesh is built for mortar constraints that live on the static mesh
6506  //
6507  // It is worth-while to note that mortar meshes that live on a dynamic mesh will be built
6508  // during residual and Jacobian evaluation because when displacements are solution variables
6509  // the mortar mesh will move and change during the course of a non-linear solve. We DO NOT
6510  // redo ghosting during non-linear solve, so for purpose 1) the below call has to be made
6511  if (!_mortar_data->initialized())
6512  updateMortarMesh();
6513 
6514  {
6515  TIME_SECTION("EquationSystems::Init", 2, "Initializing Equation Systems");
6516  es().init();
6517  }
6518 
6519  for (auto & sys : _solver_systems)
6520  sys->postInit();
6521  _aux->postInit();
6522 
6523  // Now that the equation system and the dof distribution is done, we can generate the
6524  // finite volume-related parts if needed.
6525  if (haveFV())
6527 
6528  for (auto & sys : _solver_systems)
6529  sys->update();
6530  _aux->update();
6531 
6532  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
6533  for (const auto i : index_range(_nl))
6534  {
6535  mooseAssert(
6536  _cm[i],
6537  "Coupling matrix not set for system "
6538  << i
6539  << ". This should only happen if a preconditioner was not setup for this system");
6540  _assembly[tid][i]->init(_cm[i].get());
6541  }
6542 
6543  if (_displaced_problem)
6544  _displaced_problem->init();
6545 
6546 #ifdef MOOSE_KOKKOS_ENABLED
6547  if (_has_kokkos_objects)
6548  initKokkos();
6549 #endif
6550 
6551  _initialized = true;
6552 }
6553 
6554 unsigned int
6555 FEProblemBase::nlSysNum(const NonlinearSystemName & nl_sys_name) const
6556 {
6557  std::istringstream ss(nl_sys_name);
6558  unsigned int nl_sys_num;
6559  if (!(ss >> nl_sys_num) || !ss.eof())
6560  nl_sys_num = libmesh_map_find(_nl_sys_name_to_num, nl_sys_name);
6561 
6562  return nl_sys_num;
6563 }
6564 
6565 unsigned int
6566 FEProblemBase::linearSysNum(const LinearSystemName & linear_sys_name) const
6567 {
6568  std::istringstream ss(linear_sys_name);
6569  unsigned int linear_sys_num;
6570  if (!(ss >> linear_sys_num) || !ss.eof())
6571  linear_sys_num = libmesh_map_find(_linear_sys_name_to_num, linear_sys_name);
6572 
6573  return linear_sys_num;
6574 }
6575 
6576 unsigned int
6577 FEProblemBase::solverSysNum(const SolverSystemName & solver_sys_name) const
6578 {
6579  std::istringstream ss(solver_sys_name);
6580  unsigned int solver_sys_num;
6581  if (!(ss >> solver_sys_num) || !ss.eof())
6582  {
6583  const auto & search = _solver_sys_name_to_num.find(solver_sys_name);
6584  if (search == _solver_sys_name_to_num.end())
6585  mooseError("The solver system number was requested for system '" + solver_sys_name,
6586  "' but this system does not exist in the Problem. Systems can be added to the "
6587  "problem using the 'nl_sys_names'/'linear_sys_names' parameter.\nSystems in the "
6588  "Problem: " +
6590  solver_sys_num = search->second;
6591  }
6592 
6593  return solver_sys_num;
6594 }
6595 
6596 unsigned int
6597 FEProblemBase::systemNumForVariable(const VariableName & variable_name) const
6598 {
6599  for (const auto & solver_sys : _solver_systems)
6600  if (solver_sys->hasVariable(variable_name))
6601  return solver_sys->number();
6602  mooseAssert(_aux, "Should have an auxiliary system");
6603  if (_aux->hasVariable(variable_name))
6604  return _aux->number();
6605 
6606  mooseError("Variable '",
6607  variable_name,
6608  "' was not found in any solver (nonlinear/linear) or auxiliary system");
6609 }
6610 
6611 void
6612 FEProblemBase::solve(const unsigned int nl_sys_num)
6613 {
6614  TIME_SECTION("solve", 1, "Solving", false);
6615 
6616  setCurrentNonlinearSystem(nl_sys_num);
6617 
6618  // This prevents stale dof indices from lingering around and possibly leading to invalid reads
6619  // and writes. Dof indices may be made stale through operations like mesh adaptivity
6621  if (_displaced_problem)
6622  _displaced_problem->clearAllDofIndices();
6623 
6624  // Setup the output system for printing linear/nonlinear iteration information and some solver
6625  // settings, including setting matrix prefixes. This must occur before petscSetOptions
6627 
6628 #if PETSC_RELEASE_LESS_THAN(3, 12, 0)
6630  _petsc_options, _solver_params); // Make sure the PETSc options are setup for this app
6631 #else
6632  // Now this database will be the default
6633  // Each app should have only one database
6634  if (!_app.isUltimateMaster())
6635  LibmeshPetscCall(PetscOptionsPush(_petsc_option_data_base));
6636  // We did not add PETSc options to database yet
6638  {
6639  // Insert options for all systems all at once
6642  }
6643 #endif
6644 
6645  // set up DM which is required if use a field split preconditioner
6646  // We need to setup DM every "solve()" because libMesh destroy SNES after solve()
6647  // Do not worry, DM setup is very cheap
6649 
6651 
6652  // reset flag so that residual evaluation does not get skipped
6653  // and the next non-linear iteration does not automatically fail with
6654  // "DIVERGED_NANORINF", when we throw an exception and stop solve
6656 
6657  if (_solve)
6658  {
6661  }
6662 
6663  // sync solutions in displaced problem
6664  if (_displaced_problem)
6665  _displaced_problem->syncSolutions();
6666 
6667 #if !PETSC_RELEASE_LESS_THAN(3, 12, 0)
6668  if (!_app.isUltimateMaster())
6669  LibmeshPetscCall(PetscOptionsPop());
6670 #endif
6671 }
6672 
6673 void
6674 FEProblemBase::setException(const std::string & message)
6675 {
6676  _has_exception = true;
6677  _exception_message = message;
6678 }
6679 
6680 void
6682 {
6684  return;
6685 
6686  TIME_SECTION("checkExceptionAndStopSolve", 5);
6687 
6688  // See if any processor had an exception. If it did, get back the
6689  // processor that the exception occurred on.
6690  unsigned int processor_id;
6691 
6693 
6694  if (_has_exception)
6695  {
6697 
6700  {
6701  // Print the message
6702  if (_communicator.rank() == 0 && print_message)
6703  {
6704  _console << "\n" << _exception_message << "\n";
6705  if (isTransient())
6706  _console
6707  << "To recover, the solution will fail and then be re-attempted with a reduced time "
6708  "step.\n"
6709  << std::endl;
6710  }
6711 
6712  // Stop the solve -- this entails setting
6713  // SNESSetFunctionDomainError() or directly inserting NaNs in the
6714  // residual vector to let PETSc >= 3.6 return DIVERGED_NANORINF.
6715  if (_current_nl_sys)
6717 
6718  if (_current_linear_sys)
6720 
6721  // and close Aux system (we MUST do this here; see #11525)
6722  _aux->solution().close();
6723 
6724  // We've handled this exception, so we no longer have one.
6725  _has_exception = false;
6726 
6727  // Force the next non-linear convergence check to fail (and all further residual evaluation
6728  // to be skipped).
6730 
6731  // Repropagate the exception, so it can be caught at a higher level, typically
6732  // this is NonlinearSystem::computeResidual().
6734  }
6735  else
6736  mooseError("The following parallel-communicated exception was detected during " +
6737  Moose::stringify(_current_execute_on_flag) + " evaluation:\n" +
6739  "\nBecause this did not occur during residual evaluation, there"
6740  " is no way to handle this, so the solution is aborting.\n");
6741  }
6742 }
6743 
6744 void
6746 {
6747  // Our default state is to allow computing derivatives
6748  ADReal::do_derivatives = true;
6750 
6751  // Clear the VectorTags and MatrixTags
6754 
6757 
6761  if (_displaced_problem)
6762  {
6763  _displaced_problem->setCurrentlyComputingResidual(false);
6764  _displaced_problem->setCurrentlyComputingJacobian(false);
6765  _displaced_problem->setCurrentlyComputingResidualAndJacobian(false);
6766  }
6767 }
6768 
6769 void
6770 FEProblemBase::solveLinearSystem(const unsigned int linear_sys_num,
6772 {
6773  TIME_SECTION("solve", 1, "Solving", false);
6774 
6775  setCurrentLinearSystem(linear_sys_num);
6776 
6777  const Moose::PetscSupport::PetscOptions & options = po ? *po : _petsc_options;
6778  auto & solver_params = _solver_params[numNonlinearSystems() + linear_sys_num];
6779 
6780  // Set custom convergence criteria
6782 
6783 #if PETSC_RELEASE_LESS_THAN(3, 12, 0)
6784  LibmeshPetscCall(Moose::PetscSupport::petscSetOptions(
6785  options, solver_params)); // Make sure the PETSc options are setup for this app
6786 #else
6787  // Now this database will be the default
6788  // Each app should have only one database
6789  if (!_app.isUltimateMaster())
6790  LibmeshPetscCall(PetscOptionsPush(_petsc_option_data_base));
6791 
6792  // We did not add PETSc options to database yet
6794  {
6795  Moose::PetscSupport::petscSetOptions(options, solver_params, this);
6797  }
6798 #endif
6799 
6800  if (_solve)
6802 
6803 #if !PETSC_RELEASE_LESS_THAN(3, 12, 0)
6804  if (!_app.isUltimateMaster())
6805  LibmeshPetscCall(PetscOptionsPop());
6806 #endif
6807 }
6808 
6809 bool
6810 FEProblemBase::solverSystemConverged(const unsigned int sys_num)
6811 {
6812  if (_solve)
6813  return _solver_systems[sys_num]->converged();
6814  else
6815  return true;
6816 }
6817 
6818 unsigned int
6819 FEProblemBase::nNonlinearIterations(const unsigned int nl_sys_num) const
6820 {
6821  return _nl[nl_sys_num]->nNonlinearIterations();
6822 }
6823 
6824 unsigned int
6825 FEProblemBase::nLinearIterations(const unsigned int nl_sys_num) const
6826 {
6827  return _nl[nl_sys_num]->nLinearIterations();
6828 }
6829 
6830 Real
6831 FEProblemBase::finalNonlinearResidual(const unsigned int nl_sys_num) const
6832 {
6833  return _nl[nl_sys_num]->finalNonlinearResidual();
6834 }
6835 
6836 bool
6837 FEProblemBase::computingPreSMOResidual(const unsigned int nl_sys_num) const
6838 {
6839  return _nl[nl_sys_num]->computingPreSMOResidual();
6840 }
6841 
6842 void
6844 {
6845  TIME_SECTION("copySolutionsBackwards", 3, "Copying Solutions Backward");
6846 
6847  for (auto & sys : _solver_systems)
6848  sys->copySolutionsBackwards();
6849  _aux->copySolutionsBackwards();
6850 }
6851 
6852 void
6854 {
6855  TIME_SECTION("advanceState", 5, "Advancing State");
6856 
6857  for (auto & sys : _solver_systems)
6858  sys->copyOldSolutions();
6859  _aux->copyOldSolutions();
6860 
6861  if (_displaced_problem)
6862  {
6863  for (const auto i : index_range(_solver_systems))
6864  _displaced_problem->solverSys(i).copyOldSolutions();
6865  _displaced_problem->auxSys().copyOldSolutions();
6866  }
6867 
6869 
6871 
6874 
6877 
6880 
6881 #ifdef MOOSE_KOKKOS_ENABLED
6884 
6887 
6890 #endif
6891 }
6892 
6893 void
6895 {
6896  TIME_SECTION("restoreSolutions", 5, "Restoring Solutions");
6897 
6898  if (!_not_zeroed_tagged_vectors.empty())
6899  paramError("not_zeroed_tag_vectors",
6900  "There is currently no way to restore not-zeroed vectors.");
6901 
6902  for (auto & sys : _solver_systems)
6903  {
6904  if (_verbose_restore)
6905  _console << "Restoring solutions on system " << sys->name() << "..." << std::endl;
6906  sys->restoreSolutions();
6907  }
6908 
6909  if (_verbose_restore)
6910  _console << "Restoring solutions on Auxiliary system..." << std::endl;
6911  _aux->restoreSolutions();
6912 
6913  if (_verbose_restore)
6914  _console << "Restoring postprocessor, vector-postprocessor, and reporter data..." << std::endl;
6916 
6917  if (_displaced_problem)
6918  _displaced_problem->updateMesh();
6919 }
6920 
6921 void
6923 {
6924  TIME_SECTION("saveOldSolutions", 5, "Saving Old Solutions");
6925 
6926  for (auto & sys : _solver_systems)
6927  sys->saveOldSolutions();
6928  _aux->saveOldSolutions();
6929 }
6930 
6931 void
6933 {
6934  TIME_SECTION("restoreOldSolutions", 5, "Restoring Old Solutions");
6935 
6936  for (auto & sys : _solver_systems)
6937  sys->restoreOldSolutions();
6938  _aux->restoreOldSolutions();
6939 }
6940 
6941 void
6943 {
6944  TIME_SECTION("outputStep", 1, "Outputting");
6945 
6947 
6948  for (auto & sys : _solver_systems)
6949  sys->update();
6950  _aux->update();
6951 
6952  if (_displaced_problem)
6953  _displaced_problem->syncSolutions();
6955 
6957 }
6958 
6959 void
6961 {
6963 }
6964 
6965 void
6967 {
6969 }
6970 
6971 void
6973 {
6976 }
6977 
6978 void
6980 {
6981  TIME_SECTION("onTimestepBegin", 2);
6982 
6983  for (auto & nl : _nl)
6984  nl->onTimestepBegin();
6985 }
6986 
6987 void
6989 {
6990 }
6991 
6992 Real
6994 {
6996  // If we are any iteration type other than time (e.g. nonlinear), then temporally we are still
6997  // in the present time
6998  return time();
6999 
7000  switch (state.state)
7001  {
7002  case 0:
7003  return time();
7004 
7005  case 1:
7006  return timeOld();
7007 
7008  default:
7009  mooseError("Unhandled state ", state.state, " in FEProblemBase::getTimeFromStateArg");
7010  }
7011 }
7012 
7013 void
7014 FEProblemBase::addTimeIntegrator(const std::string & type,
7015  const std::string & name,
7016  InputParameters & parameters)
7017 {
7018  parallel_object_only();
7019 
7020  parameters.set<SubProblem *>("_subproblem") = this;
7021  logAdd("TimeIntegrator", name, type, parameters);
7022  _aux->addTimeIntegrator(type, name + ":aux", parameters);
7023  for (auto & sys : _solver_systems)
7024  sys->addTimeIntegrator(type, name + ":" + sys->name(), parameters);
7025  _has_time_integrator = true;
7026 
7027  // add vectors to store u_dot, u_dotdot, udot_old, u_dotdot_old and
7028  // solution vectors older than 2 time steps, if requested by the time
7029  // integrator
7030  _aux->addDotVectors();
7031  for (auto & nl : _nl)
7032  {
7033  nl->addDotVectors();
7034 
7035  auto tag_udot = nl->getTimeIntegrators()[0]->uDotFactorTag();
7036  if (!nl->hasVector(tag_udot))
7037  nl->associateVectorToTag(*nl->solutionUDot(), tag_udot);
7038  auto tag_udotdot = nl->getTimeIntegrators()[0]->uDotDotFactorTag();
7039  if (!nl->hasVector(tag_udotdot) && uDotDotRequested())
7040  nl->associateVectorToTag(*nl->solutionUDotDot(), tag_udotdot);
7041  }
7042 
7043  if (_displaced_problem)
7044  // Time integrator does not exist when displaced problem is created.
7045  _displaced_problem->addTimeIntegrator();
7046 }
7047 
7048 void
7049 FEProblemBase::addPredictor(const std::string & type,
7050  const std::string & name,
7051  InputParameters & parameters)
7052 {
7053  parallel_object_only();
7054 
7056  mooseError("Vector bounds cannot be used with LinearSystems!");
7057 
7058  parameters.set<SubProblem *>("_subproblem") = this;
7059  std::shared_ptr<Predictor> predictor = _factory.create<Predictor>(type, name, parameters);
7060  logAdd("Predictor", name, type, parameters);
7061 
7062  for (auto & nl : _nl)
7063  nl->setPredictor(predictor);
7064 }
7065 
7066 Real
7068 {
7069  _current_nl_sys = &sys;
7070  computeResidual(*sys.currentSolution(), sys.RHS(), sys.number());
7071  return sys.RHS().l2_norm();
7072 }
7073 
7074 Real
7076 {
7077  _current_linear_sys = &sys;
7078 
7079  // We assemble the current system to check the current residual
7082  *sys.linearImplicitSystem().rhs,
7083  /*compute fresh gradients*/ true);
7084 
7085  // Unfortunate, but we have to allocate a new vector for the residual
7086  auto residual = sys.linearImplicitSystem().rhs->clone();
7087  residual->scale(-1.0);
7088  residual->add_vector(*sys.currentSolution(), *sys.linearImplicitSystem().matrix);
7089  return residual->l2_norm();
7090 }
7091 
7092 Real
7094 {
7095  TIME_SECTION("computeResidualL2Norm", 2, "Computing L2 Norm of Residual");
7096 
7097  // We use sum the squared norms of the individual systems and then take the square root of it
7098  Real l2_norm = 0.0;
7099  for (auto sys : _nl)
7100  {
7101  const auto norm = computeResidualL2Norm(*sys);
7102  l2_norm += norm * norm;
7103  }
7104 
7105  for (auto sys : _linear_systems)
7106  {
7107  const auto norm = computeResidualL2Norm(*sys);
7108  l2_norm += norm * norm;
7109  }
7110 
7111  return std::sqrt(l2_norm);
7112 }
7113 
7114 void
7116  const NumericVector<Number> & soln,
7117  NumericVector<Number> & residual)
7118 {
7119  parallel_object_only();
7120 
7121  TIME_SECTION("computeResidualSys", 5);
7122 
7123  computeResidual(soln, residual, sys.number());
7124 }
7125 
7126 void
7128  const NumericVector<Number> & soln,
7129  NumericVector<Number> & residual)
7130 {
7131  mooseDeprecated("Please use computeResidualSys");
7132 
7133  computeResidualSys(sys, soln, residual);
7134 }
7135 
7136 void
7138  NumericVector<Number> & residual,
7139  const unsigned int nl_sys_num)
7140 {
7141  setCurrentNonlinearSystem(nl_sys_num);
7142 
7143  // We associate the residual tag with the given residual vector to make sure we
7144  // don't filter it out below
7146  const auto & residual_vector_tags = getVectorTags(Moose::VECTOR_TAG_RESIDUAL);
7147 
7148  mooseAssert(_fe_vector_tags.empty(), "This should be empty indicating a clean starting state");
7149  // We filter out tags which do not have associated vectors in the current nonlinear
7150  // system. This is essential to be able to use system-dependent residual tags.
7152 
7153  computeResidualInternal(soln, residual, _fe_vector_tags);
7154  _fe_vector_tags.clear();
7155 }
7156 
7157 void
7159  NumericVector<Number> & residual,
7160  SparseMatrix<Number> & jacobian)
7161 {
7162  try
7163  {
7164  try
7165  {
7166  // vector tags
7168  const auto & residual_vector_tags = getVectorTags(Moose::VECTOR_TAG_RESIDUAL);
7169 
7170  mooseAssert(_fe_vector_tags.empty(),
7171  "This should be empty indicating a clean starting state");
7172  // We filter out tags which do not have associated vectors in the current nonlinear
7173  // system. This is essential to be able to use system-dependent residual tags.
7175 
7177 
7178  // matrix tags
7179  {
7180  _fe_matrix_tags.clear();
7181 
7182  auto & tags = getMatrixTags();
7183  for (auto & tag : tags)
7184  _fe_matrix_tags.insert(tag.second);
7185  }
7186 
7188 
7191 
7192  for (const auto tag : _fe_matrix_tags)
7193  if (_current_nl_sys->hasMatrix(tag))
7194  {
7195  auto & matrix = _current_nl_sys->getMatrix(tag);
7196  matrix.zero();
7198  // PETSc algorithms require diagonal allocations regardless of whether there is non-zero
7199  // diagonal dependence. With global AD indexing we only add non-zero
7200  // dependence, so PETSc will scream at us unless we artificially add the diagonals.
7201  for (auto index : make_range(matrix.row_start(), matrix.row_stop()))
7202  matrix.add(index, index, 0);
7203  }
7204 
7205  _aux->zeroVariablesForResidual();
7206 
7207  unsigned int n_threads = libMesh::n_threads();
7208 
7210 
7211  // Random interface objects
7212  for (const auto & it : _random_data_objects)
7213  it.second->updateSeeds(EXEC_LINEAR);
7214 
7218  if (_displaced_problem)
7219  {
7220  _displaced_problem->setCurrentlyComputingResidual(true);
7221  _displaced_problem->setCurrentlyComputingJacobian(true);
7222  _displaced_problem->setCurrentlyComputingResidualAndJacobian(true);
7223  }
7224 
7226 
7228 
7229  for (unsigned int tid = 0; tid < n_threads; tid++)
7230  reinitScalars(tid);
7231 
7233 
7234  _aux->residualSetup();
7235 
7236  if (_displaced_problem)
7237  {
7239  _displaced_problem->updateMesh();
7240  if (_mortar_data->hasDisplacedObjects())
7241  updateMortarMesh();
7242  }
7243 
7244  for (THREAD_ID tid = 0; tid < n_threads; tid++)
7245  {
7248  }
7249 
7250 #ifdef MOOSE_KOKKOS_ENABLED
7252 #endif
7253 
7255 
7257 
7259 
7261 
7264 
7266 
7269  }
7270  catch (...)
7271  {
7272  handleException("computeResidualAndJacobian");
7273  }
7274  }
7275  catch (const MooseException &)
7276  {
7277  // The buck stops here, we have already handled the exception by
7278  // calling the system's stopSolve() method, it is now up to PETSc to return a
7279  // "diverged" reason during the next solve.
7280  }
7281  catch (...)
7282  {
7283  mooseError("Unexpected exception type");
7284  }
7285 
7286  resetState();
7287  _fe_vector_tags.clear();
7288  _fe_matrix_tags.clear();
7289 }
7290 
7291 void
7293  NumericVector<Number> & residual,
7294  TagID tag)
7295 {
7296  try
7297  {
7299 
7300  _current_nl_sys->associateVectorToTag(residual, tag);
7301 
7302  computeResidualTags({tag});
7303 
7305  }
7306  catch (MooseException & e)
7307  {
7308  // If a MooseException propagates all the way to here, it means
7309  // that it was thrown from a MOOSE system where we do not
7310  // (currently) properly support the throwing of exceptions, and
7311  // therefore we have no choice but to error out. It may be
7312  // *possible* to handle exceptions from other systems, but in the
7313  // meantime, we don't want to silently swallow any unhandled
7314  // exceptions here.
7315  mooseError("An unhandled MooseException was raised during residual computation. Please "
7316  "contact the MOOSE team for assistance.");
7317  }
7318 }
7319 
7320 void
7322  NumericVector<Number> & residual,
7323  const std::set<TagID> & tags)
7324 {
7325  parallel_object_only();
7326 
7327  TIME_SECTION("computeResidualInternal", 1);
7328 
7329  try
7330  {
7332 
7334 
7335  computeResidualTags(tags);
7336 
7338  }
7339  catch (MooseException & e)
7340  {
7341  // If a MooseException propagates all the way to here, it means
7342  // that it was thrown from a MOOSE system where we do not
7343  // (currently) properly support the throwing of exceptions, and
7344  // therefore we have no choice but to error out. It may be
7345  // *possible* to handle exceptions from other systems, but in the
7346  // meantime, we don't want to silently swallow any unhandled
7347  // exceptions here.
7348  mooseError("An unhandled MooseException was raised during residual computation. Please "
7349  "contact the MOOSE team for assistance.");
7350  }
7351 }
7352 
7353 void
7355  NumericVector<Number> & residual,
7356  TagID tag)
7357 {
7358  TIME_SECTION("computeResidualType", 5);
7359 
7360  try
7361  {
7363 
7365 
7367 
7369  }
7370  catch (MooseException & e)
7371  {
7372  // If a MooseException propagates all the way to here, it means
7373  // that it was thrown from a MOOSE system where we do not
7374  // (currently) properly support the throwing of exceptions, and
7375  // therefore we have no choice but to error out. It may be
7376  // *possible* to handle exceptions from other systems, but in the
7377  // meantime, we don't want to silently swallow any unhandled
7378  // exceptions here.
7379  mooseError("An unhandled MooseException was raised during residual computation. Please "
7380  "contact the MOOSE team for assistance.");
7381  }
7382 }
7383 
7384 void
7385 FEProblemBase::handleException(const std::string & calling_method)
7386 {
7387  auto create_exception_message =
7388  [&calling_method](const std::string & exception_type, const auto & exception)
7389  {
7390  return std::string("A " + exception_type + " was raised during FEProblemBase::" +
7391  calling_method + "\n" + std::string(exception.what()));
7392  };
7393 
7394  try
7395  {
7396  throw;
7397  }
7398  catch (const MooseException & e)
7399  {
7400  setException(create_exception_message("MooseException", e));
7401  }
7402  catch (const MetaPhysicL::LogicError & e)
7403  {
7405  }
7406  catch (const libMesh::PetscSolverException & e)
7407  {
7408  // One PETSc solver exception that we cannot currently recover from are new nonzero errors. In
7409  // particular I have observed the following scenario in a parallel test:
7410  // - Both processes throw because of a new nonzero during MOOSE's computeJacobianTags
7411  // - We potentially handle the exceptions nicely here
7412  // - When the matrix is closed in libMesh's libmesh_petsc_snes_solver, there is a new nonzero
7413  // throw which we do not catch here in MOOSE and the simulation terminates. This only appears
7414  // in parallel (and not all the time; a test I was examining threw with distributed mesh, but
7415  // not with replicated). In serial there are no new throws from libmesh_petsc_snes_solver.
7416  // So for uniformity of behavior across serial/parallel, we will choose to abort here and always
7417  // produce a non-zero exit code
7418  mooseError(create_exception_message("libMesh::PetscSolverException", e));
7419  }
7420  catch (const std::exception & e)
7421  {
7422  // This might be libMesh detecting a degenerate Jacobian or matrix
7423  if (strstr(e.what(), "Jacobian") || strstr(e.what(), "singular") ||
7424  strstr(e.what(), "det != 0"))
7425  setException(create_exception_message("libMesh DegenerateMap", e));
7426  else
7427  {
7428  const auto message = create_exception_message("std::exception", e);
7430  mooseError(message);
7431  else
7432  setException(message);
7433  }
7434  }
7435 
7437 }
7438 
7439 void
7440 FEProblemBase::computeResidualTags(const std::set<TagID> & tags)
7441 {
7442  parallel_object_only();
7443 
7444  try
7445  {
7446  try
7447  {
7448  TIME_SECTION("computeResidualTags", 5, "Computing Residual");
7449 
7450  ADReal::do_derivatives = false;
7451 
7453 
7454  _aux->zeroVariablesForResidual();
7455 
7456  unsigned int n_threads = libMesh::n_threads();
7457 
7459 
7460  // Random interface objects
7461  for (const auto & it : _random_data_objects)
7462  it.second->updateSeeds(EXEC_LINEAR);
7463 
7465 
7467 
7468  for (unsigned int tid = 0; tid < n_threads; tid++)
7469  reinitScalars(tid);
7470 
7472 
7473  _aux->residualSetup();
7474 
7475  if (_displaced_problem)
7476  {
7478  _displaced_problem->updateMesh();
7479  if (_mortar_data->hasDisplacedObjects())
7480  updateMortarMesh();
7481  }
7482 
7483  for (THREAD_ID tid = 0; tid < n_threads; tid++)
7484  {
7487  }
7488 
7489 #ifdef MOOSE_KOKKOS_ENABLED
7491 #endif
7492 
7494 
7496 
7498 
7500 
7503  }
7504  catch (...)
7505  {
7506  handleException("computeResidualTags");
7507  }
7508  }
7509  catch (const MooseException &)
7510  {
7511  // The buck stops here, we have already handled the exception by
7512  // calling the system's stopSolve() method, it is now up to PETSc to return a
7513  // "diverged" reason during the next solve.
7514  }
7515  catch (...)
7516  {
7517  mooseError("Unexpected exception type");
7518  }
7519 
7520  resetState();
7521 }
7522 
7523 void
7525  const NumericVector<Number> & soln,
7526  SparseMatrix<Number> & jacobian)
7527 {
7528  computeJacobian(soln, jacobian, sys.number());
7529 }
7530 
7531 void
7533  SparseMatrix<Number> & jacobian,
7534  TagID tag)
7535 {
7537 
7538  _current_nl_sys->associateMatrixToTag(jacobian, tag);
7539 
7540  computeJacobianTags({tag});
7541 
7543 }
7544 
7545 void
7547  SparseMatrix<Number> & jacobian,
7548  const unsigned int nl_sys_num)
7549 {
7550  setCurrentNonlinearSystem(nl_sys_num);
7551 
7552  _fe_matrix_tags.clear();
7553 
7554  auto & tags = getMatrixTags();
7555  for (auto & tag : tags)
7556  _fe_matrix_tags.insert(tag.second);
7557 
7558  computeJacobianInternal(soln, jacobian, _fe_matrix_tags);
7559 }
7560 
7561 void
7563  SparseMatrix<Number> & jacobian,
7564  const std::set<TagID> & tags)
7565 {
7566  TIME_SECTION("computeJacobianInternal", 1);
7567 
7569 
7571 
7572  computeJacobianTags(tags);
7573 
7575 }
7576 
7577 void
7578 FEProblemBase::computeJacobianTags(const std::set<TagID> & tags)
7579 {
7580  try
7581  {
7582  try
7583  {
7584  if (!_has_jacobian || !_const_jacobian)
7585  {
7586  TIME_SECTION("computeJacobianTags", 5, "Computing Jacobian");
7587 
7588  for (auto tag : tags)
7589  if (_current_nl_sys->hasMatrix(tag))
7590  {
7591  auto & matrix = _current_nl_sys->getMatrix(tag);
7594  else
7595  matrix.zero();
7597  // PETSc algorithms require diagonal allocations regardless of whether there is
7598  // non-zero diagonal dependence. With global AD indexing we only add non-zero
7599  // dependence, so PETSc will scream at us unless we artificially add the diagonals.
7600  for (auto index : make_range(matrix.row_start(), matrix.row_stop()))
7601  matrix.add(index, index, 0);
7602  }
7603 
7604  _aux->zeroVariablesForJacobian();
7605 
7606  unsigned int n_threads = libMesh::n_threads();
7607 
7608  // Random interface objects
7609  for (const auto & it : _random_data_objects)
7610  it.second->updateSeeds(EXEC_NONLINEAR);
7611 
7614  if (_displaced_problem)
7615  _displaced_problem->setCurrentlyComputingJacobian(true);
7616 
7619 
7620  for (unsigned int tid = 0; tid < n_threads; tid++)
7621  reinitScalars(tid);
7622 
7624 
7625  _aux->jacobianSetup();
7626 
7627  if (_displaced_problem)
7628  {
7630  _displaced_problem->updateMesh();
7631  }
7632 
7633  for (unsigned int tid = 0; tid < n_threads; tid++)
7634  {
7637  }
7638 
7639 #ifdef MOOSE_KOKKOS_ENABLED
7641 #endif
7642 
7644 
7646 
7648 
7650 
7652 
7654 
7655  // For explicit Euler calculations for example we often compute the Jacobian one time and
7656  // then re-use it over and over. If we're performing automatic scaling, we don't want to
7657  // use that kernel, diagonal-block only Jacobian for our actual matrix when performing
7658  // solves!
7660  _has_jacobian = true;
7661  }
7662  }
7663  catch (...)
7664  {
7665  handleException("computeJacobianTags");
7666  }
7667  }
7668  catch (const MooseException &)
7669  {
7670  // The buck stops here, we have already handled the exception by
7671  // calling the system's stopSolve() method, it is now up to PETSc to return a
7672  // "diverged" reason during the next solve.
7673  }
7674  catch (...)
7675  {
7676  mooseError("Unexpected exception type");
7677  }
7678 
7679  resetState();
7680 }
7681 
7682 void
7683 FEProblemBase::computeJacobianBlocks(std::vector<JacobianBlock *> & blocks,
7684  const unsigned int nl_sys_num)
7685 {
7686  TIME_SECTION("computeTransientImplicitJacobian", 2);
7687  setCurrentNonlinearSystem(nl_sys_num);
7688 
7689  if (_displaced_problem)
7690  {
7692  _displaced_problem->updateMesh();
7693  }
7694 
7696 
7700 }
7701 
7702 void
7704  libMesh::System & precond_system,
7705  unsigned int ivar,
7706  unsigned int jvar)
7707 {
7708  JacobianBlock jac_block(precond_system, jacobian, ivar, jvar);
7709  std::vector<JacobianBlock *> blocks = {&jac_block};
7710  mooseAssert(_current_nl_sys, "This should be non-null");
7712 }
7713 
7714 void
7716  NumericVector<Number> & lower,
7717  NumericVector<Number> & upper)
7718 {
7719  try
7720  {
7721  try
7722  {
7723  mooseAssert(_current_nl_sys && (sys.number() == _current_nl_sys->number()),
7724  "I expect these system numbers to be the same");
7725 
7726  if (!_current_nl_sys->hasVector("lower_bound") || !_current_nl_sys->hasVector("upper_bound"))
7727  return;
7728 
7729  TIME_SECTION("computeBounds", 1, "Computing Bounds");
7730 
7731  NumericVector<Number> & _lower = _current_nl_sys->getVector("lower_bound");
7732  NumericVector<Number> & _upper = _current_nl_sys->getVector("upper_bound");
7733  _lower.swap(lower);
7734  _upper.swap(upper);
7735  for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
7737 
7738  _aux->residualSetup();
7740  _lower.swap(lower);
7741  _upper.swap(upper);
7742  }
7743  catch (...)
7744  {
7745  handleException("computeBounds");
7746  }
7747  }
7748  catch (MooseException & e)
7749  {
7750  mooseError("Irrecoverable exception: " + std::string(e.what()));
7751  }
7752  catch (...)
7753  {
7754  mooseError("Unexpected exception type");
7755  }
7756 }
7757 
7758 void
7760  SparseMatrix<Number> & system_matrix,
7761  NumericVector<Number> & rhs,
7762  const bool compute_gradients)
7763 {
7764  TIME_SECTION("computeLinearSystemSys", 5);
7765 
7767 
7770 
7771  // We are using the residual tag system for right hand sides so we fetch everything
7772  const auto & vector_tags = getVectorTags(Moose::VECTOR_TAG_RESIDUAL);
7773 
7774  // We filter out tags which do not have associated vectors in the current
7775  // system. This is essential to be able to use system-dependent vector tags.
7778 
7782  compute_gradients);
7783 
7788  // We reset the tags to the default containers for further operations
7793 }
7794 
7795 void
7797  const std::set<TagID> & vector_tags,
7798  const std::set<TagID> & matrix_tags,
7799  const bool compute_gradients)
7800 {
7801  TIME_SECTION("computeLinearSystemTags", 5, "Computing Linear System");
7802 
7804 
7805  for (auto tag : matrix_tags)
7806  {
7807  auto & matrix = _current_linear_sys->getMatrix(tag);
7808  matrix.zero();
7809  }
7810 
7811  unsigned int n_threads = libMesh::n_threads();
7812 
7814 
7815  // Random interface objects
7816  for (const auto & it : _random_data_objects)
7817  it.second->updateSeeds(EXEC_NONLINEAR);
7818 
7821 
7823 
7824  _aux->jacobianSetup();
7825 
7826  for (THREAD_ID tid = 0; tid < n_threads; tid++)
7827  {
7829  }
7830 
7831 #ifdef MOOSE_KOKKOS_ENABLED
7833 #endif
7834 
7835  try
7836  {
7838  }
7839  catch (MooseException & e)
7840  {
7841  _console << "\nA MooseException was raised during Auxiliary variable computation.\n"
7842  << "The next solve will fail, the timestep will be reduced, and we will try again.\n"
7843  << std::endl;
7844 
7845  // We know the next solve is going to fail, so there's no point in
7846  // computing anything else after this. Plus, using incompletely
7847  // computed AuxVariables in subsequent calculations could lead to
7848  // other errors or unhandled exceptions being thrown.
7849  return;
7850  }
7851 
7854 
7856 
7857  _current_linear_sys->computeLinearSystemTags(vector_tags, matrix_tags, compute_gradients);
7858 
7859  // Reset execution flag as after this point we are no longer on LINEAR
7861 
7862  // These are the relevant parts of resetState()
7865 }
7866 
7867 void
7869  std::vector<NumericVector<Number> *> & sp)
7870 {
7871  mooseAssert(_current_nl_sys && (sys.number() == _current_nl_sys->number()),
7872  "I expect these system numbers to be the same");
7873 
7874  sp.clear();
7875  for (unsigned int i = 0; i < subspaceDim("NearNullSpace"); ++i)
7876  {
7877  std::stringstream postfix;
7878  postfix << "_" << i;
7879  std::string modename = "NearNullSpace" + postfix.str();
7880  sp.push_back(&_current_nl_sys->getVector(modename));
7881  }
7882 }
7883 
7884 void
7886  std::vector<NumericVector<Number> *> & sp)
7887 {
7888  mooseAssert(_current_nl_sys && (sys.number() == _current_nl_sys->number()),
7889  "I expect these system numbers to be the same");
7890  sp.clear();
7891  for (unsigned int i = 0; i < subspaceDim("NullSpace"); ++i)
7892  {
7893  std::stringstream postfix;
7894  postfix << "_" << i;
7895  sp.push_back(&_current_nl_sys->getVector("NullSpace" + postfix.str()));
7896  }
7897 }
7898 
7899 void
7901  std::vector<NumericVector<Number> *> & sp)
7902 {
7903  mooseAssert(_current_nl_sys && (sys.number() == _current_nl_sys->number()),
7904  "I expect these system numbers to be the same");
7905  sp.clear();
7906  for (unsigned int i = 0; i < subspaceDim("TransposeNullSpace"); ++i)
7907  {
7908  std::stringstream postfix;
7909  postfix << "_" << i;
7910  sp.push_back(&_current_nl_sys->getVector("TransposeNullSpace" + postfix.str()));
7911  }
7912 }
7913 
7914 void
7916  const NumericVector<Number> & old_soln,
7917  NumericVector<Number> & search_direction,
7918  NumericVector<Number> & new_soln,
7919  bool & changed_search_direction,
7920  bool & changed_new_soln)
7921 {
7922  mooseAssert(_current_nl_sys && (sys.number() == _current_nl_sys->number()),
7923  "I expect these system numbers to be the same");
7924 
7925  // This function replaces the old PetscSupport::dampedCheck() function.
7926  //
7927  // 1.) Recreate code in PetscSupport::dampedCheck() for constructing
7928  // ghosted "soln" and "update" vectors.
7929  // 2.) Call FEProblemBase::computeDamping() with these ghost vectors.
7930  // 3.) Recreate the code in PetscSupport::dampedCheck() to actually update
7931  // the solution vector based on the damping, and set the "changed" flags
7932  // appropriately.
7933 
7934  TIME_SECTION("computePostCheck", 2, "Computing Post Check");
7935 
7937 
7938  // MOOSE's FEProblemBase doesn't update the solution during the
7939  // postcheck, but FEProblemBase-derived classes might.
7941  {
7942  // We need ghosted versions of new_soln and search_direction (the
7943  // ones we get from libmesh/PETSc are PARALLEL vectors. To make
7944  // our lives simpler, we use the same ghosting pattern as the
7945  // system's current_local_solution to create new ghosted vectors.
7946 
7947  // Construct zeroed-out clones with the same ghosted dofs as the
7948  // System's current_local_solution.
7949  std::unique_ptr<NumericVector<Number>> ghosted_solution =
7950  sys.current_local_solution->zero_clone(),
7951  ghosted_search_direction =
7952  sys.current_local_solution->zero_clone();
7953 
7954  // Copy values from input vectors into clones with ghosted values.
7955  *ghosted_solution = new_soln;
7956  *ghosted_search_direction = search_direction;
7957 
7958  if (_has_dampers)
7959  {
7960  // Compute the damping coefficient using the ghosted vectors
7961  Real damping = computeDamping(*ghosted_solution, *ghosted_search_direction);
7962 
7963  // If some non-trivial damping was computed, update the new_soln
7964  // vector accordingly.
7965  if (damping < 1.0)
7966  {
7967  new_soln = old_soln;
7968  new_soln.add(-damping, search_direction);
7969  changed_new_soln = true;
7970  }
7971  }
7972 
7973  if (shouldUpdateSolution())
7974  {
7975  // Update the ghosted copy of the new solution, if necessary.
7976  if (changed_new_soln)
7977  *ghosted_solution = new_soln;
7978 
7979  bool updated_solution = updateSolution(new_soln, *ghosted_solution);
7980  if (updated_solution)
7981  changed_new_soln = true;
7982  }
7983  }
7984 
7986  {
7988  _aux->copyCurrentIntoPreviousNL();
7989  }
7990 
7991  // MOOSE doesn't change the search_direction
7992  changed_search_direction = false;
7993 
7995 }
7996 
7997 Real
7999  const NumericVector<Number> & update)
8000 {
8001  // Default to no damping
8002  Real damping = 1.0;
8003 
8004  if (_has_dampers)
8005  {
8006  TIME_SECTION("computeDamping", 1, "Computing Damping");
8007 
8008  // Save pointer to the current solution
8009  const NumericVector<Number> * _saved_current_solution = _current_nl_sys->currentSolution();
8010 
8012  // For now, do not re-compute auxiliary variables. Doing so allows a wild solution increment
8013  // to get to the material models, which may not be able to cope with drastically different
8014  // values. Once more complete dependency checking is in place, auxiliary variables (and
8015  // material properties) will be computed as needed by dampers.
8016  // _aux.compute();
8017  damping = _current_nl_sys->computeDamping(soln, update);
8018 
8019  // restore saved solution
8020  _current_nl_sys->setSolution(*_saved_current_solution);
8021  }
8022 
8023  return damping;
8024 }
8025 
8026 bool
8028 {
8029  return false;
8030 }
8031 
8032 bool
8034  NumericVector<Number> & /*ghosted_solution*/)
8035 {
8036  return false;
8037 }
8038 
8039 void
8041 {
8042 }
8043 
8044 void
8045 FEProblemBase::addDisplacedProblem(std::shared_ptr<DisplacedProblem> displaced_problem)
8046 {
8047  parallel_object_only();
8048 
8051 }
8052 
8053 void
8055 {
8056  TIME_SECTION("updateGeometricSearch", 3, "Updating Geometric Search");
8057 
8059 
8060  if (_displaced_problem)
8061  _displaced_problem->updateGeomSearch(type);
8062 }
8063 
8064 void
8066 {
8067  TIME_SECTION("updateMortarMesh", 5, "Updating Mortar Mesh");
8068 
8069  FloatingPointExceptionGuard fpe_guard(_app);
8070 
8071  _mortar_data->update();
8072 }
8073 
8074 void
8076  const std::pair<BoundaryID, BoundaryID> & primary_secondary_boundary_pair,
8077  const std::pair<SubdomainID, SubdomainID> & primary_secondary_subdomain_pair,
8078  bool on_displaced,
8079  bool periodic,
8080  const bool debug,
8081  const bool correct_edge_dropping,
8082  const Real minimum_projection_angle)
8083 {
8084  _has_mortar = true;
8085 
8086  if (on_displaced)
8087  return _mortar_data->createMortarInterface(primary_secondary_boundary_pair,
8088  primary_secondary_subdomain_pair,
8090  on_displaced,
8091  periodic,
8092  debug,
8093  correct_edge_dropping,
8094  minimum_projection_angle);
8095  else
8096  return _mortar_data->createMortarInterface(primary_secondary_boundary_pair,
8097  primary_secondary_subdomain_pair,
8098  *this,
8099  on_displaced,
8100  periodic,
8101  debug,
8102  correct_edge_dropping,
8103  minimum_projection_angle);
8104 }
8105 
8108  const std::pair<BoundaryID, BoundaryID> & primary_secondary_boundary_pair,
8109  const std::pair<SubdomainID, SubdomainID> & primary_secondary_subdomain_pair,
8110  bool on_displaced) const
8111 {
8112  return _mortar_data->getMortarInterface(
8113  primary_secondary_boundary_pair, primary_secondary_subdomain_pair, on_displaced);
8114 }
8115 
8118  const std::pair<BoundaryID, BoundaryID> & primary_secondary_boundary_pair,
8119  const std::pair<SubdomainID, SubdomainID> & primary_secondary_subdomain_pair,
8120  bool on_displaced)
8121 {
8122  return _mortar_data->getMortarInterface(
8123  primary_secondary_boundary_pair, primary_secondary_subdomain_pair, on_displaced);
8124 }
8125 
8126 void
8128 {
8129  if (_displaced_problem) // Only need to do this if things are moving...
8130  {
8131  TIME_SECTION("possiblyRebuildGeomSearchPatches", 5, "Rebuilding Geometric Search Patches");
8132 
8133  switch (_mesh.getPatchUpdateStrategy())
8134  {
8135  case Moose::Never:
8136  break;
8137  case Moose::Iteration:
8138  // Update the list of ghosted elements at the start of the time step
8141 
8142  _displaced_problem->geomSearchData().updateGhostedElems();
8144 
8145  // The commands below ensure that the sparsity of the Jacobian matrix is
8146  // augmented at the start of the time step using neighbor nodes from the end
8147  // of the previous time step.
8148 
8150 
8151  // This is needed to reinitialize PETSc output
8153 
8154  break;
8155 
8156  case Moose::Auto:
8157  {
8158  Real max = _displaced_problem->geomSearchData().maxPatchPercentage();
8160 
8161  // If we haven't moved very far through the patch
8162  if (max < 0.4)
8163  break;
8164  }
8165  libmesh_fallthrough();
8166 
8167  // Let this fall through if things do need to be updated...
8168  case Moose::Always:
8169  // Flush output here to see the message before the reinitialization, which could take a
8170  // while
8171  _console << "\n\nUpdating geometric search patches\n" << std::endl;
8172 
8175 
8176  _displaced_problem->geomSearchData().clearNearestNodeLocators();
8178 
8180 
8181  // This is needed to reinitialize PETSc output
8183  }
8184  }
8185 }
8186 
8187 #ifdef LIBMESH_ENABLE_AMR
8188 void
8190 {
8191  unsigned int n = adaptivity().getInitialSteps();
8192  _cycles_completed = 0;
8193  if (n)
8194  {
8195  if (!_mesh.interiorLowerDBlocks().empty() || !_mesh.boundaryLowerDBlocks().empty())
8196  mooseError("HFEM does not support mesh adaptivity currently.");
8197 
8198  TIME_SECTION("initialAdaptMesh", 2, "Performing Initial Adaptivity");
8199 
8200  for (unsigned int i = 0; i < n; i++)
8201  {
8203  computeMarkers();
8204 
8206  {
8207  meshChanged(
8208  /*intermediate_change=*/false, /*contract_mesh=*/true, /*clean_refinement_flags=*/true);
8209 
8210  // reproject the initial condition
8211  projectSolution();
8212 
8214  }
8215  else
8216  {
8217  _console << "Mesh unchanged, skipping remaining steps..." << std::endl;
8218  return;
8219  }
8220  }
8221  }
8222 }
8223 
8224 bool
8226 {
8227  // reset cycle counter
8228  _cycles_completed = 0;
8229 
8231  return false;
8232 
8233  TIME_SECTION("adaptMesh", 3, "Adapting Mesh");
8234 
8235  unsigned int cycles_per_step = _adaptivity.getCyclesPerStep();
8236 
8237  bool mesh_changed = false;
8238 
8239  for (unsigned int i = 0; i < cycles_per_step; ++i)
8240  {
8241  if (!_mesh.interiorLowerDBlocks().empty() || !_mesh.boundaryLowerDBlocks().empty())
8242  mooseError("HFEM does not support mesh adaptivity currently.");
8243 
8244  // Markers were already computed once by Executioner
8245  if (_adaptivity.getRecomputeMarkersFlag() && i > 0)
8246  computeMarkers();
8247 
8248  bool mesh_changed_this_step;
8249  mesh_changed_this_step = _adaptivity.adaptMesh();
8250 
8251  if (mesh_changed_this_step)
8252  {
8253  mesh_changed = true;
8254 
8255  meshChanged(
8256  /*intermediate_change=*/true, /*contract_mesh=*/true, /*clean_refinement_flags=*/true);
8258  }
8259  else
8260  {
8261  // If the mesh didn't change, we still need to update the displaced mesh
8262  // to undo the undisplacement performed in Adaptivity::adaptMesh
8263  if (_displaced_problem)
8264  _displaced_problem->updateMesh();
8265 
8266  _console << "Mesh unchanged, skipping remaining steps..." << std::endl;
8267  break;
8268  }
8269 
8270  // Show adaptivity progress
8271  _console << std::flush;
8272  }
8273 
8274  // We're done with all intermediate changes; now get systems ready
8275  // for real if necessary.
8276  if (mesh_changed)
8277  es().reinit_systems();
8278 
8279  // Execute multi-apps that need to run after adaptivity, but before the next timestep.
8281 
8282  return mesh_changed;
8283 }
8284 #endif // LIBMESH_ENABLE_AMR
8285 
8286 void
8287 FEProblemBase::initXFEM(std::shared_ptr<XFEMInterface> xfem)
8288 {
8289  _xfem = xfem;
8290  _xfem->setMesh(&_mesh);
8291  if (_displaced_mesh)
8292  _xfem->setDisplacedMesh(_displaced_mesh);
8293 
8294  auto fill_data = [](auto & storage)
8295  {
8296  std::vector<MaterialData *> data(libMesh::n_threads());
8297  for (const auto tid : make_range(libMesh::n_threads()))
8298  data[tid] = &storage.getMaterialData(tid);
8299  return data;
8300  };
8301  _xfem->setMaterialData(fill_data(_material_props));
8302  _xfem->setBoundaryMaterialData(fill_data(_bnd_material_props));
8303 
8304  unsigned int n_threads = libMesh::n_threads();
8305  for (unsigned int i = 0; i < n_threads; ++i)
8306  for (const auto nl_sys_num : index_range(_nl))
8307  {
8308  _assembly[i][nl_sys_num]->setXFEM(_xfem);
8309  if (_displaced_problem)
8310  _displaced_problem->assembly(i, nl_sys_num).setXFEM(_xfem);
8311  }
8312 }
8313 
8314 bool
8316 {
8317  TIME_SECTION("updateMeshXFEM", 5, "Updating XFEM");
8318 
8319  bool updated = false;
8320  if (haveXFEM())
8321  {
8322  if (_xfem->updateHeal())
8323  // XFEM exodiff tests rely on a given numbering because they cannot use map = true due to
8324  // having coincident elements. While conceptually speaking we do not need to contract the
8325  // mesh, we need its call to renumber_nodes_and_elements in order to preserve these tests
8326  meshChanged(
8327  /*intermediate_change=*/false, /*contract_mesh=*/true, /*clean_refinement_flags=*/false);
8328 
8329  updated = _xfem->update(_time, _nl, *_aux);
8330  if (updated)
8331  {
8332  meshChanged(
8333  /*intermediate_change=*/false, /*contract_mesh=*/true, /*clean_refinement_flags=*/false);
8334  _xfem->initSolution(_nl, *_aux);
8335  restoreSolutions();
8336  _console << "\nXFEM update complete: Mesh modified" << std::endl;
8337  }
8338  else
8339  _console << "\nXFEM update complete: Mesh not modified" << std::endl;
8340  }
8341  return updated;
8342 }
8343 
8344 void
8345 FEProblemBase::meshChanged(const bool intermediate_change,
8346  const bool contract_mesh,
8347  const bool clean_refinement_flags)
8348 {
8349  TIME_SECTION("meshChanged", 3, "Handling Mesh Changes");
8350 
8353  _mesh.cacheChangedLists(); // Currently only used with adaptivity and stateful material
8354  // properties
8355 
8356  // Clear these out because they corresponded to the old mesh
8357  _ghosted_elems.clear();
8359 
8360  // The mesh changed. We notify the MooseMesh first, because
8361  // callbacks (e.g. for sparsity calculations) triggered by the
8362  // EquationSystems reinit may require up-to-date MooseMesh caches.
8363  _mesh.meshChanged();
8364 
8365  // If we're just going to alter the mesh again, all we need to
8366  // handle here is AMR and projections, not full system reinit
8367  if (intermediate_change)
8368  es().reinit_solutions();
8369  else
8370  es().reinit();
8371 
8372  if (contract_mesh)
8373  // Once vectors are restricted, we can delete children of coarsened elements
8374  _mesh.getMesh().contract();
8375  if (clean_refinement_flags)
8376  {
8377  // Finally clear refinement flags so that if someone tries to project vectors again without
8378  // an intervening mesh refinement to clear flags they won't run into trouble
8379  MeshRefinement refinement(_mesh.getMesh());
8380  refinement.clean_refinement_flags();
8381  }
8382 
8383  if (!intermediate_change)
8384  {
8385  // Since the mesh has changed, we need to make sure that we update any of our
8386  // MOOSE-system specific data.
8387  for (auto & sys : _solver_systems)
8388  sys->reinit();
8389  _aux->reinit();
8390  }
8391 
8392  // Updating MooseMesh first breaks other adaptivity code, unless we
8393  // then *again* update the MooseMesh caches. E.g. the definition of
8394  // "active" and "local" may have been *changed* by refinement and
8395  // repartitioning done in EquationSystems::reinit().
8396  _mesh.meshChanged();
8397 
8398  // If we have finite volume variables, we will need to recompute additional elemental/face
8399  // quantities
8402 
8403  // Let the meshChangedInterface notify the mesh changed event before we update the active
8404  // semilocal nodes, because the set of ghosted elements may potentially be updated during a mesh
8405  // changed event.
8406  for (const auto & mci : _notify_when_mesh_changes)
8407  mci->meshChanged();
8408 
8409  // Since the Mesh changed, update the PointLocator object used by DiracKernels.
8411 
8412  // Need to redo ghosting
8414 
8415  if (_displaced_problem)
8416  {
8417  _displaced_problem->meshChanged(contract_mesh, clean_refinement_flags);
8419  }
8420 
8422 
8425 
8426  // Just like we reinitialized our geometric search objects, we also need to reinitialize our
8427  // mortar meshes. Note that this needs to happen after DisplacedProblem::meshChanged because the
8428  // mortar mesh discretization will depend necessarily on the displaced mesh being re-displaced
8429  updateMortarMesh();
8430 
8431  // Nonlinear systems hold the mortar mesh functors. The domains of definition of the mortar
8432  // functors might have changed when the mesh changed.
8433  for (auto & nl_sys : _nl)
8434  nl_sys->reinitMortarFunctors();
8435 
8436  reinitBecauseOfGhostingOrNewGeomObjects(/*mortar_changed=*/true);
8437 
8438  // We need to create new storage for newly active elements, and copy
8439  // stateful properties from the old elements.
8442  {
8443  if (havePRefinement())
8445 
8446  // Prolong properties onto newly refined elements' children
8447  {
8449  /* refine = */ true, *this, _material_props, _bnd_material_props, _assembly);
8450  const auto & range = *_mesh.refinedElementRange();
8451  Threads::parallel_reduce(range, pmp);
8452 
8453  // Concurrent erasure from the shared hash map is not safe while we are reading from it in
8454  // ProjectMaterialProperties, so we handle erasure here. Moreover, erasure based on key is
8455  // not thread safe in and of itself because it is a read-write operation. Note that we do not
8456  // do the erasure for p-refinement because the coarse level element is the same as our active
8457  // refined level element
8458  if (!doingPRefinement())
8459  for (const auto & elem : range)
8460  {
8464  }
8465  }
8466 
8467  // Restrict properties onto newly coarsened elements
8468  {
8470  /* refine = */ false, *this, _material_props, _bnd_material_props, _assembly);
8471  const auto & range = *_mesh.coarsenedElementRange();
8472  Threads::parallel_reduce(range, pmp);
8473  // Note that we do not do the erasure for p-refinement because the coarse level element is the
8474  // same as our active refined level element
8475  if (!doingPRefinement())
8476  for (const auto & elem : range)
8477  {
8478  auto && coarsened_children = _mesh.coarsenedElementChildren(elem);
8479  for (auto && child : coarsened_children)
8480  {
8484  }
8485  }
8486  }
8487  }
8488 
8491 
8492  _has_jacobian = false; // we have to recompute jacobian when mesh changed
8493 
8494  // Now for backwards compatibility with user code that overrode the old no-arg meshChanged we must
8495  // call it here
8496  meshChanged();
8497 }
8498 
8499 void
8501 {
8502  _notify_when_mesh_changes.push_back(mci);
8503 }
8504 
8505 void
8507 {
8508  _notify_when_mesh_displaces.push_back(mdi);
8509 }
8510 
8511 void
8513 {
8514  for (const auto & mdi : _notify_when_mesh_displaces)
8515  mdi->meshDisplaced();
8516 }
8517 
8518 void
8519 FEProblemBase::initElementStatefulProps(const ConstElemRange & elem_range, const bool threaded)
8520 {
8523  if (threaded)
8524  Threads::parallel_reduce(elem_range, cmt);
8525  else
8526  cmt(elem_range, true);
8527 
8528 #ifdef MOOSE_KOKKOS_ENABLED
8529  if (_has_kokkos_objects)
8531 #endif
8532 }
8533 
8534 void
8536 {
8537  TIME_SECTION("checkProblemIntegrity", 5);
8538 
8539  // Subdomains specified by the "Problem/block" parameter
8540  const auto & subdomain_names = getParam<std::vector<SubdomainName>>("block");
8541  auto mesh_subdomains_vec = MooseMeshUtils::getSubdomainIDs(_mesh, subdomain_names);
8542  std::set<SubdomainID> mesh_subdomains(mesh_subdomains_vec.begin(), mesh_subdomains_vec.end());
8543 
8544  // Check kernel coverage of subdomains (blocks) in the mesh
8547  {
8548  std::set<SubdomainID> blocks;
8551  blocks = mesh_subdomains;
8553  {
8554  blocks = mesh_subdomains;
8555  for (const auto & subdomain_name : _kernel_coverage_blocks)
8556  {
8557  const auto id = _mesh.getSubdomainID(subdomain_name);
8558  if (id == Moose::INVALID_BLOCK_ID)
8559  paramError("kernel_coverage_block_list",
8560  "Subdomain \"",
8561  subdomain_name,
8562  "\" not found in mesh.");
8563  blocks.erase(id);
8564  }
8565  }
8567  for (const auto & subdomain_name : _kernel_coverage_blocks)
8568  {
8569  const auto id = _mesh.getSubdomainID(subdomain_name);
8570  if (id == Moose::INVALID_BLOCK_ID)
8571  paramError("kernel_coverage_block_list",
8572  "Subdomain \"",
8573  subdomain_name,
8574  "\" not found in mesh.");
8575  blocks.insert(id);
8576  }
8577  if (!blocks.empty())
8578  for (auto & nl : _nl)
8579  nl->checkKernelCoverage(blocks);
8580  }
8581 
8582  // Check materials
8583  {
8584 #ifdef LIBMESH_ENABLE_AMR
8585  if ((_adaptivity.isOn() || _num_grid_steps) &&
8588  {
8589  _console << "Using EXPERIMENTAL Stateful Material Property projection with Adaptivity!\n"
8590  << std::flush;
8591  }
8592 #endif
8593 
8594  std::set<SubdomainID> local_mesh_subs(mesh_subdomains);
8595 
8598  {
8603  bool check_material_coverage = false;
8604  std::set<SubdomainID> ids = _all_materials.getActiveBlocks();
8605  for (const auto & id : ids)
8606  {
8607  local_mesh_subs.erase(id);
8608  check_material_coverage = true;
8609  }
8610 
8611  // did the user limit the subdomains to be checked?
8613  {
8614  for (const auto & subdomain_name : _material_coverage_blocks)
8615  {
8616  const auto id = _mesh.getSubdomainID(subdomain_name);
8617  if (id == Moose::INVALID_BLOCK_ID)
8618  paramError("material_coverage_block_list",
8619  "Subdomain \"" + subdomain_name + "\" not found in mesh.");
8620  local_mesh_subs.erase(id);
8621  }
8622  }
8624  {
8625  std::set<SubdomainID> blocks(local_mesh_subs);
8626  for (const auto & subdomain_name : _material_coverage_blocks)
8627  {
8628  const auto id = _mesh.getSubdomainID(subdomain_name);
8629  if (id == Moose::INVALID_BLOCK_ID)
8630  paramError("material_coverage_block_list",
8631  "Subdomain \"" + subdomain_name + "\" not found in mesh.");
8632  blocks.erase(id);
8633  }
8634  for (const auto id : blocks)
8635  local_mesh_subs.erase(id);
8636  }
8637 
8638  // also exclude mortar spaces from the material check
8639  auto && mortar_subdomain_ids = _mortar_data->getMortarSubdomainIDs();
8640  for (auto subdomain_id : mortar_subdomain_ids)
8641  local_mesh_subs.erase(subdomain_id);
8642 
8643  // Check Material Coverage
8644  if (check_material_coverage && !local_mesh_subs.empty())
8645  {
8646  std::stringstream extra_subdomain_ids;
8648  std::copy(local_mesh_subs.begin(),
8649  local_mesh_subs.end(),
8650  std::ostream_iterator<unsigned int>(extra_subdomain_ids, " "));
8652  std::vector<SubdomainID> local_mesh_subs_vec(local_mesh_subs.begin(),
8653  local_mesh_subs.end());
8654 
8655  mooseError("The following blocks from your input mesh do not contain an active material: " +
8656  extra_subdomain_ids.str() +
8657  "(names: " + Moose::stringify(_mesh.getSubdomainNames(local_mesh_subs_vec)) +
8658  ")\nWhen ANY mesh block contains a Material object, "
8659  "all blocks must contain a Material object.\n");
8660  }
8661  }
8662 
8663  // Check material properties on blocks and boundaries
8666 
8667  // Check that material properties exist when requested by other properties on a given block
8668  const auto & materials = _all_materials.getActiveObjects();
8669  for (const auto & material : materials)
8670  material->checkStatefulSanity();
8671 
8672  // auto mats_to_check = _materials.getActiveBlockObjects();
8673  // const auto & discrete_materials = _discrete_materials.getActiveBlockObjects();
8674  // for (const auto & map_it : discrete_materials)
8675  // for (const auto & container_element : map_it.second)
8676  // mats_to_check[map_it.first].push_back(container_element);
8679  }
8680 
8681  checkUserObjects();
8682 
8683  // Verify that we don't have any Element type/Coordinate Type conflicts
8685 
8686  // Coordinate transforms are only intended for use with MultiApps at this time. If you are not
8687  // using multiapps but still require these, contact a moose developer
8689  !hasMultiApps())
8690  mooseError("Coordinate transformation parameters, listed below, are only to be used in the "
8691  "context of application to application field transfers at this time. The mesh is "
8692  "not modified by these parameters within an application.\n"
8693  "You should likely use a 'TransformGenerator' in the [Mesh] block to achieve the "
8694  "desired mesh modification.\n\n",
8696 
8697  // If using displacements, verify that the order of the displacement
8698  // variables matches the order of the elements in the displaced
8699  // mesh.
8701 
8702  // Check for postprocessor names with same name as a scalar variable
8704 }
8705 
8706 void
8708 {
8709  if (_displaced_problem)
8710  {
8711  bool mesh_has_second_order_elements = false;
8712  for (const auto & elem : as_range(_displaced_mesh->activeLocalElementsBegin(),
8714  {
8715  if (elem->default_order() == SECOND)
8716  {
8717  mesh_has_second_order_elements = true;
8718  break;
8719  }
8720  }
8721 
8722  // We checked our local elements, so take the max over all processors.
8723  _displaced_mesh->comm().max(mesh_has_second_order_elements);
8724 
8725  // If the Mesh has second order elements, make sure the
8726  // displacement variables are second-order.
8727  if (mesh_has_second_order_elements)
8728  {
8729  const std::vector<std::string> & displacement_variables =
8730  _displaced_problem->getDisplacementVarNames();
8731 
8732  for (const auto & var_name : displacement_variables)
8733  {
8734  MooseVariableFEBase & mv =
8735  _displaced_problem->getVariable(/*tid=*/0,
8736  var_name,
8739  if (mv.order() != SECOND)
8740  mooseError("Error: mesh has SECOND order elements, so all displacement variables must be "
8741  "SECOND order.");
8742  }
8743  }
8744  }
8745 }
8746 
8747 void
8749 {
8750  // Check user_objects block coverage
8751  std::set<SubdomainID> mesh_subdomains = _mesh.meshSubdomains();
8752  std::set<SubdomainID> user_objects_blocks;
8753 
8754  // gather names of all user_objects that were defined in the input file
8755  // and the blocks that they are defined on
8756  std::set<std::string> names;
8757 
8758  std::vector<UserObject *> objects;
8760 
8761  for (const auto & obj : objects)
8762  names.insert(obj->name());
8763 
8764  // See if all referenced blocks are covered
8765  std::set<SubdomainID> difference;
8766  std::set_difference(user_objects_blocks.begin(),
8767  user_objects_blocks.end(),
8768  mesh_subdomains.begin(),
8769  mesh_subdomains.end(),
8770  std::inserter(difference, difference.end()));
8771 
8772  if (!difference.empty())
8773  {
8774  std::ostringstream oss;
8775  oss << "One or more UserObjects is referencing a nonexistent block:\n";
8776  for (const auto & id : difference)
8777  oss << id << "\n";
8778  mooseError(oss.str());
8779  }
8780 }
8781 
8782 void
8784  const std::map<SubdomainID, std::vector<std::shared_ptr<MaterialBase>>> & materials_map)
8785 {
8786  for (const auto & it : materials_map)
8787  {
8789  std::set<std::string> block_depend_props, block_supplied_props;
8790 
8791  for (const auto & mat1 : it.second)
8792  {
8793  auto & alldeps = mat1->getMatPropDependencies(); // includes requested stateful props
8794  for (auto & dep : alldeps)
8795  block_depend_props.insert(_material_prop_registry.getName(dep));
8796 
8797  // See if any of the active materials supply this property
8798  for (const auto & mat2 : it.second)
8799  {
8800  const std::set<std::string> & supplied_props = mat2->MaterialBase::getSuppliedItems();
8801  block_supplied_props.insert(supplied_props.begin(), supplied_props.end());
8802  }
8803  }
8804 
8805  // Add zero material properties specific to this block and unrestricted
8806  block_supplied_props.insert(_zero_block_material_props[it.first].begin(),
8807  _zero_block_material_props[it.first].end());
8808 
8809  // Error check to make sure all properties consumed by materials are supplied on this block
8810  std::set<std::string> difference;
8811  std::set_difference(block_depend_props.begin(),
8812  block_depend_props.end(),
8813  block_supplied_props.begin(),
8814  block_supplied_props.end(),
8815  std::inserter(difference, difference.end()));
8816 
8817  if (!difference.empty())
8818  {
8819  std::ostringstream oss;
8820  oss << "One or more Material Properties were not supplied on block ";
8821  const std::string & subdomain_name = _mesh.getSubdomainName(it.first);
8822  if (subdomain_name.length() > 0)
8823  oss << subdomain_name << " (" << it.first << ")";
8824  else
8825  oss << it.first;
8826  oss << ":\n";
8827  for (const auto & name : difference)
8828  oss << name << "\n";
8829  mooseError(oss.str());
8830  }
8831  }
8832 
8833  // This loop checks that materials are not supplied by multiple Material objects
8834  for (const auto & it : materials_map)
8835  {
8836  const auto & materials = it.second;
8837  std::set<std::string> inner_supplied, outer_supplied;
8838 
8839  for (const auto & outer_mat : materials)
8840  {
8841  // Storage for properties for this material (outer) and all other materials (inner)
8842  outer_supplied = outer_mat->getSuppliedItems();
8843  inner_supplied.clear();
8844 
8845  // Property to material map for error reporting
8846  std::map<std::string, std::set<std::string>> prop_to_mat;
8847  for (const auto & name : outer_supplied)
8848  prop_to_mat[name].insert(outer_mat->name());
8849 
8850  for (const auto & inner_mat : materials)
8851  {
8852  if (outer_mat == inner_mat)
8853  continue;
8854 
8855  // Check whether these materials are an AD pair
8856  auto outer_mat_type = outer_mat->type();
8857  auto inner_mat_type = inner_mat->type();
8858  removeSubstring(outer_mat_type, "<RESIDUAL>");
8859  removeSubstring(outer_mat_type, "<JACOBIAN>");
8860  removeSubstring(inner_mat_type, "<RESIDUAL>");
8861  removeSubstring(inner_mat_type, "<JACOBIAN>");
8862  if (outer_mat_type == inner_mat_type && outer_mat_type != outer_mat->type() &&
8863  inner_mat_type != inner_mat->type())
8864  continue;
8865 
8866  inner_supplied.insert(inner_mat->getSuppliedItems().begin(),
8867  inner_mat->getSuppliedItems().end());
8868 
8869  for (const auto & inner_supplied_name : inner_supplied)
8870  prop_to_mat[inner_supplied_name].insert(inner_mat->name());
8871  }
8872 
8873  // Test that a property isn't supplied on multiple blocks
8874  std::set<std::string> intersection;
8875  std::set_intersection(outer_supplied.begin(),
8876  outer_supplied.end(),
8877  inner_supplied.begin(),
8878  inner_supplied.end(),
8879  std::inserter(intersection, intersection.end()));
8880 
8881  if (!intersection.empty())
8882  {
8883  std::ostringstream oss;
8884  oss << "The following material properties are declared on block " << it.first
8885  << " by multiple materials:\n";
8886  oss << ConsoleUtils::indent(2) << std::setw(30) << std::left << "Material Property"
8887  << "Material Objects\n";
8888  for (const auto & outer_name : intersection)
8889  {
8890  oss << ConsoleUtils::indent(2) << std::setw(30) << std::left << outer_name;
8891  for (const auto & inner_name : prop_to_mat[outer_name])
8892  oss << inner_name << " ";
8893  oss << '\n';
8894  }
8895 
8896  mooseError(oss.str());
8897  break;
8898  }
8899  }
8900  }
8901 }
8902 
8903 void
8905 {
8907 }
8908 
8909 void
8910 FEProblemBase::setRestartFile(const std::string & file_name)
8911 {
8912  if (_app.isRecovering())
8913  {
8914  mooseInfo("Restart file ", file_name, " is NOT being used since we are performing recovery.");
8915  }
8916  else
8917  {
8918  _app.setRestart(true);
8919  _app.setRestartRecoverFileBase(file_name);
8920  mooseInfo("Using ", file_name, " for restart.");
8921  }
8922 }
8923 
8924 std::vector<VariableName>
8926 {
8927  std::vector<VariableName> names;
8928 
8929  for (auto & sys : _solver_systems)
8930  {
8931  const std::vector<VariableName> & var_names = sys->getVariableNames();
8932  names.insert(names.end(), var_names.begin(), var_names.end());
8933  }
8934 
8935  const std::vector<VariableName> & aux_var_names = _aux->getVariableNames();
8936  names.insert(names.end(), aux_var_names.begin(), aux_var_names.end());
8937 
8938  return names;
8939 }
8940 
8941 SolverParams &
8942 FEProblemBase::solverParams(const unsigned int solver_sys_num)
8943 {
8944  mooseAssert(solver_sys_num < numSolverSystems(),
8945  "Solver system number '" << solver_sys_num << "' is out of bounds. We have '"
8946  << numSolverSystems() << "' solver systems");
8947  return _solver_params[solver_sys_num];
8948 }
8949 
8950 const SolverParams &
8951 FEProblemBase::solverParams(const unsigned int solver_sys_num) const
8952 {
8953  return const_cast<FEProblemBase *>(this)->solverParams(solver_sys_num);
8954 }
8955 
8956 void
8957 FEProblemBase::registerRandomInterface(RandomInterface & random_interface, const std::string & name)
8958 {
8959  auto insert_pair = moose_try_emplace(
8960  _random_data_objects, name, std::make_unique<RandomData>(*this, random_interface));
8961 
8962  auto random_data_ptr = insert_pair.first->second.get();
8963  random_interface.setRandomDataPointer(random_data_ptr);
8964 }
8965 
8966 bool
8968 {
8969  if (_bnd_mat_side_cache[tid].find(bnd_id) == _bnd_mat_side_cache[tid].end())
8970  {
8971  auto & bnd_mat_side_cache = _bnd_mat_side_cache[tid][bnd_id];
8972  bnd_mat_side_cache = false;
8973 
8974  // Check systems
8975  if (_aux->needMaterialOnSide(bnd_id))
8976  {
8977  bnd_mat_side_cache = true;
8978  return true;
8979  }
8980  for (auto & nl : _nl)
8981  if (nl->needBoundaryMaterialOnSide(bnd_id, tid))
8982  {
8983  bnd_mat_side_cache = true;
8984  return true;
8985  }
8986 
8987  // TODO: these objects should be checked for whether they actually consume materials
8988  // NOTE: InterfaceUO can use use boundary properties too
8989  if (theWarehouse()
8990  .query()
8991  .condition<AttribThread>(tid)
8992  .condition<AttribInterfaces>(Interfaces::SideUserObject | Interfaces::DomainUserObject |
8994  .condition<AttribBoundaries>(bnd_id)
8995  .count() > 0)
8996  {
8997  bnd_mat_side_cache = true;
8998  return true;
8999  }
9000  }
9001 
9002  return _bnd_mat_side_cache[tid][bnd_id];
9003 }
9004 
9005 bool
9007 {
9008  if (_interface_mat_side_cache[tid].find(bnd_id) == _interface_mat_side_cache[tid].end())
9009  {
9010  auto & interface_mat_side_cache = _interface_mat_side_cache[tid][bnd_id];
9011  interface_mat_side_cache = false;
9012 
9013  // Aux-system has not needed interface materials so far
9014  for (auto & nl : _nl)
9015  if (nl->needInterfaceMaterialOnSide(bnd_id, tid))
9016  {
9017  interface_mat_side_cache = true;
9018  return true;
9019  }
9020 
9021  // TODO: these objects should be checked for whether they actually consume materials
9022  if (theWarehouse()
9023  .query()
9024  .condition<AttribThread>(tid)
9025  .condition<AttribInterfaces>(Interfaces::InterfaceUserObject |
9027  .condition<AttribBoundaries>(bnd_id)
9028  .count() > 0)
9029  {
9030  interface_mat_side_cache = true;
9031  return true;
9032  }
9033  else if (_interface_materials.hasActiveBoundaryObjects(bnd_id, tid))
9034  {
9035  interface_mat_side_cache = true;
9036  return true;
9037  }
9038  }
9039  return _interface_mat_side_cache[tid][bnd_id];
9040 }
9041 
9042 bool
9044 {
9045  if (_block_mat_side_cache[tid].find(subdomain_id) == _block_mat_side_cache[tid].end())
9046  {
9047  _block_mat_side_cache[tid][subdomain_id] = false;
9048 
9049  for (auto & nl : _nl)
9050  if (nl->needInternalNeighborSideMaterial(subdomain_id, tid))
9051  {
9052  _block_mat_side_cache[tid][subdomain_id] = true;
9053  return true;
9054  }
9055 
9056  // TODO: these objects should be checked for whether they actually consume materials
9057  if (theWarehouse()
9058  .query()
9059  .condition<AttribThread>(tid)
9060  .condition<AttribInterfaces>(Interfaces::InternalSideUserObject |
9062  .condition<AttribSubdomains>(subdomain_id)
9063  .count() > 0)
9064  {
9065  _block_mat_side_cache[tid][subdomain_id] = true;
9066  return true;
9067  }
9068  }
9069 
9070  return _block_mat_side_cache[tid][subdomain_id];
9071 }
9072 
9073 bool
9075 {
9077 }
9078 
9079 void
9081 {
9083  mooseError("Previous nonlinear solution is required but not added through "
9084  "Problem/previous_nl_solution_required=true");
9085 }
9086 
9087 bool
9089 {
9090  return _has_jacobian;
9091 }
9092 
9093 bool
9095 {
9096  return _const_jacobian;
9097 }
9098 
9099 void
9100 FEProblemBase::addOutput(const std::string & object_type,
9101  const std::string & object_name,
9102  InputParameters & parameters)
9103 {
9104  parallel_object_only();
9105 
9106  // Get a reference to the OutputWarehouse
9107  OutputWarehouse & output_warehouse = _app.getOutputWarehouse();
9108 
9109  // Reject the reserved names for objects not built by MOOSE
9110  if (!parameters.get<bool>("_built_by_moose") && output_warehouse.isReservedName(object_name))
9111  mooseError("The name '", object_name, "' is a reserved name for output objects");
9112 
9113  // Check that an object by the same name does not already exist; this must be done before the
9114  // object is created to avoid getting misleading errors from the Parser
9115  if (output_warehouse.hasOutput(object_name))
9116  mooseError("An output object named '", object_name, "' already exists");
9117 
9118  // Add a pointer to the FEProblemBase class
9119  parameters.addPrivateParam<FEProblemBase *>("_fe_problem_base", this);
9120 
9121  // Create common parameter exclude list
9122  std::vector<std::string> exclude;
9123  if (object_type == "Console")
9124  {
9125  exclude.push_back("execute_on");
9126 
9127  // --show-input should enable the display of the input file on the screen
9128  if (_app.getParam<bool>("show_input") && parameters.get<bool>("output_screen"))
9129  parameters.set<ExecFlagEnum>("execute_input_on") = EXEC_INITIAL;
9130  }
9131  // Need this because Checkpoint::validParams changes the default value of
9132  // execute_on
9133  else if (object_type == "Checkpoint")
9134  exclude.push_back("execute_on");
9135 
9136  // Apply the common parameters loaded with Outputs input syntax
9137  const InputParameters * common = output_warehouse.getCommonParameters();
9138  if (common)
9139  parameters.applyParameters(*common, exclude);
9140  if (common && std::find(exclude.begin(), exclude.end(), "execute_on") != exclude.end() &&
9141  common->isParamSetByUser("execute_on") && object_type != "Console")
9143  "'execute_on' parameter specified in [Outputs] block is ignored for object '" +
9144  object_name +
9145  "'.\nDefine this object in its own sub-block of [Outputs] to modify its "
9146  "execution schedule.");
9147 
9148  // Set the correct value for the binary flag for XDA/XDR output
9149  if (object_type == "XDR")
9150  parameters.set<bool>("_binary") = true;
9151  else if (object_type == "XDA")
9152  parameters.set<bool>("_binary") = false;
9153 
9154  // Adjust the checkpoint suffix if auto recovery was enabled
9155  if (object_name == "auto_recovery_checkpoint")
9156  parameters.set<std::string>("suffix") = "auto_recovery";
9157 
9158  // Create the object and add it to the warehouse
9159  std::shared_ptr<Output> output = _factory.create<Output>(object_type, object_name, parameters);
9160  logAdd("Output", object_name, object_type, parameters);
9161  output_warehouse.addOutput(output);
9162 }
9163 
9164 void
9165 FEProblemBase::haveADObjects(const bool have_ad_objects)
9166 {
9167  _have_ad_objects = have_ad_objects;
9168  if (_displaced_problem)
9169  _displaced_problem->SubProblem::haveADObjects(have_ad_objects);
9170 }
9171 
9172 const SystemBase &
9173 FEProblemBase::getSystemBase(const unsigned int sys_num) const
9174 {
9175  if (sys_num < _solver_systems.size())
9176  return *_solver_systems[sys_num];
9177 
9178  return *_aux;
9179 }
9180 
9181 SystemBase &
9182 FEProblemBase::getSystemBase(const std::string & sys_name)
9183 {
9184  if (std::find(_solver_sys_names.begin(), _solver_sys_names.end(), sys_name) !=
9185  _solver_sys_names.end())
9186  return getSystemBase(solverSysNum(sys_name));
9187  else if (sys_name == "aux0")
9188  return *_aux;
9189  else
9190  mooseError("System '" + sys_name + "' was requested from problem but does not exist.");
9191 }
9192 
9193 SystemBase &
9194 FEProblemBase::getSystemBase(const unsigned int sys_num)
9195 {
9196  if (sys_num < _solver_systems.size())
9197  return *_solver_systems[sys_num];
9198 
9199  return *_aux;
9200 }
9201 
9202 const SystemBase &
9203 FEProblemBase::systemBaseNonlinear(const unsigned int sys_num) const
9204 {
9205  mooseAssert(sys_num < _nl.size(), "System number greater than the number of nonlinear systems");
9206  return *_nl[sys_num];
9207 }
9208 
9209 SystemBase &
9210 FEProblemBase::systemBaseNonlinear(const unsigned int sys_num)
9211 {
9212  mooseAssert(sys_num < _nl.size(), "System number greater than the number of nonlinear systems");
9213  return *_nl[sys_num];
9214 }
9215 
9216 const SystemBase &
9217 FEProblemBase::systemBaseLinear(const unsigned int sys_num) const
9218 {
9219  mooseAssert(sys_num < _linear_systems.size(),
9220  "System number greater than the number of linear systems");
9221  return *_linear_systems[sys_num];
9222 }
9223 
9224 SystemBase &
9225 FEProblemBase::systemBaseLinear(const unsigned int sys_num)
9226 {
9227  mooseAssert(sys_num < _linear_systems.size(),
9228  "System number greater than the number of linear systems");
9229  return *_linear_systems[sys_num];
9230 }
9231 
9232 const SystemBase &
9233 FEProblemBase::systemBaseSolver(const unsigned int sys_num) const
9234 {
9235  mooseAssert(sys_num < _solver_systems.size(),
9236  "System number greater than the number of solver systems");
9237  return *_solver_systems[sys_num];
9238 }
9239 
9240 SystemBase &
9241 FEProblemBase::systemBaseSolver(const unsigned int sys_num)
9242 {
9243  mooseAssert(sys_num < _solver_systems.size(),
9244  "System number greater than the number of solver systems");
9245  return *_solver_systems[sys_num];
9246 }
9247 
9248 const SystemBase &
9250 {
9251  return *_aux;
9252 }
9253 
9254 SystemBase &
9256 {
9257  return *_aux;
9258 }
9259 
9260 void
9261 FEProblemBase::computingNonlinearResid(bool computing_nonlinear_residual)
9262 {
9263  parallel_object_only();
9264 
9265  if (_displaced_problem)
9266  _displaced_problem->computingNonlinearResid(computing_nonlinear_residual);
9267  _computing_nonlinear_residual = computing_nonlinear_residual;
9268 }
9269 
9270 void
9271 FEProblemBase::setCurrentlyComputingResidual(bool currently_computing_residual)
9272 {
9273  if (_displaced_problem)
9274  _displaced_problem->setCurrentlyComputingResidual(currently_computing_residual);
9275  _currently_computing_residual = currently_computing_residual;
9276 }
9277 
9278 void
9280 {
9281  // ResetDisplacedMeshThread::onNode looks up the reference mesh by ID, so we need to make sure
9282  // we undisplace before adapting the reference mesh
9283  if (_displaced_problem)
9284  _displaced_problem->undisplaceMesh();
9285 
9287  if (_displaced_problem)
9289 
9290  meshChanged(
9291  /*intermediate_change=*/false, /*contract_mesh=*/true, /*clean_refinement_flags=*/true);
9292 }
9293 
9294 void
9295 FEProblemBase::automaticScaling(bool automatic_scaling)
9296 {
9297  if (_displaced_problem)
9298  _displaced_problem->automaticScaling(automatic_scaling);
9299 
9300  SubProblem::automaticScaling(automatic_scaling);
9301 }
9302 
9303 void
9305  unsigned int side,
9306  Real tolerance,
9307  const std::vector<Point> * const pts,
9308  const std::vector<Real> * const weights,
9309  const THREAD_ID tid)
9310 {
9311  SubProblem::reinitElemFaceRef(elem, side, tolerance, pts, weights, tid);
9312 
9313  if (_displaced_problem)
9314  _displaced_problem->reinitElemFaceRef(
9315  _displaced_mesh->elemPtr(elem->id()), side, tolerance, pts, weights, tid);
9316 }
9317 
9318 void
9320  unsigned int neighbor_side,
9321  Real tolerance,
9322  const std::vector<Point> * const pts,
9323  const std::vector<Real> * const weights,
9324  const THREAD_ID tid)
9325 {
9326  SubProblem::reinitNeighborFaceRef(neighbor_elem, neighbor_side, tolerance, pts, weights, tid);
9327 
9328  if (_displaced_problem)
9329  _displaced_problem->reinitNeighborFaceRef(
9330  _displaced_mesh->elemPtr(neighbor_elem->id()), neighbor_side, tolerance, pts, weights, tid);
9331 }
9332 
9333 void
9335  const SubdomainID blk_id,
9336  std::vector<std::shared_ptr<MaterialBase>> & face_materials,
9337  std::vector<std::shared_ptr<MaterialBase>> & neighbor_materials,
9338  std::set<MooseVariableFieldBase *> & variables,
9339  const THREAD_ID tid)
9340 {
9341  if (_materials[Moose::FACE_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
9342  {
9343  auto & this_face_mats =
9345  for (std::shared_ptr<MaterialBase> face_mat : this_face_mats)
9346  if (face_mat->ghostable())
9347  {
9348  face_materials.push_back(face_mat);
9349  auto & var_deps = face_mat->getMooseVariableDependencies();
9350  for (auto * var : var_deps)
9351  {
9352  if (!var->isFV())
9353  mooseError(
9354  "Ghostable materials should only have finite volume variables coupled into them.");
9355  else if (face_mat->hasStatefulProperties())
9356  mooseError("Finite volume materials do not currently support stateful properties.");
9357  variables.insert(var);
9358  }
9359  }
9360  }
9361 
9362  if (_materials[Moose::NEIGHBOR_MATERIAL_DATA].hasActiveBlockObjects(blk_id, tid))
9363  {
9364  auto & this_neighbor_mats =
9366  for (std::shared_ptr<MaterialBase> neighbor_mat : this_neighbor_mats)
9367  if (neighbor_mat->ghostable())
9368  {
9369  neighbor_materials.push_back(neighbor_mat);
9370 #ifndef NDEBUG
9371  auto & var_deps = neighbor_mat->getMooseVariableDependencies();
9372  for (auto * var : var_deps)
9373  {
9374  if (!var->isFV())
9375  mooseError(
9376  "Ghostable materials should only have finite volume variables coupled into them.");
9377  else if (neighbor_mat->hasStatefulProperties())
9378  mooseError("Finite volume materials do not currently support stateful properties.");
9379  auto pr = variables.insert(var);
9380  mooseAssert(!pr.second,
9381  "We should not have inserted any new variables dependencies from our "
9382  "neighbor materials that didn't exist for our face materials");
9383  }
9384 #endif
9385  }
9386  }
9387 }
9388 
9389 void
9391  const unsigned int nqp,
9392  const THREAD_ID tid)
9393 {
9394  getMaterialData(data_type, tid).resize(nqp);
9395 }
9396 
9397 void
9398 FEProblemBase::setNonlinearConvergenceNames(const std::vector<ConvergenceName> & convergence_names)
9399 {
9400  if (convergence_names.size() != numNonlinearSystems())
9401  paramError("nonlinear_convergence",
9402  "There must be one convergence object per nonlinear system");
9403  _nonlinear_convergence_names = convergence_names;
9404 }
9405 
9406 void
9407 FEProblemBase::setMultiAppFixedPointConvergenceName(const ConvergenceName & convergence_name)
9408 {
9409  _multiapp_fixed_point_convergence_name = convergence_name;
9410 }
9411 
9412 void
9413 FEProblemBase::setSteadyStateConvergenceName(const ConvergenceName & convergence_name)
9414 {
9415  _steady_state_convergence_name = convergence_name;
9416 }
9417 
9418 const std::vector<ConvergenceName> &
9420 {
9423  mooseError("The nonlinear system convergence name(s) have not been set.");
9424 }
9425 
9426 bool
9428 {
9429  // If false,this means we have not set one, not that we are querying this too early
9430  // TODO: once there is a default linear CV object, error on the 'not set' case
9431  return _linear_convergence_names.has_value();
9432 }
9433 
9434 void
9435 FEProblemBase::setLinearConvergenceNames(const std::vector<ConvergenceName> & convergence_names)
9436 {
9437  if (convergence_names.size() != numLinearSystems())
9438  paramError("linear_convergence", "There must be one convergence object per linear system");
9439  _linear_convergence_names = convergence_names;
9440 }
9441 
9442 const std::vector<ConvergenceName> &
9444 {
9446  return *_linear_convergence_names;
9447  mooseError("The linear convergence name(s) have not been set.");
9448 }
9449 
9450 const ConvergenceName &
9452 {
9455  else
9456  mooseError("The fixed point convergence name has not been set.");
9457 }
9458 
9459 const ConvergenceName &
9461 {
9463  return _steady_state_convergence_name.value();
9464  else
9465  mooseError("The steady convergence name has not been set.");
9466 }
9467 
9468 void
9470 {
9472  // We need to setup all the nonlinear systems other than our current one which actually called
9473  // this method (so we have to make sure we don't go in a circle)
9474  for (const auto i : make_range(numNonlinearSystems()))
9475  if (i != currentNlSysNum())
9476  _nl[i]->residualSetup();
9477  // We don't setup the aux sys because that's been done elsewhere
9478  if (_displaced_problem)
9479  _displaced_problem->residualSetup();
9480 }
9481 
9482 void
9484 {
9486  // We need to setup all the nonlinear systems other than our current one which actually called
9487  // this method (so we have to make sure we don't go in a circle)
9488  for (const auto i : make_range(numNonlinearSystems()))
9489  if (i != currentNlSysNum())
9490  _nl[i]->jacobianSetup();
9491  // We don't setup the aux sys because that's been done elsewhere
9492  if (_displaced_problem)
9493  _displaced_problem->jacobianSetup();
9494 }
9495 
9498 {
9499  return mesh().coordTransform();
9500 }
9501 
9502 unsigned int
9504 {
9505  // If we don't have nonlinear systems this should be an invalid number
9506  unsigned int current_nl_sys_num = libMesh::invalid_uint;
9507  if (_nl.size())
9508  current_nl_sys_num = currentNonlinearSystem().number();
9509 
9510  return current_nl_sys_num;
9511 }
9512 
9513 unsigned int
9515 {
9516  // If we don't have linear systems this should be an invalid number
9517  unsigned int current_linear_sys_num = libMesh::invalid_uint;
9518  if (_linear_systems.size())
9519  current_linear_sys_num = currentLinearSystem().number();
9520 
9521  return current_linear_sys_num;
9522 }
9523 
9524 bool
9526 {
9527  // For now, only support printing from thread 0
9528  if (tid != 0)
9529  return false;
9530 
9533  return true;
9534  else
9535  return false;
9536 }
9537 
9538 std::vector<MortarUserObject *>
9540  const BoundaryID secondary_boundary_id,
9541  const bool displaced,
9542  const std::vector<MortarUserObject *> & mortar_uo_superset)
9543 {
9544  std::vector<MortarUserObject *> mortar_uos;
9545  auto * const subproblem = displaced ? static_cast<SubProblem *>(_displaced_problem.get())
9546  : static_cast<SubProblem *>(this);
9547  for (auto * const obj : mortar_uo_superset)
9548  if (obj->onInterface(primary_boundary_id, secondary_boundary_id) &&
9549  (&obj->getSubProblem() == subproblem))
9550  mortar_uos.push_back(obj);
9551 
9552  return mortar_uos;
9553 }
9554 
9555 std::vector<MortarUserObject *>
9557  const BoundaryID secondary_boundary_id,
9558  const bool displaced)
9559 {
9560  std::vector<MortarUserObject *> mortar_uos;
9561  theWarehouse()
9562  .query()
9564  .queryInto(mortar_uos);
9565  return getMortarUserObjects(primary_boundary_id, secondary_boundary_id, displaced, mortar_uos);
9566 }
9567 
9568 void
9570  const BoundaryID secondary_boundary_id,
9571  const bool displaced)
9572 {
9573  const auto mortar_uos =
9574  getMortarUserObjects(primary_boundary_id, secondary_boundary_id, displaced);
9575  for (auto * const mortar_uo : mortar_uos)
9576  {
9577  mortar_uo->setNormals();
9578  mortar_uo->reinit();
9579  }
9580 }
9581 
9582 void
9584 {
9585  _verbose_setup = verbose ? "true" : "false";
9586  _verbose_multiapps = verbose;
9587  _verbose_restore = verbose;
9588 }
9589 
9590 void
9591 FEProblemBase::setCurrentLowerDElem(const Elem * const lower_d_elem, const THREAD_ID tid)
9592 {
9593  SubProblem::setCurrentLowerDElem(lower_d_elem, tid);
9594  if (_displaced_problem)
9595  _displaced_problem->setCurrentLowerDElem(
9596  lower_d_elem ? _displaced_mesh->elemPtr(lower_d_elem->id()) : nullptr, tid);
9597 }
9598 
9599 void
9601 {
9603  if (_displaced_problem)
9604  _displaced_problem->setCurrentBoundaryID(bid, tid);
9605 }
9606 
9607 void
9608 FEProblemBase::setCurrentNonlinearSystem(const unsigned int nl_sys_num)
9609 {
9610  mooseAssert(nl_sys_num < _nl.size(),
9611  "System number greater than the number of nonlinear systems");
9612  _current_nl_sys = _nl[nl_sys_num].get();
9614 }
9615 
9616 void
9617 FEProblemBase::setCurrentLinearSystem(const unsigned int sys_num)
9618 {
9619  mooseAssert(sys_num < _linear_systems.size(),
9620  "System number greater than the number of linear systems");
9621  _current_linear_sys = _linear_systems[sys_num].get();
9623 }
9624 
9625 void
9627 {
9628  // When performing an adjoint solve in the optimization module, the current solver system is the
9629  // adjoint. However, the adjoint solve requires having accurate time derivative calculations for
9630  // the forward system. The cleanest way to handle such uses is just to compute the time
9631  // derivatives for all solver systems instead of trying to guess which ones we need and don't need
9632  for (auto & solver_sys : _solver_systems)
9633  solver_sys->compute(type);
9634 
9635  _aux->compute(type);
9636 }
9637 
9638 const ConstElemRange &
9640 {
9643 
9645 }
9646 const ConstNodeRange &
9648 {
9650  return *_mesh.getLocalNodeRange();
9651 
9653 }
9654 const ConstBndNodeRange &
9656 {
9658  return *_mesh.getBoundaryNodeRange();
9659 
9661 }
9662 
9663 void
9665 {
9666  if (!range)
9667  {
9669  return;
9670  }
9671 
9672  _current_algebraic_elem_range = std::make_unique<ConstElemRange>(*range);
9673 }
9674 void
9676 {
9677  if (!range)
9678  {
9680  return;
9681  }
9682 
9683  _current_algebraic_node_range = std::make_unique<ConstNodeRange>(*range);
9684 }
9685 void
9687 {
9688  if (!range)
9689  {
9691  return;
9692  }
9693 
9694  _current_algebraic_bnd_node_range = std::make_unique<ConstBndNodeRange>(*range);
9695 }
9696 
9697 unsigned short
9699 {
9700  return _current_ic_state;
9701 }
9702 
9703 std::string
9704 FEProblemBase::solverTypeString(const unsigned int solver_sys_num)
9705 {
9706  return Moose::stringify(solverParams(solver_sys_num)._type);
9707 }
9708 
9711 {
9712  SolverParams solver_params;
9713  solver_params._type = Moose::SolveType::ST_LINEAR;
9715  return solver_params;
9716 }
9717 
9720 {
9721  return _nonlocal_cm[i];
9722 }
9723 
9724 bool
9726 {
9728 }
9729 
9730 const std::unordered_map<std::pair<BoundaryID, BoundaryID>,
9731  std::unique_ptr<AutomaticMortarGeneration>> &
9732 FEProblemBase::getMortarInterfaces(bool on_displaced) const
9733 {
9734  return _mortar_data->getMortarInterfaces(on_displaced);
9735 }
bool _reinit_displaced_elem
Whether to call DisplacedProblem::reinitElem when this->reinitElem is called.
This class determines the maximum number of Quadrature Points and Shape Functions used for a given si...
Definition: MaxQpsThread.h:27
virtual void addInterfaceMaterial(const std::string &material_name, const std::string &name, InputParameters &parameters)
std::map< NonlinearSystemName, unsigned int > _nl_sys_name_to_num
Map from nonlinear system name to number.
void setCurrentAlgebraicElementRange(libMesh::ConstElemRange *range)
These functions allow setting custom ranges for the algebraic elements, nodes, and boundary nodes tha...
std::string indent(unsigned int spaces)
Create empty string for indenting.
Definition: ConsoleUtils.C:41
void addControllableParameterConnection(const MooseObjectParameterName &primary, const MooseObjectParameterName &secondary, bool error_on_empty=true)
Method for linking control parameters of different names.
std::vector< Point > _point_zero
Interface for objects that need parallel consistent random numbers without patterns over the course o...
void updateVariableDependency(std::set< MooseVariableFieldBase *> &needed_moose_vars, THREAD_ID tid=0) const
Update variable dependency vector.
virtual void addCachedResidual(const THREAD_ID tid)
Definition: SubProblem.C:1310
virtual void computeJacobianTag(const NumericVector< libMesh::Number > &soln, libMesh::SparseMatrix< libMesh::Number > &jacobian, TagID tag)
Form a Jacobian matrix for a given tag.
void addObject(std::shared_ptr< T > object, THREAD_ID tid=0, bool recurse=true) override
Adds an object to the storage structure.
unsigned short getCurrentICState()
Retrieves the current initial condition state.
void finalizeMultiApps()
virtual void addFVInitialCondition(const std::string &ic_name, const std::string &name, InputParameters &parameters)
Add an initial condition for a finite volume variables.
bool adaptMesh(std::string marker_name=std::string())
Adapts the mesh based on the error estimator used.
Definition: Adaptivity.C:131
void sort(THREAD_ID tid=0)
Sort the objects using the DependencyResolver.
VarFieldType
Definition: MooseTypes.h:770
virtual void addMaterialHelper(std::vector< MaterialWarehouse *> warehouse, const std::string &material_name, const std::string &name, InputParameters &parameters)
bool initialAdaptMesh()
Used during initial adaptivity.
Definition: Adaptivity.C:268
virtual void residualSetup(THREAD_ID tid=0) const
virtual bool hasVariable(const std::string &var_name) const override
Whether or not this problem has the variable.
virtual void stopSolve(const ExecFlagType &exec_flag, const std::set< TagID > &vector_tags_to_close) override
Quit the current solve as soon as possible.
Definition: LinearSystem.C:339
bool hasInvalidSolutionError() const
Whether or not an invalid solution was encountered that was an error.
void mooseInfo(Args &&... args) const
Definition: MooseBase.h:321
void setActiveMaterialProperties(const std::unordered_set< unsigned int > &mat_prop_ids, const THREAD_ID tid)
Record and set the material properties required by the current computing thread.
const bool _regard_general_exceptions_as_errors
If we catch an exception during residual/Jacobian evaluaton for which we don&#39;t have specific handling...
const std::size_t _num_nl_sys
The number of nonlinear systems.
void setVariableAllDoFMap(const std::vector< const MooseVariableFEBase *> &moose_vars)
void computeJacobianBlocks(std::vector< JacobianBlock *> &blocks)
Computes several Jacobian blocks simultaneously, summing their contributions into smaller preconditio...
virtual void initPetscOutputAndSomeSolverSettings()
Reinitialize PETSc output for proper linear/nonlinear iteration display.
const std::vector< ConvergenceName > & getNonlinearConvergenceNames() const
Gets the nonlinear system convergence object name(s).
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:50
void timestepSetup() override
virtual void addSampler(const std::string &type, const std::string &name, InputParameters &parameters)
The following functions will enable MOOSE to have the capability to import Samplers.
bool _skip_exception_check
If or not skip &#39;exception and stop solve&#39;.
const std::vector< std::string > & get_global_var_names()
bool isFiniteVolumeInfoDirty() const
Definition: MooseMesh.h:1322
Helper class for holding the preconditioning blocks to fill.
virtual void restore_original_nonzero_pattern()
bool _reinit_displaced_neighbor
Whether to call DisplacedProblem::reinitNeighbor when this->reinitNeighbor is called.
virtual void clearActiveFEVariableCoupleableMatrixTags(const THREAD_ID tid)
Definition: SubProblem.C:385
void outputStep(ExecFlagType type)
Calls the outputStep method for each output object.
virtual void meshChanged()
Deprecated.
virtual void addDamper(const std::string &damper_name, const std::string &name, InputParameters &parameters)
std::map< LinearSystemName, unsigned int > _linear_sys_name_to_num
Map from linear system name to number.
virtual void clearActiveFEVariableCoupleableVectorTags(const THREAD_ID tid)
Definition: SubProblem.C:379
libMesh::ConstElemRange * getActiveLocalElementRange()
Return pointers to range objects for various types of ranges (local nodes, boundary elems...
Definition: MooseMesh.C:1288
void getFVMatsAndDependencies(SubdomainID block_id, std::vector< std::shared_ptr< MaterialBase >> &face_materials, std::vector< std::shared_ptr< MaterialBase >> &neighbor_materials, std::set< MooseVariableFieldBase *> &variables, const THREAD_ID tid)
Get the materials and variables potentially needed for FV.
std::vector< MooseArray< ADRealTensorValue > > _ad_second_zero
bool _have_ad_objects
AD flag indicating whether any AD objects have been added.
Definition: SubProblem.h:1116
void shift()
Shift the material properties in time.
virtual void prepareFace(const Elem *elem, const THREAD_ID tid) override
Base class for function objects.
Definition: Function.h:29
void setPreserveMatrixSparsityPattern(bool preserve)
Set whether the sparsity pattern of the matrices being formed during the solve (usually the Jacobian)...
void reinitBecauseOfGhostingOrNewGeomObjects(bool mortar_changed=false)
Call when it is possible that the needs for ghosted elements has changed.
void fill_data(std::map< processor_id_type, std::vector< std::set< unsigned int >>> &data, int M)
virtual void addTransfer(const std::string &transfer_name, const std::string &name, InputParameters &parameters)
Add a Transfer to the problem.
KOKKOS_INLINE_FUNCTION const T * find(const T &target, const T *const begin, const T *const end)
Find a value in an array.
Definition: KokkosUtils.h:42
const std::string & getBoundaryName(BoundaryID boundary_id) const
Return the name of the boundary given the id.
Definition: MooseMesh.C:1842
virtual libMesh::System & getSystem(const std::string &var_name) override
Returns the equation system containing the variable provided.
virtual void setActiveScalarVariableCoupleableMatrixTags(std::set< TagID > &mtags, const THREAD_ID tid)
Definition: SubProblem.C:403
static const std::string app_param
The name of the parameter that contains the MooseApp.
Definition: MooseBase.h:59
A MultiMooseEnum object to hold "execute_on" flags.
Definition: ExecFlagEnum.h:21
static SolverParams makeLinearSolverParams()
Make basic solver params for linear solves.
Order
bool _parallel_barrier_messaging
Whether or not information about how many transfers have completed is printed.
MooseVariableFieldBase & getVariableHelper(const THREAD_ID tid, const std::string &var_name, Moose::VarKindType expected_var_type, Moose::VarFieldType expected_var_field_type, const std::vector< T > &nls, const SystemBase &aux) const
Helper function called by getVariable that handles the logic for checking whether Variables of the re...
virtual void addResidualLower(const THREAD_ID tid) override
A class for creating restricted objects.
Definition: Restartable.h:28
bool isUltimateMaster() const
Whether or not this app is the ultimate master app.
Definition: MooseApp.h:820
virtual void addJacobianLowerD(const THREAD_ID tid) override
Factory & _factory
The Factory for building objects.
Definition: SubProblem.h:1049
virtual void clearActiveScalarVariableCoupleableVectorTags(const THREAD_ID tid) override
MaterialPropertyStorage & _bnd_material_props
virtual void addGhostedElem(dof_id_type elem_id) override
Will make sure that all dofs connected to elem_id are ghosted to this processor.
void setNonlocalCouplingMatrix()
Set custom coupling matrix for variables requiring nonlocal contribution.
Threads::spin_mutex get_function_mutex
void initialSetup()
Calls the initialSetup function for each of the output objects.
virtual Real & time() const
virtual const char * what() const
Get out the error message.
std::vector< std::pair< MooseVariableFEBase *, MooseVariableFEBase * > > & couplingEntries(const THREAD_ID tid, const unsigned int nl_sys_num)
const Variable & variable(unsigned int var) const
void checkDependMaterialsHelper(const std::map< SubdomainID, std::vector< std::shared_ptr< MaterialBase >>> &materials_map)
Helper method for checking Material object dependency.
void extraSparsity(libMesh::SparsityPattern::Graph &sparsity, std::vector< dof_id_type > &n_nz, std::vector< dof_id_type > &n_oz, void *context)
Free function used for a libMesh callback.
Definition: SystemBase.C:48
unsigned int n_threads()
void projectFunctionOnCustomRange(ConstElemRange &elem_range, Number(*func)(const Point &, const libMesh::Parameters &, const std::string &, const std::string &), Gradient(*func_grad)(const Point &, const libMesh::Parameters &, const std::string &, const std::string &), const libMesh::Parameters &params, const VariableName &target_var)
Project a function onto a range of elements for a given variable.
virtual void cacheResidualNeighbor(const THREAD_ID tid) override
void addDeprecatedParam(const std::string &name, const T &value, const std::string &doc_string, const std::string &deprecation_message)
ExecFlagType _current_execute_on_flag
Current execute_on flag.
const std::set< SubdomainID > & interiorLowerDBlocks() const
Definition: MooseMesh.h:1421
void clearCurrentResidualVectorTags()
Clear the current residual vector tag data structure.
unsigned int max() const
Definition: MaxQpsThread.h:39
bool hasActiveBlockObjects(THREAD_ID tid=0) const
QueryCache is a convenient way to construct and pass around (possible partially constructed) warehous...
Definition: TheWarehouse.h:208
std::shared_ptr< DisplacedProblem > displaced_problem
const unsigned int invalid_uint
virtual void reinitLowerDElem(const Elem *lower_d_elem, const THREAD_ID tid, const std::vector< Point > *const pts=nullptr, const std::vector< Real > *const weights=nullptr)
Definition: SubProblem.C:958
RelationshipManagerType
Main types of Relationship Managers.
Definition: MooseTypes.h:1012
bool hasVector(const std::string &tag_name) const
Check if the named vector exists in the system.
Definition: SystemBase.C:924
unsigned int get_node_index(const Node *node_ptr) const
virtual void checkExceptionAndStopSolve(bool print_message=true)
Check to see if an exception has occurred on any processor and, if possible, force the solve to fail...
virtual void meshDisplaced()
Update data after a mesh displaced.
const std::set< BoundaryID > & getSubdomainBoundaryIds(const SubdomainID subdomain_id) const
Get the list of boundary ids associated with the given subdomain id.
Definition: MooseMesh.C:3577
std::optional< ConvergenceName > _multiapp_fixed_point_convergence_name
MultiApp fixed point convergence name.
const std::string & name() const
Definition: MooseEnumItem.h:35
MooseAppCoordTransform & coordTransform()
virtual void setActiveFEVariableCoupleableMatrixTags(std::set< TagID > &mtags, const THREAD_ID tid) override
void setCurrentAlgebraicNodeRange(libMesh::ConstNodeRange *range)
static InputParameters validParams()
Describes the parameters this object can take to setup transformations.
SCALAR
void paramError(const std::string &param, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
Definition: MooseBase.h:439
const std::map< SubdomainID, std::vector< std::shared_ptr< T > > > & getActiveBlockObjects(THREAD_ID tid=0) const
unsigned int TagID
Definition: MooseTypes.h:238
Real computeDamping(const NumericVector< Number > &solution, const NumericVector< Number > &update)
Compute damping.
const T & getParam(const std::string &name) const
Retrieve a parameter for the object.
Definition: MooseBase.h:388
virtual void reinitNode(const Node *node, const THREAD_ID tid) override
virtual std::size_t numNonlinearSystems() const override
Base class for implementing interface user objects.
virtual void setPreviousNewtonSolution(const NumericVector< Number > &soln)
virtual void predictorCleanup(NumericVector< libMesh::Number > &ghosted_solution)
Perform cleanup tasks after application of predictor to solution vector.
virtual void prepare(const Elem *elem, const THREAD_ID tid) override
TagID rightHandSideVectorTag() const
Definition: LinearSystem.h:114
virtual Elem * elemPtr(const dof_id_type i)
Definition: MooseMesh.C:3193
MPI_Datatype data_type
TagID systemMatrixTag() const override
Return the Matrix Tag ID for System.
NumericVector< Number > & solution()
Definition: SystemBase.h:196
bool hasObjects(THREAD_ID tid=0) const
Convenience functions for determining if objects exist.
bool _has_jacobian
Indicates if the Jacobian was computed.
virtual bool haveFV() const override
returns true if this problem includes/needs finite volume functionality.
char ** blocks
Interface for objects acting when the mesh has been displaced.
static void uniformRefine(MooseMesh *mesh, unsigned int level=libMesh::invalid_uint)
Performs uniform refinement of the passed Mesh object.
Definition: Adaptivity.C:274
void addPrivateParam(const std::string &name, const T &value)
These method add a parameter to the InputParameters object which can be retrieved like any other para...
bool _has_dampers
Whether or not this system has any Dampers associated with it.
MooseObjectWarehouse< InternalSideIndicatorBase > _internal_side_indicators
void shift()
Shift current, old, and older material property data storages.
std::vector< SubdomainName > _kernel_coverage_blocks
const std::map< dof_id_type, std::vector< dof_id_type > > & nodeToActiveSemilocalElemMap()
If not already created, creates a map from every node to all active semilocal elements to which they ...
Definition: MooseMesh.C:1256
virtual Distribution & getDistribution(const std::string &name)
void swapBack(const Elem &elem, unsigned int side=0)
material properties for given element (and possible side)
Definition: MaterialData.C:58
bool _has_nonlocal_coupling
Indicates if nonlocal coupling is required/exists.
void setCurrentAlgebraicBndNodeRange(ConstBndNodeRange *range)
void dof_indices(const Elem *const elem, std::vector< dof_id_type > &di) const
This is the base class for Samplers as used within the Stochastic Tools module.
Definition: Sampler.h:43
Base class for predictors.
Definition: Predictor.h:28
bool areCoupled(const unsigned int ivar, const unsigned int jvar, const unsigned int nl_sys_num) const
Moose::LineSearchType _line_search
Definition: SolverParams.h:20
const std::string & getObjectName() const
const T & get() const
Get the restartable value.
Definition: Restartable.h:58
void setPostprocessorValueByName(const PostprocessorName &name, const PostprocessorValue &value, std::size_t t_index=0)
Set the value of a PostprocessorValue.
virtual void clearActiveScalarVariableCoupleableMatrixTags(const THREAD_ID tid) override
virtual void postExecute()
Method called at the end of the simulation.
void reinit(bool reinit_for_derivative_reordering=false)
Fill out the VariableValue arrays from the system solution vector.
unsigned int number() const
Get variable number coming from libMesh.
void eraseProperty(const Elem *elem)
Remove the property storage and element pointer from internal data structures Use this when elements ...
bool isSolverSystemNonlinear(const unsigned int sys_num)
Check if the solver system is nonlinear.
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.
void petscSetDefaults(FEProblemBase &problem)
Sets the default options for PETSc.
Definition: PetscSupport.C:450
std::unordered_set< TagID > _not_zeroed_tagged_vectors
the list of vector tags that will not be zeroed when all other tags are
Definition: SubProblem.h:1119
void joinAndFinalize(TheWarehouse::Query query, bool isgen=false)
DISCRETE_L2
bool hasInitialBackup() const
Definition: MooseApp.h:1001
std::vector< MooseArray< ADRealVectorValue > > _ad_grad_zero
std::vector< SolverParams > _solver_params
InputParameterWarehouse & getInputParameterWarehouse()
Get the InputParameterWarehouse for MooseObjects.
Definition: MooseApp.C:2983
ExecuteMooseObjectWarehouse< Control > _control_warehouse
The control logic warehouse.
void reinitMaterialsFaceOnBoundary(const BoundaryID boundary_id, const SubdomainID blk_id, const THREAD_ID tid, const bool swap_stateful=true, const std::deque< MaterialBase *> *const reinit_mats=nullptr)
reinit materials on element faces on a boundary (internal or external) This specific routine helps us...
void updateActive(THREAD_ID tid=0) override
Updates the active objects storage.
virtual std::pair< bool, unsigned int > determineSolverSystem(const std::string &var_name, bool error_if_not_found=false) const override
Determine what solver system the provided variable name lies in.
std::unique_ptr< libMesh::ConstNodeRange > _current_algebraic_node_range
virtual void setActiveScalarVariableCoupleableMatrixTags(std::set< TagID > &mtags, const THREAD_ID tid) override
void setCoupling(Moose::CouplingType type)
Set the coupling between variables TODO: allow user-defined coupling.
constexpr std::size_t constMaxQpsPerElem
This is used for places where we initialize some qp-sized data structures that would end up being siz...
Definition: MooseTypes.h:258
const ExecFlagType & getCurrentExecuteOnFlag() const
Return/set the current execution flag.
unsigned int _cycles_completed
bool _currently_computing_jacobian
Flag to determine whether the problem is currently computing Jacobian.
Definition: SubProblem.h:1098
virtual void reinitScalars(const THREAD_ID tid, bool reinit_for_derivative_reordering=false) override
fills the VariableValue arrays for scalar variables from the solution vector
const ExecFlagEnum & getExecuteOnEnum() const
Return the app level ExecFlagEnum, this contains all the available flags for the app.
Definition: MooseApp.h:994
virtual void init() override
void add(std::shared_ptr< MooseObject > obj)
add adds a new object to the warehouse and stores attributes/metadata about it for running queries/fi...
Definition: TheWarehouse.C:116
void translateMetaPhysicLError(const MetaPhysicL::LogicError &)
emit a relatively clear error message when we catch a MetaPhysicL logic error
Definition: MooseError.C:141
virtual void getDiracElements(std::set< const Elem *> &elems) override
Fills "elems" with the elements that should be looped over for Dirac Kernels.
virtual void setActiveElementalMooseVariables(const std::set< MooseVariableFieldBase *> &moose_vars, const THREAD_ID tid)
Set the MOOSE variables to be reinited on each element.
Definition: SubProblem.C:444
void parentOutputPositionChanged()
Calls parentOutputPositionChanged() on all sub apps.
void setupDM()
Setup the PETSc DM object (when appropriate)
virtual void setCurrentBoundaryID(BoundaryID bid, const THREAD_ID tid)
sets the current boundary ID in assembly
Definition: SubProblem.C:790
virtual void addInterfaceKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
virtual void neighborSubdomainSetup(THREAD_ID tid=0) const
libMesh::LinearImplicitSystem & linearImplicitSystem()
Return a reference to the stored linear implicit system.
Definition: LinearSystem.h:86
bool _is_petsc_options_inserted
If or not PETSc options have been added to database.
void setCurrentlyComputingResidual(bool currently_computing_residual) final
Set whether or not the problem is in the process of computing the residual.
virtual void addMaterial(const std::string &material_name, const std::string &name, InputParameters &parameters)
virtual void lineSearch()
execute MOOSE line search
const std::vector< T > & getSortedValues()
This function also returns dependency resolved values but with a simpler single vector interface...
unsigned int getCyclesPerStep() const
Pull out the number of cycles_per_step previously set through the AdaptivityAction.
Definition: Adaptivity.h:112
virtual void setCurrentLowerDElem(const Elem *const lower_d_elem, const THREAD_ID tid)
Set the current lower dimensional element.
Definition: SubProblem.C:1385
const Elem * getLowerDElem(const Elem *, unsigned short int) const
Returns a const pointer to a lower dimensional element that corresponds to a side of a higher dimensi...
Definition: MooseMesh.C:1751
NonlocalIntegratedBC is used for solving integral terms in integro-differential equations.
virtual bool checkNonlocalCouplingRequirement() const override
virtual bool uDotDotRequested()
Get boolean flag to check whether solution second time derivative needs to be stored.
bool _has_kokkos_objects
Whether we have any Kokkos objects.
void updateErrorVectors()
Update the ErrorVectors that have been requested through calls to getErrorVector().
Definition: Adaptivity.C:372
const InputParameters & parameters() const
Get the parameters of the object.
Definition: MooseBase.h:131
unsigned short _current_ic_state
char ** vars
FORTYTHIRD
virtual void reinitNeighborPhys(const Elem *neighbor, unsigned int neighbor_side, const std::vector< Point > &physical_points, const THREAD_ID tid) override
virtual TagID addVectorTag(const TagName &tag_name, const Moose::VectorTagType type=Moose::VECTOR_TAG_RESIDUAL)
Create a Tag.
Definition: SubProblem.C:93
std::vector< MeshDisplacedInterface * > _notify_when_mesh_displaces
Objects to be notified when the mesh displaces.
std::vector< T * > & queryInto(std::vector< T *> &results, Args &&... args)
queryInto executes the query and stores the results in the given vector.
Definition: TheWarehouse.h:311
void trustUserCouplingMatrix()
Whether to trust the user coupling matrix even if we want to do things like be paranoid and create a ...
virtual void newAssemblyArray(std::vector< std::shared_ptr< SolverSystem >> &solver_systems)
const bool _uo_aux_state_check
Whether or not checking the state of uo/aux evaluation.
virtual const std::set< MooseVariableFieldBase * > & getActiveElementalMooseVariables(const THREAD_ID tid) const
Get the MOOSE variables to be reinited on each element.
Definition: SubProblem.C:455
This is a template class that implements the workhorse compute and computeNodal methods.
virtual void addMeshDivision(const std::string &type, const std::string &name, InputParameters &params)
Add a MeshDivision.
const ExecFlagType EXEC_NONE
Definition: Moose.C:29
A struct for storing the various types of petsc options and values.
Definition: PetscSupport.h:44
virtual void computeMarkers()
void reportMooseObjectDependency(MooseObject *a, MooseObject *b)
Register a MOOSE object dependency so we can either order operations properly or report when we canno...
void residualSetup() override
MaterialDataType
MaterialData types.
Definition: MooseTypes.h:740
void computeUserObjectsInternal(const ExecFlagType &type, const Moose::AuxGroup &group, TheWarehouse::Query &query)
TagID nonTimeVectorTag() const override
A class for "pretty printing" a table of data.
Definition: PerfGraph.h:34
virtual void addCachedJacobian(const THREAD_ID tid)
Definition: SubProblem.C:1331
void cacheChangedLists()
Cache information about what elements were refined and coarsened in the previous step.
Definition: MooseMesh.C:940
virtual void residualSetup()
Definition: SubProblem.C:1204
Positions objects are under the hood Reporters.
Definition: Positions.h:20
T & set(const std::string &name, bool quiet_mode=false)
Returns a writable reference to the named parameters.
void reinitMortarUserObjects(BoundaryID primary_boundary_id, BoundaryID secondary_boundary_id, bool displaced)
Call reinit on mortar user objects with matching primary boundary ID, secondary boundary ID...
virtual TagID systemMatrixTag() const override
Return the Matrix Tag ID for System.
Definition: LinearSystem.h:115
virtual void associateVectorToTag(NumericVector< Number > &vec, TagID tag)
Associate a vector for a given tag.
Definition: SystemBase.C:981
virtual void reinitNodes(const std::vector< dof_id_type > &nodes, const THREAD_ID tid) override
virtual void updateActiveObjects()
Update the active objects in the warehouses.
Stores the stateful material properties computed by materials.
const RestartableEquationSystems & getRestartableEquationSystems() const
Get the RestartableEquationSystems object.
virtual void computeIndicatorsAndMarkers()
Definition: Marker.h:41
void reinitMaterialsBoundary(BoundaryID boundary_id, const THREAD_ID tid, bool swap_stateful=true, const std::deque< MaterialBase *> *reinit_mats=nullptr)
reinit materials on a boundary
virtual void addJacobianOffDiagScalar(unsigned int ivar, const THREAD_ID tid=0)
virtual void setException(const std::string &message)
Set an exception, which is stored at this point by toggling a member variable in this class...
virtual void addJacobian(const THREAD_ID tid) override
void addFunctor(const std::string &name, const Moose::FunctorBase< T > &functor, const THREAD_ID tid)
add a functor to the problem functor container
Definition: SubProblem.h:1380
virtual libMesh::System & system()=0
Get the reference to the libMesh system.
std::filesystem::path restartFolderBase(const std::filesystem::path &folder_base) const
The file suffix for restartable data.
Definition: MooseApp.C:3170
virtual void addAuxScalarKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
virtual void customSetup(const ExecFlagType &exec_type, THREAD_ID tid=0) const
bool isReservedName(const std::string &name)
Test if the given name is reserved.
bool globalADIndexing()
Whether we are using global AD indexing.
Definition: ADUtils.h:28
bool hasOutput(const std::string &name) const
Returns true if the output object exists.
Base class for MOOSE-based applications.
Definition: MooseApp.h:103
void mooseInfoRepeated(Args &&... args)
Emit an informational message with the given stringified, concatenated args.
Definition: MooseError.h:398
PetscOptions _petsc_option_data_base
bool needBoundaryMaterialOnSide(BoundaryID bnd_id, const THREAD_ID tid)
These methods are used to determine whether stateful material properties need to be stored on interna...
virtual const std::vector< VectorTag > & currentResidualVectorTags() const override
Return the residual vector tags we are currently computing.
processor_id_type rank() const
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
std::vector< SubdomainName > _material_coverage_blocks
bool computingScalingJacobian() const
Whether we are computing an initial Jacobian for automatic variable scaling.
Definition: SystemBase.C:1552
TODO: delete this later - it is a temporary hack for dealing with inter-system dependencies.
Definition: Attributes.h:313
NumericVector< Number > * rhs
void setSteadyStateConvergenceName(const ConvergenceName &convergence_name)
Sets the steady-state detection convergence object name if there is one.
void applyParameters(const InputParameters &common, const std::vector< std::string > &exclude={}, const bool allow_private=false)
Method for applying common parameters.
virtual void addAuxScalarVariable(const std::string &var_name, libMesh::Order order, Real scale_factor=1., const std::set< SubdomainID > *const active_subdomains=NULL)
virtual const SystemBase & systemBaseLinear(unsigned int sys_num) const override
Get a constant base class reference to a linear system.
const Parallel::Communicator & comm() const
void logAdd(const std::string &system, const std::string &name, const std::string &type, const InputParameters &params) const
Output information about the object just added to the problem.
QuadratureType
virtual bool hasScalarVariable(const std::string &var_name) const override
Returns a Boolean indicating whether any system contains a variable with the name provided...
void setSolution(const NumericVector< Number > &soln)
Set the solution to a given vector.
Definition: SolverSystem.C:67
MultiApp Implementation for Transient Apps.
Solving a linear problem.
Definition: MooseTypes.h:897
void resizeMaterialData(Moose::MaterialDataType data_type, unsigned int nqp, const THREAD_ID tid)
Resize material data.
void finishMultiAppStep(ExecFlagType type, bool recurse_through_multiapp_levels=false)
Finish the MultiApp time step (endStep, postStep) associated with the ExecFlagType.
virtual void addFunctorMaterial(const std::string &functor_material_name, const std::string &name, InputParameters &parameters)
virtual void timestepSetup(THREAD_ID tid=0) const
std::vector< VariableSecond > _second_zero
std::map< SolverVariableName, unsigned int > _solver_var_to_sys_num
Map connecting variable names with their respective solver systems.
virtual std::unique_ptr< NumericVector< T > > clone() const=0
std::vector< MooseArray< ADReal > > _ad_zero
void customSetup(const ExecFlagType &exec_type)
Calls the setup function for each of the output objects.
virtual bool hasMatrix(TagID tag) const
Check if the tagged matrix exists in the system.
Definition: SystemBase.h:360
bool _requires_nonlocal_coupling
nonlocal coupling requirement flag
virtual void onTimestepEnd() override
virtual void computeNearNullSpace(libMesh::NonlinearImplicitSystem &sys, std::vector< NumericVector< libMesh::Number > *> &sp)
virtual void addNodalKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
std::vector< std::shared_ptr< SolverSystem > > _solver_systems
Combined container to base pointer of every solver system.
All Distributions should inherit from this class.
Definition: Distribution.h:18
void setCurrentDirection(const int direction)
Set this Transfer to be executed in a given direction.
Definition: Transfer.h:89
std::unique_ptr< T_DEST, T_DELETER > dynamic_pointer_cast(std::unique_ptr< T_SRC, T_DELETER > &src)
These are reworked from https://stackoverflow.com/a/11003103.
ConstElemPointerRange * refinedElementRange() const
Return a range that is suitable for threaded execution over elements that were just refined...
Definition: MooseMesh.C:958
MaterialWarehouse _kokkos_materials
std::vector< VectorVariableCurl > _vector_curl_zero
static void selectVectorTagsFromSystem(const SystemBase &system, const std::vector< VectorTag > &input_vector_tags, std::set< TagID > &selected_tags)
Select the vector tags which belong to a specific system.
Definition: SubProblem.C:290
Base class for user objects executed one or more sidesets, which may be on the outer boundary of the ...
bool _has_exception
Whether or not an exception has occurred.
unsigned int _num_grid_steps
Number of steps in a grid sequence.
virtual void associateMatrixToTag(libMesh::SparseMatrix< Number > &matrix, TagID tag)
Associate a matrix to a tag.
Definition: SystemBase.C:1076
bool haveXFEM()
Find out whether the current analysis is using XFEM.
virtual void addJacobianBlockTags(libMesh::SparseMatrix< libMesh::Number > &jacobian, unsigned int ivar, unsigned int jvar, const DofMap &dof_map, std::vector< dof_id_type > &dof_indices, const std::set< TagID > &tags, const THREAD_ID tid)
void registerRandomInterface(RandomInterface &random_interface, const std::string &name)
bool _has_time_integrator
Indicates whether or not this executioner has a time integrator (during setup)
This class provides an interface for common operations on field variables of both FE and FV types wit...
const Parallel::Communicator & _communicator
virtual void addAuxKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
MaterialPropertyRegistry _material_prop_registry
virtual void jacobianSetup()
Definition: SubProblem.C:1212
void clearActiveMaterialProperties(const THREAD_ID tid)
Clear the active material properties.
virtual unsigned int nLinearIterations(const unsigned int nl_sys_num) const override
bool has_static_condensation() const
std::vector< subdomain_id_type > getSubdomainIDs(const libMesh::MeshBase &mesh, const std::vector< SubdomainName > &subdomain_name)
Get the associated subdomainIDs for the subdomain names that are passed in.
ExecuteMooseObjectWarehouse< TransientMultiApp > _transient_multi_apps
Storage for TransientMultiApps (only needed for calling &#39;computeDT&#39;)
bool hasUserObject(const std::string &name) const
Check if there if a user object of given name.
MaterialWarehouse _interface_materials
Real getStartTime() const
Definition: MooseApp.h:300
Thread to compute threaded general user objects.
The following methods are specializations for using the libMesh::Parallel::packed_range_* routines fo...
bool _ignore_zeros_in_jacobian
Whether to ignore zeros in the Jacobian, thereby leading to a reduced sparsity pattern.
const libMesh::ConstElemRange & getCurrentAlgebraicElementRange()
These are the element and nodes that contribute to the jacobian and residual for this local processor...
void setup(const ExecFlagType &exec_flag, THREAD_ID tid=0) const
void setCurrentExecuteOnFlag(const ExecFlagType &)
virtual void computeResidualInternal(const NumericVector< libMesh::Number > &soln, NumericVector< libMesh::Number > &residual, const std::set< TagID > &tags)
Form a residual vector for a set of tags.
void copyValuesBack()
Copies current chain control data values into old values.
void initElementStatefulProps(const libMesh::ConstElemRange &elem_range, const bool threaded)
Initialize stateful properties for elements in a specific elem_range This is needed when elements/bou...
const libMesh::ConstNodeRange & getCurrentAlgebraicNodeRange()
void setCurrentlyComputingResidualAndJacobian(bool currently_computing_residual_and_jacobian)
Set whether or not the problem is in the process of computing the Jacobian.
Definition: SubProblem.h:1498
ExecuteMooseObjectWarehouse< Transfer > _from_multi_app_transfers
Transfers executed just after MultiApps to transfer data from them.
virtual void addKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
libMesh::TensorValue< ADReal > ADRealTensorValue
Definition: MooseTypes.h:409
Base class for a system (of equations)
Definition: SystemBase.h:84
const ExecFlagType EXEC_ALWAYS
Definition: Moose.C:51
SparseMatrix< Number > & getSystemMatrix()
Fetching the system matrix from the libmesh system.
Definition: LinearSystem.h:126
This user object allows related evaluations on elements, boundaries, internal sides, interfaces in one single place.
virtual void addAuxVariable(const std::string &var_type, const std::string &var_name, InputParameters &params)
Canonical method for adding an auxiliary variable.
SECOND
std::pair< typename M::iterator, bool > moose_try_emplace(M &m, const typename M::key_type &k, Args &&... args)
Function to mirror the behavior of the C++17 std::map::try_emplace() method (no hint).
Definition: Moose.h:101
const T_sys & get_system(std::string_view name) const
std::optional< ConvergenceName > _steady_state_convergence_name
Steady-state detection convergence name.
Base class for MeshDivision objects.
Definition: MeshDivision.h:35
MooseObjectWarehouse< Moose::FunctionBase > _kokkos_functions
bool computingNonlinearResid() const
Returns true if the problem is in the process of computing the nonlinear residual.
Definition: SubProblem.h:707
virtual void addFVInterfaceKernel(const std::string &fv_ik_name, const std::string &name, InputParameters &parameters)
MeshDivision & getMeshDivision(const std::string &name, const THREAD_ID tid=0) const
Get a MeshDivision.
bool isRestarting() const
Whether or not this is a "restart" calculation.
Definition: MooseApp.C:1890
Base class for creating new nodally-based mortar user objects.
Reporter objects allow for the declaration of arbitrary data types that are aggregate values for a si...
Definition: Reporter.h:47
const Positions & getPositionsObject(const std::string &name) const
Get the Positions object by its name.
libMesh::ConstNodeRange * getLocalNodeRange()
Definition: MooseMesh.C:1325
std::map< SolverSystemName, unsigned int > _solver_sys_name_to_num
Map connecting solver system names with their respective systems.
FEProblemBase(const InputParameters &parameters)
void addEdge(const T &a, const T &b)
Add an edge between nodes &#39;a&#39; and &#39;b&#39;.
std::string convertLatestCheckpoint(std::string orig)
Definition: MooseUtils.C:157
void prepareScalar()
Definition: Assembly.C:2951
bool isOn()
Is adaptivity on?
Definition: Adaptivity.h:179
void computeResidualTags(const std::set< TagID > &tags)
Form multiple tag-associated residual vectors for all the given tags.
virtual void cacheJacobianNeighbor(const THREAD_ID tid) override
const std::string & getBase() const
Specialization of SubProblem for solving nonlinear equations plus auxiliary equations.
virtual void clearActiveElementalMooseVariables(const THREAD_ID tid)
Clear the active elemental MooseVariableFieldBase.
Definition: SubProblem.C:467
std::vector< std::unordered_map< BoundaryID, bool > > _bnd_mat_side_cache
Cache for calculating materials on side.
bool hasLinearConvergenceObjects() const
Whether we have linear convergence objects.
virtual const Node & nodeRef(const dof_id_type i) const
Definition: MooseMesh.C:861
std::set< dof_id_type > _ghosted_elems
Elements that should have Dofs ghosted to the local processor.
Definition: SubProblem.h:1095
ExecFlagEnum _print_execution_on
When to print the execution of loops.
std::vector< SubdomainID > getSubdomainIDs(const std::vector< SubdomainName > &subdomain_names) const
Get the associated subdomainIDs for the subdomain names that are passed in.
Definition: MooseMesh.C:1787
void clearAllDofIndices()
Clear dof indices from variables in nl and aux systems.
Definition: SubProblem.C:1178
virtual void setResidual(NumericVector< libMesh::Number > &residual, const THREAD_ID tid) override
virtual void solve(const unsigned int nl_sys_num)
virtual void setCurrentLowerDElem(const Elem *const lower_d_elem, const THREAD_ID tid) override
Set the current lower dimensional element.
std::set< TagID > _linear_matrix_tags
Temporary storage for filtered matrix tags for linear systems.
MooseApp & getMooseApp() const
Get the MooseApp this class is associated with.
Definition: MooseBase.h:87
void bumpAllQRuleOrder(libMesh::Order order, SubdomainID block)
Real computeMultiAppsDT(ExecFlagType type)
Find the smallest timestep over all MultiApps.
const std::string & getSubdomainName(SubdomainID subdomain_id) const
Return the name of a block given an id.
Definition: MooseMesh.C:1813
virtual void reinitNeighborFaceRef(const Elem *neighbor_elem, unsigned int neighbor_side, Real tolerance, const std::vector< Point > *const pts, const std::vector< Real > *const weights=nullptr, const THREAD_ID tid=0)
reinitialize FE objects on a given neighbor element on a given side at a given set of reference point...
Definition: SubProblem.C:922
void projectSolution()
virtual const MooseVariableFieldBase & getVariable(const THREAD_ID tid, const std::string &var_name, Moose::VarKindType expected_var_type=Moose::VarKindType::VAR_ANY, Moose::VarFieldType expected_var_field_type=Moose::VarFieldType::VAR_FIELD_ANY) const override
Returns the variable reference for requested variable which must be of the expected_var_type (Nonline...
void reinitMaterialsFace(SubdomainID blk_id, const THREAD_ID tid, bool swap_stateful=true, const std::deque< MaterialBase *> *reinit_mats=nullptr)
reinit materials on element faces
std::unique_ptr< libMesh::ConstElemRange > _nl_evaluable_local_elem_range
virtual void disassociateMatrixFromTag(libMesh::SparseMatrix< Number > &matrix, TagID tag)
Disassociate a matrix from a tag.
Definition: SystemBase.C:1088
Scope guard for starting and stopping Floating Point Exception Trapping.
virtual void computeResidualTags(const std::set< TagID > &tags)
Form multiple residual vectors and each is associated with one tag.
void forceOutput()
Indicates that the next call to outputStep should be forced This is private, users should utilize FEP...
virtual void computeJacobianSys(libMesh::NonlinearImplicitSystem &sys, const NumericVector< libMesh::Number > &soln, libMesh::SparseMatrix< libMesh::Number > &jacobian)
Form a Jacobian matrix.
auto max(const L &left, const R &right)
std::shared_ptr< MultiApp > getMultiApp(const std::string &multi_app_name) const
Get a MultiApp object by name.
ExecuteMooseObjectWarehouse< UserObject > _all_user_objects
virtual void reinitElemNeighborAndLowerD(const Elem *elem, unsigned int side, const THREAD_ID tid) override
bool hasSolverVariable(const std::string &var_name) const
void preparePRefinement()
Prepare DofMap and Assembly classes with our p-refinement information.
Definition: SubProblem.C:1337
AuxGroup
Flag for AuxKernel related execution type.
Definition: MooseTypes.h:752
void removeSubstring(std::string &main, const std::string &sub)
Definition: MooseUtils.C:1201
virtual Elem * queryElemPtr(const dof_id_type i)
Definition: MooseMesh.C:3205
virtual void addMarker(const std::string &marker_name, const std::string &name, InputParameters &parameters)
void updateGhostedElems()
Updates the list of ghosted elements at the start of each time step for the nonlinear iteration patch...
unsigned int subspaceDim(const std::string &prefix) const
Dimension of the subspace spanned by vectors with a given prefix.
elem_info_iterator ownedElemInfoBegin()
Iterators to owned faceInfo objects.
Definition: MooseMesh.C:1578
void setCurrentlyComputingJacobian(const bool currently_computing_jacobian)
Set whether or not the problem is in the process of computing the Jacobian.
Definition: SubProblem.h:689
unsigned int variable_number(std::string_view var) const
A ReporterName that represents a VectorPostprocessor.
Definition: ReporterName.h:152
bool needsPreviousNewtonIteration() const
Check to see whether we need to compute the variable values of the previous Newton iterate...
virtual void addBoundaryCondition(const std::string &bc_name, const std::string &name, InputParameters &parameters)
bool _computing_nonlinear_residual
Whether the non-linear residual is being evaluated.
Definition: SubProblem.h:1104
virtual bool computingPreSMOResidual(const unsigned int nl_sys_num) const override
Returns true if the problem is in the process of computing it&#39;s initial residual. ...
void update()
Update the system (doing libMesh magic)
Definition: SystemBase.C:1243
This class is a container/interface for the objects involved in automatic generation of mortar spaces...
virtual Assembly & assembly(const THREAD_ID tid, const unsigned int sys_num) override
void createTagMatrices(CreateTaggedMatrixKey)
const bool _skip_nl_system_check
virtual void resetState()
Reset state of this object in preparation for the next evaluation.
void jacobianSetup()
Calls the jacobianSetup function for each of the output objects.
std::vector< MooseObjectParameterName > getControllableParameterNames(const MooseObjectParameterName &input) const
Return a vector of parameters names matching the supplied name.
virtual void addInitialCondition(const std::string &ic_name, const std::string &name, InputParameters &parameters)
virtual void addCachedResidualDirectly(NumericVector< libMesh::Number > &residual, const THREAD_ID tid)
Allows for all the residual contributions that are currently cached to be added directly into the vec...
bool hasActiveBoundaryObjects(THREAD_ID tid=0) const
virtual void jacobianSetup(THREAD_ID tid=0) const
const SubdomainID INVALID_BLOCK_ID
Definition: MooseTypes.C:20
ScalarInitialConditionWarehouse _scalar_ics
virtual void computeLinearSystemSys(libMesh::LinearImplicitSystem &sys, libMesh::SparseMatrix< libMesh::Number > &system_matrix, NumericVector< libMesh::Number > &rhs, const bool compute_gradients=true)
Assemble both the right hand side and the system matrix of a given linear system. ...
Nonlinear system to be solved.
bool getExodusFileRestart() const
Whether or not we need to use a separate Exodus reader to read the mesh BEFORE we create the mesh...
Definition: MooseApp.h:430
virtual void swapBackMaterialsFace(const THREAD_ID tid)
virtual void addDistribution(const std::string &type, const std::string &name, InputParameters &parameters)
The following functions will enable MOOSE to have the capability to import distributions.
virtual void advanceState()
Advance all of the state holding vectors / datastructures so that we can move to the next timestep...
A user object that runs over all the nodes and does an aggregation step to compute a single value...
ExecuteMooseObjectWarehouse< Transfer > _transfers
Normal Transfers.
void setAuxKernelParamsAndLog(const std::string &ak_name, const std::string &name, InputParameters &parameters, const std::string &base_name)
Set the subproblem and system parameters for auxiliary kernels and log their addition.
virtual void customSetup(const ExecFlagType &exec_type)
Definition: SubProblem.C:1196
virtual void checkBoundaryMatProps()
Checks boundary material properties integrity.
Definition: SubProblem.C:666
std::map< std::string, std::vector< dof_id_type > > _var_dof_map
Definition: SubProblem.h:674
Based class for output objects.
Definition: Output.h:43
const VectorPostprocessorValue & getVectorPostprocessorValueByName(const std::string &object_name, const std::string &vector_name, std::size_t t_index=0) const
Get a read-only reference to the vector value associated with the VectorPostprocessor.
virtual void addPredictor(const std::string &type, const std::string &name, InputParameters &parameters)
virtual Function & getFunction(const std::string &name, const THREAD_ID tid=0)
virtual void computeJacobianBlocks(std::vector< JacobianBlock *> &blocks, const unsigned int nl_sys_num)
Computes several Jacobian blocks simultaneously, summing their contributions into smaller preconditio...
virtual void copySolutionsBackwards()
const ConstBndNodeRange & getCurrentAlgebraicBndNodeRange()
bool _calculate_jacobian_in_uo
TODO: delete this later - it is a temporary hack for dealing with inter-system dependencies.
Definition: Attributes.h:294
virtual void reinitElemFaceRef(const Elem *elem, unsigned int side, Real tolerance, const std::vector< Point > *const pts, const std::vector< Real > *const weights=nullptr, const THREAD_ID tid=0) override
reinitialize FE objects on a given element on a given side at a given set of reference points and the...
virtual void setActiveScalarVariableCoupleableVectorTags(std::set< TagID > &vtags, const THREAD_ID tid)
Definition: SubProblem.C:410
virtual void prepareFaceShapes(unsigned int var, const THREAD_ID tid) override
virtual void addPostprocessor(const std::string &pp_name, const std::string &name, InputParameters &parameters)
virtual Real finalNonlinearResidual(const unsigned int nl_sys_num) const override
void addItem(const T &value)
Add an independent item to the set.
std::vector< std::shared_ptr< NonlinearSystemBase > > _nl
The nonlinear systems.
bool automaticScaling() const
Automatic scaling getter.
Definition: SubProblem.C:1163
virtual void computeUserObjects(const ExecFlagType &type, const Moose::AuxGroup &group)
Call compute methods on UserObjects.
virtual void setActiveElementalMooseVariables(const std::set< MooseVariableFEBase *> &moose_vars, const THREAD_ID tid) override
Set the MOOSE variables to be reinited on each element.
virtual void reinit_systems()
std::map< std::pair< BoundaryID, BoundaryID >, NearestNodeLocator * > _nearest_node_locators
std::vector< VariablePhiGradient > _grad_phi_zero
void mooseWarning(Args &&... args) const
void initialSetup(THREAD_ID tid)
Initial setup.
bool hasJacobian() const
Returns _has_jacobian.
void notifyWhenMeshDisplaces(MeshDisplacedInterface *mdi)
Register an object that derives from MeshDisplacedInterface to be notified when the displaced mesh ge...
void createTagSolutions()
Create extra tagged solution vectors.
std::vector< SolverSystemName > _solver_sys_names
The union of nonlinear and linear system names.
virtual void execute(const ExecFlagType &exec_type)
Convenience function for performing execution of MOOSE systems.
bool _verbose_restore
Whether or not to be verbose on solution restoration post a failed time step.
bool _previous_nl_solution_required
Indicates we need to save the previous NL iteration variable values.
processor_id_type n_processors() const
bool _trust_user_coupling_matrix
Whether to trust the user coupling matrix no matter what.
void setRestartRecoverFileBase(const std::string &file_base)
mutator for recover_base (set by RecoverBaseAction)
Definition: MooseApp.h:506
unsigned int number() const
const ConvergenceName & getSteadyStateConvergenceName() const
Gets the steady-state detection convergence object name.
void computeResidualAndJacobianTags(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags)
Form possibly multiple tag-associated vectors and matrices.
void handleException(const std::string &calling_method)
Handle exceptions.
virtual std::vector< VariableName > getVariableNames()
Returns a list of all the variables in the problem (both from the NL and Aux systems.
ReporterData _reporter_data
const std::string & name() const
Get the name of the class.
Definition: MooseBase.h:103
void uniformRefine()
uniformly refine the problem mesh(es).
virtual void computeResidualSys(libMesh::NonlinearImplicitSystem &sys, const NumericVector< libMesh::Number > &soln, NumericVector< libMesh::Number > &residual)
This function is called by Libmesh to form a residual.
const ReporterData & getReporterData() const
Provides const access the ReporterData object.
virtual const libMesh::CouplingMatrix & nonlocalCouplingMatrix(const unsigned i) const override
std::unique_ptr< libMesh::ConstElemRange > _current_algebraic_elem_range
FunctorMaterials compute functor material properties.
std::vector< std::shared_ptr< Transfer > > getTransfers(ExecFlagType type, Transfer::DIRECTION direction) const
Get Transfers by ExecFlagType and direction.
virtual void addConvergence(const std::string &type, const std::string &name, InputParameters &parameters)
Adds a Convergence object.
MultiPointMap & getPoints()
Returns a writeable reference to the _points container.
bool shouldPrintExecution(const THREAD_ID tid) const
Check whether the problem should output execution orders at this time.
const std::vector< std::shared_ptr< T > > & getActiveObjects(THREAD_ID tid=0) const
Retrieve complete vector to the active all/block/boundary restricted objects for a given thread...
const std::set< subdomain_id_type > & active_subdomains() const
bool havePRefinement() const
Query whether p-refinement has been requested at any point during the simulation. ...
Definition: SubProblem.h:1011
virtual Real l2_norm() const=0
bool getRecomputeMarkersFlag() const
Pull out the _recompute_markers_during_cycles flag previously set through the AdaptivityAction.
Definition: Adaptivity.h:125
const bool & _solve
Whether or not to actually solve the nonlinear system.
virtual const SystemBase & systemBaseSolver(const unsigned int sys_num) const override
Return the solver system object as a base class reference given the system number.
DenseVector< Real > getAllRealReporterValues() const
Get all real reporter values including postprocessor and vector postprocessor values into a dense vec...
Definition: ReporterData.C:81
ExecuteMooseObjectWarehouse< Transfer > _to_multi_app_transfers
Transfers executed just before MultiApps to transfer data to them.
std::set< SubdomainID > getActiveBlocks(THREAD_ID tid=0) const
Return a set of active SubdomainsIDs.
virtual void zero()=0
NonlinearSystemBase * _current_nl_sys
The current nonlinear system that we are solving.
MooseObjectWarehouse< Convergence > _convergences
convergence warehouse
Interface for notifications that the mesh has changed.
void sort(THREAD_ID tid=0, bool sort_all_objects=false)
By default, this method only sorts block and boundary-wise object storages that are used by the MOOSE...
virtual std::unique_ptr< Base > create()=0
void setCurrentNonlinearSystem(const unsigned int nl_sys_num)
std::shared_ptr< T > getActiveObject(const std::string &name, THREAD_ID tid=0) const
bool hasScalingOrRotationTransformation() const
Returns true if the app has scaling and/or rotation transformation.
const std::vector< std::shared_ptr< T > > & getObjects(THREAD_ID tid=0) const
Retrieve complete vector to the all/block/boundary restricted objects for a given thread...
virtual const NumericVector< Number > *const & currentSolution() const override final
The solution vector that is currently being operated on.
Definition: SolverSystem.h:117
dof_id_type id() const
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)
Base class for convergence criteria.
Definition: Convergence.h:21
MeshBase & getMesh()
Accessor for the underlying libMesh Mesh object.
Definition: MooseMesh.C:3528
void min(const T &r, T &o, Request &req) const
virtual void reinitElem(const Elem *elem, const THREAD_ID tid) override
const T & getReporterValue(const ReporterName &reporter_name, const MooseObject &consumer, const ReporterMode &mode, const std::size_t time_index=0) const
Method for returning read only references to Reporter values.
Definition: ReporterData.h:388
virtual Convergence & getConvergence(const std::string &name, const THREAD_ID tid=0) const
Gets a Convergence object.
TheWarehouse & theWarehouse() const
void createTagVectors()
Create extra tagged vectors and matrices.
virtual void createQRules(libMesh::QuadratureType type, libMesh::Order order, libMesh::Order volume_order=libMesh::INVALID_ORDER, libMesh::Order face_order=libMesh::INVALID_ORDER, SubdomainID block=Moose::ANY_BLOCK_ID, bool allow_negative_qweights=true)
unsigned int n_vars
void reinitMaterialsNeighbor(SubdomainID blk_id, const THREAD_ID tid, bool swap_stateful=true, const std::deque< MaterialBase *> *reinit_mats=nullptr)
reinit materials on the neighboring element face
void setMultiAppFixedPointConvergenceName(const ConvergenceName &convergence_name)
Sets the MultiApp fixed point convergence object name if there is one.
void checkUserObjects()
Moose::CouplingType _coupling
Type of variable coupling.
Every object that can be built by the factory should be derived from this class.
Definition: MooseObject.h:28
Real l2_norm() const
virtual bool shouldUpdateSolution()
Check to see whether the problem should update the solution.
virtual void setActiveFEVariableCoupleableVectorTags(std::set< TagID > &vtags, const THREAD_ID tid)
Definition: SubProblem.C:370
void extraSendList(std::vector< dof_id_type > &send_list, void *context)
///< Type of coordinate system
Definition: SystemBase.C:40
void addObjects(std::shared_ptr< MaterialBase > block, std::shared_ptr< MaterialBase > neighbor, std::shared_ptr< MaterialBase > face, THREAD_ID tid=0)
A special method unique to this class for adding Block, Neighbor, and Face material objects...
const ConvergenceName & getMultiAppFixedPointConvergenceName() const
Gets the MultiApp fixed point convergence object name.
std::vector< std::string > getAllRealReporterFullNames() const
Get full names of all real reporter values Note: For a postprocessor, the full name is the postproces...
Definition: ReporterData.C:106
virtual void clearActiveScalarVariableCoupleableVectorTags(const THREAD_ID tid)
Definition: SubProblem.C:420
Real getTimeFromStateArg(const Moose::StateArg &state) const
Returns the time associated with the requested state.
virtual std::string solverTypeString(unsigned int solver_sys_num=0)
Return solver type as a human readable string.
const ExecFlagType EXEC_TIMESTEP_BEGIN
Definition: Moose.C:37
std::shared_ptr< T > getObject(const std::string &name, THREAD_ID tid=0) const
void executeSamplers(const ExecFlagType &exec_type)
Performs setup and execute calls for Sampler objects.
unsigned int which_neighbor_am_i(const Elem *e) const
virtual void computeJacobianInternal(const NumericVector< libMesh::Number > &soln, libMesh::SparseMatrix< libMesh::Number > &jacobian, const std::set< TagID > &tags)
Form a Jacobian matrix for multiple tags.
bool _safe_access_tagged_vectors
Is it safe to retrieve data from tagged vectors.
Definition: SubProblem.h:1113
virtual void computeJacobian(const NumericVector< libMesh::Number > &soln, libMesh::SparseMatrix< libMesh::Number > &jacobian, const unsigned int nl_sys_num)
Form a Jacobian matrix with the default tag (system).
const std::unordered_map< std::pair< BoundaryID, BoundaryID >, std::unique_ptr< AutomaticMortarGeneration > > & getMortarInterfaces(bool on_displaced) const
void reinitMaterialsNeighborOnBoundary(const BoundaryID boundary_id, const SubdomainID blk_id, const THREAD_ID tid, const bool swap_stateful=true, const std::deque< MaterialBase *> *const reinit_mats=nullptr)
reinit materials on neighbor element (usually faces) on a boundary (internal or external) This specif...
void addOutput(const std::string &, const std::string &, InputParameters &)
Adds an Output object.
SolutionIterationType iteration_type
The solution iteration type, e.g. time or nonlinear.
boundary_id_type BoundaryID
void boundaryIntegrityCheckError(const MooseObject &object, const std::set< MooseVariableFieldBase *> &variables, const BoundaryName &boundary_name)
Compose boundary restricted error message for the provided object, variables, and boundary_name if th...
const bool _allow_ics_during_restart
bool constJacobian() const
Returns _const_jacobian (whether a MOOSE object has specified that the Jacobian is the same as the pr...
virtual void clearActiveFEVariableCoupleableMatrixTags(const THREAD_ID tid) override
void computeJacobianTags(const std::set< TagID > &tags)
Computes multiple (tag associated) Jacobian matricese.
SolutionInvalidity & solutionInvalidity()
Get the SolutionInvalidity for this app.
Definition: MooseApp.h:179
std::vector< MeshChangedInterface * > _notify_when_mesh_changes
Objects to be notified when the mesh changes.
virtual void timestepSetup(THREAD_ID tid=0) const
void checkNonlocalCoupling()
VarKindType
Framework-wide stuff.
Definition: MooseTypes.h:763
void addDefaultSteadyStateConvergence(const InputParameters &params)
Adds the default steady-state detection Convergence.
NonlinearSystemBase & currentNonlinearSystem()
SimpleRange< IndexType > as_range(const std::pair< IndexType, IndexType > &p)
Jacobian-Free Newton Krylov.
Definition: MooseTypes.h:894
void groupUserObjects(TheWarehouse &w, AuxiliarySystem &aux, const ExecFlagEnum &execute_flags, const std::vector< T *> &objs, const std::set< std::string > &ic_deps)
void checkDisplacementOrders()
Verify that SECOND order mesh uses SECOND order displacements.
virtual void addFunction(const std::string &type, const std::string &name, InputParameters &parameters)
Real PostprocessorValue
various MOOSE typedefs
Definition: MooseTypes.h:230
void uniformly_coarsen(unsigned int n=1)
virtual void addJacobianNeighbor(const THREAD_ID tid) override
virtual TagID addMatrixTag(TagName tag_name)
Create a Tag.
Definition: SubProblem.C:312
virtual libMesh::EquationSystems & es() override
std::vector< std::unordered_map< SubdomainID, bool > > _block_mat_side_cache
Cache for calculating materials on side.
std::shared_ptr< AuxiliarySystem > _aux
The auxiliary system.
void setRestart(bool value)
Sets the restart/recover flags.
Definition: MooseApp.C:2995
AttribBoundaries tracks all boundary IDs associated with an object.
Definition: Attributes.h:188
void setValue(unsigned int i, Number value)
Set the nodal value for this variable (to keep everything up to date.
virtual void reinitElemFaceRef(const Elem *elem, unsigned int side, Real tolerance, const std::vector< Point > *const pts, const std::vector< Real > *const weights=nullptr, const THREAD_ID tid=0)
reinitialize FE objects on a given element on a given side at a given set of reference points and the...
Definition: SubProblem.C:883
virtual void addVectorPostprocessor(const std::string &pp_name, const std::string &name, InputParameters &parameters)
MooseMesh wraps a libMesh::Mesh object and enhances its capabilities by caching additional data and s...
Definition: MooseMesh.h:92
virtual bool converged(const unsigned int sys_num)
Eventually we want to convert this virtual over to taking a solver system number argument.
Definition: SubProblem.h:113
virtual unsigned int currentNlSysNum() const override
virtual void computeIndicators()
virtual MooseVariableScalar & getScalarVariable(const THREAD_ID tid, const std::string &var_name) override
Returns the scalar variable reference from whichever system contains it.
const bool _boundary_restricted_node_integrity_check
whether to perform checking of boundary restricted nodal object variable dependencies, e.g.
virtual void setActiveScalarVariableCoupleableVectorTags(std::set< TagID > &vtags, const THREAD_ID tid) override
MooseMesh & _mesh
virtual void updateActive(THREAD_ID tid=0)
Update the active status of Kernels.
virtual bool updateMeshXFEM()
Update the mesh due to changing XFEM cuts.
virtual const SystemBase & systemBaseNonlinear(const unsigned int sys_num) const override
Return the nonlinear system object as a base class reference given the system number.
std::vector< MortarUserObject * > getMortarUserObjects(BoundaryID primary_boundary_id, BoundaryID secondary_boundary_id, bool displaced, const std::vector< MortarUserObject *> &mortar_uo_superset)
Helper for getting mortar objects corresponding to primary boundary ID, secondary boundary ID...
virtual void restoreSolutions()
virtual bool hasConvergence(const std::string &name, const THREAD_ID tid=0) const
Returns true if the problem has a Convergence object of the given name.
void markFamilyPRefinement(const InputParameters &params)
Mark a variable family for either disabling or enabling p-refinement with valid parameters of a varia...
Definition: SubProblem.C:1372
virtual const std::vector< dof_id_type > & dofIndices() const
Get local DoF indices.
void addAnyRedistributers()
void mooseDeprecated(Args &&... args) const
const std::string & type() const
Get the type of this class.
Definition: MooseBase.h:93
bool hasPostprocessorValueByName(const PostprocessorName &name) const
Whether or not a Postprocessor value exists by a given name.
virtual void checkBlockMatProps()
Checks block material properties integrity.
Definition: SubProblem.C:624
void restoreFromInitialBackup(const bool for_restart)
Restores from a "initial" backup, that is, one set in _initial_backup.
Definition: MooseApp.C:1992
void setAxisymmetricCoordAxis(const MooseEnum &rz_coord_axis)
void initialSetup() override
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition: MooseEnum.h:33
void reinit()
Completely redo all geometric search objects.
Adaptivity _adaptivity
std::vector< VectorTag > getVectorTags(const std::set< TagID > &tag_ids) const
Definition: SubProblem.C:173
bool allowInvalidSolution() const
Whether to accept / allow an invalid solution.
bool needInternalNeighborSideMaterial(SubdomainID subdomain_id, const THREAD_ID tid)
virtual const SystemBase & systemBaseAuxiliary() const override
Return the auxiliary system object as a base class reference.
Moose::SolveType _type
Definition: SolverParams.h:19
void setLinearConvergenceNames(const std::vector< ConvergenceName > &convergence_names)
Sets the linear convergence object name(s) if there is one.
void checkUserObjectJacobianRequirement(THREAD_ID tid)
MooseVariableFieldBase & getActualFieldVariable(const THREAD_ID tid, const std::string &var_name) override
Returns the variable reference for requested MooseVariableField which may be in any system...
void finalize(const std::string &object_name)
Helper function for performing post calculation actions via the ReporterContext objects.
Definition: ReporterData.C:48
void addObject(std::shared_ptr< InitialConditionBase > object, THREAD_ID tid, bool recurse=true)
Add object to the warehouse.
virtual void disassociateVectorFromTag(NumericVector< Number > &vec, TagID tag)
Disassociate a given vector from a given tag.
virtual void computeNullSpace(libMesh::NonlinearImplicitSystem &sys, std::vector< NumericVector< libMesh::Number > *> &sp)
virtual void addTimeIntegrator(const std::string &type, const std::string &name, InputParameters &parameters)
LinearSystem * _current_linear_sys
The current linear system that we are solving.
virtual void cacheResidual(const THREAD_ID tid) override
virtual void computeResidualType(const NumericVector< libMesh::Number > &soln, NumericVector< libMesh::Number > &residual, TagID tag)
Form a residual vector for a given tag and "residual" tag.
const bool _force_restart
void checkCoordinateSystems()
Performs a sanity check for every element in the mesh.
Definition: MooseMesh.C:4387
QueryCache clone() const
clone creates and returns an independent copy of the query in its current state.
Definition: TheWarehouse.h:292
void forceOutput()
Indicates that the next call to outputStep should be forced.
const VectorPostprocessor & getVectorPostprocessorObjectByName(const std::string &object_name, const THREAD_ID tid=0) const
Return the VPP object given the name.
std::vector< VariablePhiSecond > _second_phi_zero
StoredRange< std::vector< GeneralUserObject * >::iterator, GeneralUserObject * > GeneralUserObjectRange
bool _started_initial_setup
At or beyond initialSteup stage.
std::map< std::string, std::unique_ptr< RandomData > > _random_data_objects
A map of objects that consume random numbers.
virtual bool vectorTagExists(const TagID tag_id) const
Check to see if a particular Tag exists.
Definition: SubProblem.h:201
std::unique_ptr< ConstBndNodeRange > _current_algebraic_bnd_node_range
virtual void addResidual(const THREAD_ID tid) override
void checkParams(const std::string &parsing_syntax)
This function checks parameters stored in the object to make sure they are in the correct state as th...
virtual void addResidualNeighbor(const THREAD_ID tid) override
virtual void reinitNeighborFaceRef(const Elem *neighbor_elem, unsigned int neighbor_side, Real tolerance, const std::vector< Point > *const pts, const std::vector< Real > *const weights=nullptr, const THREAD_ID tid=0) override
reinitialize FE objects on a given neighbor element on a given side at a given set of reference point...
void setCoordSystem(const std::vector< SubdomainName > &blocks, const MultiMooseEnum &coord_sys)
Set the coordinate system for the provided blocks to coord_sys.
Definition: MooseMesh.C:4161
Base class for all Postprocessors.
Definition: Postprocessor.h:23
libMesh::ExodusII_IO * getExReaderForRestart() const
Get the Exodus reader to restart variables from an Exodus mesh file.
Definition: MooseApp.h:443
void needSolutionState(unsigned int oldest_needed, Moose::SolutionIterationType iteration_type)
Declare that we need up to old (1) or older (2) solution states for a given type of iteration...
void clearPoints()
Remove all of the current points and elements.
std::string typeAndName() const
Get the class&#39;s combined type and name; useful in error handling.
Definition: MooseBase.C:57
MooseApp & _app
The MOOSE application this is associated with.
Definition: MooseBase.h:357
virtual void clearActiveFEVariableCoupleableVectorTags(const THREAD_ID tid) override
void maxloc(T &r, unsigned int &max_id) const
bool isValueSet(const std::string &value) const
Methods for seeing if a value is set in the MultiMooseEnum.
void setCouplingMatrix(std::unique_ptr< libMesh::CouplingMatrix > cm, const unsigned int nl_sys_num)
Set custom coupling matrix.
unsigned int number() const
Gets the number of this system.
Definition: SystemBase.C:1157
virtual void addDefaultNonlinearConvergence(const InputParameters &params)
Adds the default nonlinear Convergence associated with the problem.
virtual void solve() override
Solve the system (using libMesh magic)
Definition: LinearSystem.C:312
void setNonlinearConvergenceNames(const std::vector< ConvergenceName > &convergence_names)
Sets the nonlinear convergence object name(s) if there is one.
auto norm(const T &a) -> decltype(std::abs(a))
unsigned int uniformRefineLevel() const
Returns the level of uniform refinement requested (zero if AMR is disabled).
Definition: MooseMesh.C:3296
const ExecFlagType EXEC_LINEAR
Definition: Moose.C:31
TODO: delete this later - it is a temporary hack for dealing with inter-system dependencies.
Definition: Attributes.h:344
virtual bool solverSystemConverged(const unsigned int solver_sys_num) override
std::string stringify(const T &t)
conversion to string
Definition: Conversion.h:64
std::string _exception_message
The error message to go with an exception.
const std::set< SubdomainID > & boundaryLowerDBlocks() const
Definition: MooseMesh.h:1425
std::vector< SubdomainName > getSubdomainNames(const std::vector< SubdomainID > &subdomain_ids) const
Get the associated subdomainNames for the subdomain ids that are passed in.
Definition: MooseMesh.C:1819
virtual void checkProblemIntegrity()
Method called to perform a series of sanity checks before a simulation is run.
void setReporterValue(const ReporterName &reporter_name, const T &value, const std::size_t time_index=0)
Method for setting Reporter values that already exist.
Definition: ReporterData.h:481
Class for storing and utilizing output objects.
AuxiliarySystem & getAuxiliarySystem()
virtual void initialSetup(THREAD_ID tid=0) const
Convenience methods for calling object setup methods.
virtual void updateGeomSearch(GeometricSearchData::GeometricSearchType type=GeometricSearchData::ALL) override
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.
Definition: PetscSupport.C:230
MooseObjectWarehouse< MeshDivision > _mesh_divisions
Warehouse to store mesh divisions NOTE: this could probably be moved to the MooseMesh instead of the ...
virtual void addConstraint(const std::string &c_name, const std::string &name, InputParameters &parameters)
void buildRefinementAndCoarseningMaps(Assembly *assembly)
Create the refinement and coarsening maps necessary for projection of stateful material properties wh...
Definition: MooseMesh.C:2512
MooseObjectWarehouse< Indicator > _indicators
virtual void addMultiApp(const std::string &multi_app_name, const std::string &name, InputParameters &parameters)
Add a MultiApp to the problem.
virtual void prepareAssembly(const THREAD_ID tid) override
bool haveADObjects() const
Method for reading wehther we have any ad objects.
Definition: SubProblem.h:771
unsigned int systemNumForVariable(const VariableName &variable_name) const
bool _checking_uo_aux_state
Flag used to indicate whether we are doing the uo/aux state check in execute.
const PostprocessorValue & getPostprocessorValueByName(const PostprocessorName &name, std::size_t t_index=0) const
Get a read-only reference to the value associated with a Postprocessor that exists.
MeshBase::element_iterator activeLocalElementsBegin()
Calls active_local_nodes_begin/end() on the underlying libMesh mesh object.
Definition: MooseMesh.C:3131
InitialConditions are objects that set the initial value of variables.
Base class for user objects executed on all element sides internal to one or more blocks...
virtual void clearActiveScalarVariableCoupleableMatrixTags(const THREAD_ID tid)
Definition: SubProblem.C:426
virtual std::map< TagName, TagID > & getMatrixTags()
Return all matrix tags in the system, where a tag is represented by a map from name to ID...
Definition: SubProblem.h:253
virtual void initNullSpaceVectors(const InputParameters &parameters, std::vector< std::shared_ptr< NonlinearSystemBase >> &nl)
virtual bool hasVariable(const std::string &var_name) const
Query a system for a variable.
Definition: SystemBase.C:851
Executioner * getExecutioner() const
Retrieve the Executioner for this App.
Definition: MooseApp.C:2206
virtual void setCurrentSubdomainID(const Elem *elem, const THREAD_ID tid) override
MaterialData & getMaterialData(Moose::MaterialDataType type, const THREAD_ID tid=0, const MooseObject *object=nullptr) const
void broadcast(T &data, const unsigned int root_id=0, const bool identical_sizes=false) const
virtual void clearDiracInfo() override
Gets called before Dirac Kernels are asked to add the points they are supposed to be evaluated in...
virtual void addIndicator(const std::string &indicator_name, const std::string &name, InputParameters &parameters)
virtual void reinitNodesNeighbor(const std::vector< dof_id_type > &nodes, const THREAD_ID tid) override
bool duplicateVariableCheck(const std::string &var_name, const libMesh::FEType &type, bool is_aux, const std::set< SubdomainID > *const active_subdomains)
Helper to check for duplicate variable names across systems or within a single system.
virtual void solve() override=0
Solve the system (using libMesh magic)
GeometricSearchType
Used to select groups of geometric search objects to update.
void backupMultiApps(ExecFlagType type)
Backup the MultiApps associated with the ExecFlagType.
virtual ~FEProblemBase()
A ReporterName that represents a Postprocessor.
Definition: ReporterName.h:143
virtual void addVariable(const std::string &var_type, const std::string &var_name, InputParameters &params)
Canonical method for adding a non-linear variable.
bool doingPRefinement() const
Definition: SubProblem.C:1366
ExecuteMooseObjectWarehouse< MultiApp > _multi_apps
MultiApp Warehouse.
virtual void jacobianSetup(THREAD_ID tid=0) const
void updateBoundaryMatPropDependency(std::unordered_set< unsigned int > &needed_mat_props, THREAD_ID tid=0) const
void uniformRefineWithProjection()
Performs uniform refinement on the meshes in the current object.
Definition: Adaptivity.C:301
TagID residualVectorTag() const override
std::vector< std::vector< std::unique_ptr< Assembly > > > _assembly
The Assembly objects.
virtual void addDisplacedProblem(std::shared_ptr< DisplacedProblem > displaced_problem)
const std::map< BoundaryID, std::vector< std::shared_ptr< T > > > & getActiveBoundaryObjects(THREAD_ID tid=0) const
void computeResidual(libMesh::NonlinearImplicitSystem &sys, const NumericVector< libMesh::Number > &soln, NumericVector< libMesh::Number > &residual)
This function is called by Libmesh to form a residual.
virtual void cacheJacobianNeighbor(const THREAD_ID tid)
Definition: SubProblem.C:1325
MONOMIAL
void setResidualObjectParamsAndLog(const std::string &ro_name, const std::string &name, InputParameters &parameters, const unsigned int nl_sys_num, const std::string &base_name, bool &reinit_displaced)
Set the subproblem and system parameters for residual objects and log their addition.
void setVectorPostprocessorValueByName(const std::string &object_name, const std::string &vector_name, const VectorPostprocessorValue &value, std::size_t t_index=0)
Set the value of a VectorPostprocessor vector.
virtual MooseVariable & getStandardVariable(const THREAD_ID tid, const std::string &var_name) override
Returns the variable reference for requested MooseVariable which may be in any system.
virtual void initialSetup(THREAD_ID tid=0) const
Convenience methods for calling object setup methods that handle the extra neighbor and face objects...
void setCoordSystem(const std::vector< SubdomainName > &blocks, const MultiMooseEnum &coord_sys)
virtual void swapBackMaterialsNeighbor(const THREAD_ID tid)
virtual void addLinearFVKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
void residualSetup()
Calls the residualSetup function for each of the output objects.
virtual NonlinearSystem & getNonlinearSystem(const unsigned int sys_num)
void solveSetup()
Calls the timestepSetup function for each of the output objects.
virtual bool reinitDirac(const Elem *elem, const THREAD_ID tid) override
Returns true if the Problem has Dirac kernels it needs to compute on elem.
MooseAppCoordTransform & coordTransform()
Definition: MooseMesh.h:1931
bool have_parameter(std::string_view name) const
A wrapper around the Parameters base class method.
virtual void cacheResidual(const THREAD_ID tid)
Definition: SubProblem.C:1296
virtual void timestepSetup()
Definition: SubProblem.C:1186
libMesh::Order order() const
Get the order of this variable Note: Order enum can be implicitly converted to unsigned int...
const ExecFlagType EXEC_PRE_DISPLACE
Definition: Moose.C:52
virtual const Elem * elem_ptr(const dof_id_type i) const=0
const std::vector< NonlinearSystemName > _nl_sys_names
The nonlinear system names.
const ExecFlagType EXEC_POSTCHECK
Definition: Moose.C:35
query_obj query
PetscErrorCode PetscInt const PetscInt fields[]
const ExecFlagType EXEC_NONLINEAR
Definition: Moose.C:33
bool isParamSetByUser(const std::string &name) const
Method returns true if the parameter was set by the user.
std::vector< Real > VectorPostprocessorValue
Definition: MooseTypes.h:231
virtual void updateMortarMesh()
void copyValuesBack()
At the end of a timestep this method is called to copy the values back in time in preparation for the...
Definition: ReporterData.C:17
const std::vector< const Elem * > & coarsenedElementChildren(const Elem *elem) const
Get the newly removed children element ids for an element that was just coarsened.
Definition: MooseMesh.C:970
void restore(const std::filesystem::path &folder_base, const bool for_restart)
Restore an application from file.
Definition: MooseApp.C:1957
void addDefaultMultiAppFixedPointConvergence(const InputParameters &params)
Adds the default fixed point Convergence associated with the problem.
std::set< TagID > _fe_matrix_tags
Moose::Kokkos::MaterialPropertyStorage & _kokkos_material_props
virtual NumericVector< Number > & RHS()=0
virtual void addAuxArrayVariable(const std::string &var_name, const libMesh::FEType &type, unsigned int components, const std::set< SubdomainID > *const active_subdomains=NULL)
const ExecuteMooseObjectWarehouse< Transfer > & getMultiAppTransferWarehouse(Transfer::DIRECTION direction) const
Return the complete warehouse for MultiAppTransfer object for the given direction.
virtual const SystemBase & getSystemBase(const unsigned int sys_num) const
Get constant reference to a system in this problem.
const Elem * neighbor_ptr(unsigned int i) const
virtual void reinitLowerDElem(const Elem *lower_d_elem, const THREAD_ID tid, const std::vector< Point > *const pts=nullptr, const std::vector< Real > *const weights=nullptr) override
Provides a way for users to bail out of the current solve.
virtual void addReporter(const std::string &type, const std::string &name, InputParameters &parameters)
Add a Reporter object to the simulation.
virtual void swapBackMaterials(const THREAD_ID tid)
std::vector< VariablePhiValue > _phi_zero
InitialConditionWarehouse _ics
std::vector< unsigned char > _has_active_material_properties
Whether there are active material properties on each thread.
std::string varName(const std::string &var_param_name, const std::string &moose_object_with_var_param_name) const
Determine the actual variable name from the given variable parameter name.
MaterialWarehouse _discrete_materials
bool _reinit_displaced_face
Whether to call DisplacedProblem::reinitElemFace when this->reinitElemFace is called.
void updateBlockMatPropDependency(SubdomainID id, std::unordered_set< unsigned int > &needed_mat_props, THREAD_ID tid=0) const
void setSinglePetscOption(const std::string &name, const std::string &value="", FEProblemBase *const problem=nullptr)
A wrapper function for dealing with different versions of PetscOptionsSetValue.
virtual void initialSetup()
Definition: SubProblem.C:1220
NumericVector< Number > & getRightHandSideVector()
Fetching the right hand side vector from the libmesh system.
Definition: LinearSystem.h:119
std::unique_ptr< MortarInterfaceWarehouse > _mortar_data
virtual void addDGKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
virtual void setCurrentBoundaryID(BoundaryID bid, const THREAD_ID tid) override
sets the current boundary ID in assembly
SolverSystem * _current_solver_sys
The current solver system.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
virtual std::shared_ptr< const DisplacedProblem > getDisplacedProblem() const
virtual bool contract()=0
std::optional< std::vector< ConvergenceName > > _nonlinear_convergence_names
Nonlinear system(s) convergence name(s)
Generic class for solving transient nonlinear problems.
Definition: SubProblem.h:78
virtual void preProblemInit()
Perform initializations during executing actions right before init_problem task.
Definition: Executioner.h:57
void updateActiveSemiLocalNodeRange(std::set< dof_id_type > &ghosted_elems)
Clears the "semi-local" node list and rebuilds it.
Definition: MooseMesh.C:978
subdomain_id_type subdomain_id() const
virtual void stopSolve(const ExecFlagType &exec_flag, const std::set< TagID > &vector_tags_to_close)=0
Quit the current solve as soon as possible.
const InputParameters * getCommonParameters() const
Get a reference to the common output parameters.
TagID timeVectorTag() const override
Ideally, we should not need this API.
std::map< SubdomainID, std::set< MaterialPropertyName > > _zero_block_material_props
Set of properties returned as zero properties.
Definition: SubProblem.h:1060
Class for containing MooseEnum item information.
Definition: MooseEnumItem.h:18
unsigned int solverSysNum(const SolverSystemName &solver_sys_name) const override
std::shared_ptr< MaterialBase > getMaterial(std::string name, Moose::MaterialDataType type, const THREAD_ID tid=0, bool no_warn=false)
Return a pointer to a MaterialBase object.
virtual void swap(NumericVector< T > &v)
bool hasActiveObject(const std::string &name, THREAD_ID tid=0) const
Convenience functions for checking/getting specific objects.
std::vector< VariableGradient > _grad_zero
bool hasActiveObjects(THREAD_ID tid=0) const
void clearCurrentJacobianMatrixTags()
Clear the current Jacobian matrix tag data structure ...
CTSub CT_OPERATOR_BINARY CTMul CTCompareLess CTCompareGreater CTCompareEqual _arg template * sqrt(_arg)) *_arg.template D< dtag >()) CT_SIMPLE_UNARY_FUNCTION(tanh
virtual void subdomainSetup(SubdomainID subdomain, const THREAD_ID tid)
virtual void restoreOldSolutions()
Restore old solutions from the backup vectors and deallocate them.
unsigned int getInitialSteps() const
Pull out the number of initial steps previously set by calling init()
Definition: Adaptivity.h:98
void max(const T &r, T &o, Request &req) const
void reinitMaterials(SubdomainID blk_id, const THREAD_ID tid, bool swap_stateful=true)
virtual unsigned short dim() const=0
const AutomaticMortarGeneration & getMortarInterface(const std::pair< BoundaryID, BoundaryID > &primary_secondary_boundary_pair, const std::pair< SubdomainID, SubdomainID > &primary_secondary_subdomain_pair, bool on_displaced) const
Return the undisplaced or displaced mortar generation object associated with the provided boundaries ...
bool acceptInvalidSolution() const
Whether or not to accept the solution based on its invalidity.
void setLoadAllVectors(const bool load_all_vectors)
Sets whether or not all vectors are to be loaded.
Class for threaded computation of UserObjects.
const bool _restore_original_nonzero_pattern
Whether we should restore the original nonzero pattern for every Jacobian evaluation.
void setRandomDataPointer(RandomData *random_data)
Base class for all MultiAppTransfer objects.
virtual libMesh::SparseMatrix< Number > & getMatrix(TagID tag)
Get a raw SparseMatrix.
Definition: SystemBase.C:1024
void execMultiAppTransfers(ExecFlagType type, Transfer::DIRECTION direction)
Execute MultiAppTransfers associated with execution flag and direction.
T & set(const std::string &)
Wrapper class that owns a libMesh EquationSystem and adds advanced restart capability to it...
void restoreMultiApps(ExecFlagType type, bool force=false)
Restore the MultiApps associated with the ExecFlagType.
virtual void addLinearFVBC(const std::string &fv_bc_name, const std::string &name, InputParameters &parameters)
virtual bool is_vertex(const unsigned int i) const=0
void subdomainSetup()
Calls the subdomainSetup function for each of the output objects.
const std::string & getName(const unsigned int id) const
const std::vector< dof_id_type > & allDofIndices() const
Get all global dofindices for the variable.
const std::vector< std::string > & get_elem_var_names()
void addMaterialPropertyStorage(MaterialPropertyStorage &mat_props)
Pushes the given pair ( mat_data , mat_props ) onto our list of _materials data to redistribute each ...
SparseMatrix< Number > * matrix
void customSetup(const ExecFlagType &exec_type) override
void setRestartFile(const std::string &file_name)
Communicate to the Resurector the name of the restart filer.
void setCurrentLinearSystem(unsigned int sys_num)
Set the current linear system pointer.
void initNonlocalCoupling()
Create pair of variables requiring nonlocal jacobian contributions.
Definition: Assembly.C:2649
void executeControls(const ExecFlagType &exec_type)
Performs setup and execute calls for Control objects.
virtual std::vector< std::shared_ptr< UserObject > > addUserObject(const std::string &user_object_name, const std::string &name, InputParameters &parameters)
Query query()
query creates and returns an initialized a query object for querying objects from the warehouse...
Definition: TheWarehouse.h:466
void allowOutput(bool state)
Ability to enable/disable output calls This is private, users should utilize FEProblemBase::allowOutp...
bool hasStartTime() const
Definition: MooseApp.h:295
virtual void onTimestepBegin() override
virtual void computeBounds(libMesh::NonlinearImplicitSystem &sys, NumericVector< libMesh::Number > &lower, NumericVector< libMesh::Number > &upper)
Nonlinear system to be solved.
void initKokkos()
Construct Kokkos assembly and systems and allocate Kokkos material property storages.
virtual void computePostCheck(libMesh::NonlinearImplicitSystem &sys, const NumericVector< libMesh::Number > &old_soln, NumericVector< libMesh::Number > &search_direction, NumericVector< libMesh::Number > &new_soln, bool &changed_search_direction, bool &changed_new_soln)
void checkDuplicatePostprocessorVariableNames()
void addConsumer(Moose::MaterialDataType type, const MooseObject *object)
Add object as the consumer of storage of type type.
void setAxisymmetricCoordAxis(const MooseEnum &rz_coord_axis)
For axisymmetric simulations, set the symmetry coordinate axis.
Definition: MooseMesh.C:4293
void addOutput(std::shared_ptr< Output > output)
Adds an existing output object to the warehouse.
void computeResidualAndJacobian(const NumericVector< libMesh::Number > &soln, NumericVector< libMesh::Number > &residual, libMesh::SparseMatrix< libMesh::Number > &jacobian)
Form a residual and Jacobian with default tags.
std::vector< std::pair< MooseVariableFEBase *, MooseVariableFEBase * > > & nonlocalCouplingEntries(const THREAD_ID tid, const unsigned int nl_sys_num)
static void selectMatrixTagsFromSystem(const SystemBase &system, const std::map< TagName, TagID > &input_matrix_tags, std::set< TagID > &selected_tags)
Select the matrix tags which belong to a specific system.
Definition: SubProblem.C:301
std::vector< VariableValue > _scalar_zero
virtual Real computeResidualL2Norm()
Computes the residual using whatever is sitting in the current solution vector then returns the L2 no...
void update(GeometricSearchType type=ALL)
Update all of the search objects.
const std::vector< LinearSystemName > _linear_sys_names
The linear system names.
void incrementMultiAppTStep(ExecFlagType type)
Advance the MultiApps t_step (incrementStepOrReject) associated with the ExecFlagType.
Class for scalar variables (they are different).
IntRange< T > make_range(T beg, T end)
void computeLinearSystemTags(const NumericVector< libMesh::Number > &soln, const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags, const bool compute_gradients=true)
Assemble the current linear system given a set of vector and matrix tags.
void bumpVolumeQRuleOrder(libMesh::Order order, SubdomainID block)
Increases the element/volume quadrature order for the specified mesh block if and only if the current...
const bool _material_dependency_check
Determines whether a check to verify material dependencies on every subdomain.
std::vector< std::vector< const MooseVariableFEBase * > > _uo_jacobian_moose_vars
virtual MooseMesh & mesh() override
NonlocalKernel is used for solving integral terms in integro-differential equations.
virtual void subdomainSetup(THREAD_ID tid=0) const
std::vector< VariableValue > _zero
CouplingType
Definition: MooseTypes.h:779
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...
Definition: MooseBase.h:271
const ExecFlagType EXEC_SAME_AS_MULTIAPP
Definition: Moose.C:53
unsigned int linearSysNum(const LinearSystemName &linear_sys_name) const override
LinearSystem & currentLinearSystem()
Get a non-constant reference to the current linear system.
virtual void updateActive(THREAD_ID tid=0) override
Update the active status of Kernels.
std::set< TagID > _fe_vector_tags
const std::set< const MooseObject * > & getConsumers(Moose::MaterialDataType type) const
const std::set< const MooseObject * > & getMaterialPropertyStorageConsumers(Moose::MaterialDataType type) const
void addObjectParamsHelper(InputParameters &params, const std::string &object_name, const std::string &var_param_name="variable")
Helper for setting the "_subproblem" and "_sys" parameters in addObject() and in addUserObject().
virtual unsigned int size() const override final
SolverParams & solverParams(unsigned int solver_sys_num=0)
Get the solver parameters.
virtual void saveOldSolutions()
Allocate vectors and save old solutions into them.
std::unique_ptr< NumericVector< Number > > current_local_solution
ADRealVectorValue ADRealGradient
Definition: MooseTypes.h:407
virtual void setActiveFEVariableCoupleableMatrixTags(std::set< TagID > &mtags, const THREAD_ID tid)
Definition: SubProblem.C:364
void mooseConsole()
Send current output buffer to Console output objects.
std::set< std::string > getDependObjects() const
Get a list of dependent UserObjects for this exec type.
virtual void computeTransposeNullSpace(libMesh::NonlinearImplicitSystem &sys, std::vector< NumericVector< libMesh::Number > *> &sp)
bool hasPostprocessor(const std::string &name) const
Deprecated.
virtual bool updateSolution(NumericVector< libMesh::Number > &vec_solution, NumericVector< libMesh::Number > &ghosted_solution)
Update the solution.
ChainControlDataSystem & getChainControlDataSystem()
Gets the system that manages the ChainControls.
Definition: MooseApp.h:845
std::shared_ptr< DisplacedProblem > _displaced_problem
GeometricSearchData _geometric_search_data
State argument for evaluating functors.
void setCurrentResidualVectorTags(const std::set< TagID > &vector_tags)
Set the current residual vector tag data structure based on the passed in tag IDs.
MooseObjectWarehouse< Function > _functions
functions
void project_vector(NumericVector< Number > &new_vector, FunctionBase< Number > *f, FunctionBase< Gradient > *g=nullptr, int is_adjoint=-1) const
virtual void addObject(std::shared_ptr< T > object, THREAD_ID tid=0, bool recurse=true)
Adds an object to the storage structure.
virtual Real & timeOld() const
Proxy for accessing MaterialPropertyStorage.
Definition: MaterialData.h:37
std::vector< VectorVariableValue > _vector_zero
bool hasMultiApp(const std::string &name) const
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an optional parameter and a documentation string to the InputParameters object...
void createMortarInterface(const std::pair< BoundaryID, BoundaryID > &primary_secondary_boundary_pair, const std::pair< SubdomainID, SubdomainID > &primary_secondary_subdomain_pair, bool on_displaced, bool periodic, const bool debug, const bool correct_edge_dropping, const Real minimum_projection_angle)
std::vector< std::unique_ptr< libMesh::CouplingMatrix > > _cm
Coupling matrix for variables.
bool needInterfaceMaterialOnSide(BoundaryID bnd_id, const THREAD_ID tid)
void reinitElemFace(const Elem *elem, unsigned int side, BoundaryID, const THREAD_ID tid)
virtual void cacheResidualNeighbor(const THREAD_ID tid)
Definition: SubProblem.C:1303
Linear system to be solved.
Definition: LinearSystem.h:35
bool hasReporterValue(const ReporterName &reporter_name) const
Return True if a Reporter value with the given type and name have been created.
Definition: ReporterData.h:445
std::optional< std::vector< ConvergenceName > > _linear_convergence_names
Linear system(s) convergence name(s) (if any)
bool _has_initialized_stateful
Whether nor not stateful materials have been initialized.
void checkICRestartError(const std::string &ic_name, const std::string &name, const VariableName &var_name)
Checks if the variable of the initial condition is getting restarted and errors for specific cases...
virtual void setResidualNeighbor(NumericVector< libMesh::Number > &residual, const THREAD_ID tid) override
QueryCache & condition(Args &&... args)
Adds a new condition to the query.
Definition: TheWarehouse.h:284
const TagName SOLUTION_TAG
Definition: MooseTypes.C:25
unsigned int _max_qps
Maximum number of quadrature points used in the problem.
A class for storing an input parameter name.
static InputParameters validParams()
Eigen::Matrix< Real, Eigen::Dynamic, 1 > RealEigenVector
Definition: MooseTypes.h:147
virtual void addScalarKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
elem_info_iterator ownedElemInfoEnd()
Definition: MooseMesh.C:1586
std::set< const Elem * > & getElements()
Returns a writeable reference to the _elements container.
virtual void set(const numeric_index_type i, const T value)=0
void addGhostedBoundary(BoundaryID boundary_id)
This will add the boundary ids to be ghosted to this processor.
Definition: MooseMesh.C:3309
bool _preserve_matrix_sparsity_pattern
Whether to preserve the system matrix / Jacobian sparsity pattern, using 0-valued entries usually...
virtual unsigned int nNonlinearIterations(const unsigned int nl_sys_num) const override
void setHitNode(const std::string &param, const hit::Node &node, const SetParamHitNodeKey)
Sets the hit node associated with the parameter param to node.
CoverageCheckMode _material_coverage_check
Determines whether and which subdomains are to be checked to ensure that they have an active material...
bool isAdaptivityDue()
Query if an adaptivity step should be performed at the current time / time step.
Definition: Adaptivity.C:393
virtual std::size_t numLinearSystems() const override
MaterialPropertyStorage & _neighbor_material_props
std::unique_ptr< Backup > finalizeRestore()
Finalizes (closes) the restoration process done in restore().
Definition: MooseApp.C:1999
libMesh::StoredRange< MooseMesh::const_bnd_elem_iterator, const BndElement * > * getBoundaryElementRange()
Definition: MooseMesh.C:1353
bool isParamValid(const std::string &name) const
Test if the supplied parameter is valid.
Definition: MooseBase.h:199
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
const ConsoleStream _console
An instance of helper class to write streams to the Console objects.
const std::size_t _num_linear_sys
The number of linear systems.
std::map< std::string, unsigned int > _subspace_dim
Dimension of the subspace spanned by the vectors with a given prefix.
const libMesh::ConstElemRange & getEvaluableElementRange()
In general, {evaluable elements} >= {local elements} U {algebraic ghosting elements}.
static InputParameters validParams()
Definition: SubProblem.C:36
bool _currently_computing_residual
Whether the residual is being evaluated.
Definition: SubProblem.h:1107
const UserObject & getUserObjectBase(const std::string &name, const THREAD_ID tid=0) const
Get the user object by its name.
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type...
MooseVariableFieldBase & getVariable(THREAD_ID tid, const std::string &var_name) const
Gets a reference to a variable of with specified name.
Definition: SystemBase.C:90
bool _has_internal_edge_residual_objects
Whether the problem has dgkernels or interface kernels.
bool execMultiApps(ExecFlagType type, bool auto_advance=true)
Execute the MultiApps associated with the ExecFlagType.
const std::string & name() const
void paramWarning(const std::string &param, Args... args) const
virtual ArrayMooseVariable & getArrayVariable(const THREAD_ID tid, const std::string &var_name) override
Returns the variable reference for requested ArrayMooseVariable which may be in any system...
const ExecFlagType EXEC_SUBDOMAIN
Definition: Moose.C:50
bool _has_constraints
Whether or not this system has any Constraints.
virtual bool isTransient() const override
bool hasMultiApps() const
Returns whether or not the current simulation has any multiapps.
virtual void reinitNeighbor(const Elem *elem, unsigned int side, const THREAD_ID tid) override
const MaterialData & getMaterialData(const THREAD_ID tid) const
void doingPRefinement(bool doing_p_refinement)
Indicate whether the kind of adaptivity we&#39;re doing is p-refinement.
Definition: MooseMesh.h:1365
const bool & currentlyComputingJacobian() const
Returns true if the problem is in the process of computing the Jacobian.
Definition: SubProblem.h:684
void notifyWhenMeshChanges(MeshChangedInterface *mci)
Register an object that derives from MeshChangedInterface to be notified when the mesh changes...
ConstElemPointerRange * coarsenedElementRange() const
Return a range that is suitable for threaded execution over elements that were just coarsened...
Definition: MooseMesh.C:964
std::unique_ptr< libMesh::ConstElemRange > _evaluable_local_elem_range
const Moose::PatchUpdateType & getPatchUpdateStrategy() const
Get the current patch update strategy.
Definition: MooseMesh.C:3493
virtual void executeAllObjects(const ExecFlagType &exec_type)
CoverageCheckMode _kernel_coverage_check
Determines whether and which subdomains are to be checked to ensure that they have an active kernel...
virtual void setActiveFEVariableCoupleableVectorTags(std::set< TagID > &vtags, const THREAD_ID tid) override
void check() const
Perform integrity check for get/declare calls.
Definition: ReporterData.C:162
std::set< std::string > getPostprocessorNames() const
Return a list of all postprocessor names.
Definition: ReporterData.C:71
bool _fail_next_system_convergence_check
void ghostGhostedBoundaries()
Actually do the ghosting of boundaries that need to be ghosted to this processor. ...
Definition: MooseMesh.C:3394
std::vector< std::shared_ptr< LinearSystem > > _linear_systems
The vector of linear systems.
const hit::Node * getHitNode() const
Definition: MooseBase.h:136
std::shared_ptr< XFEMInterface > _xfem
Pointer to XFEM controller.
virtual void prepareShapes(unsigned int var, const THREAD_ID tid) override
const bool _boundary_restricted_elem_integrity_check
whether to perform checking of boundary restricted elemental object variable dependencies, e.g.
void reinitMaterialsInterface(BoundaryID boundary_id, const THREAD_ID tid, bool swap_stateful=true)
bool _const_jacobian
true if the Jacobian is constant
virtual void computeJacobianBlock(libMesh::SparseMatrix< libMesh::Number > &jacobian, libMesh::System &precond_system, unsigned int ivar, unsigned int jvar)
Really not a good idea to use this.
virtual void solveLinearSystem(const unsigned int linear_sys_num, const Moose::PetscSupport::PetscOptions *po=nullptr)
Build and solve a linear system.
virtual void computeUserObjectByName(const ExecFlagType &type, const Moose::AuxGroup &group, const std::string &name)
Compute an user object with the given name.
virtual void possiblyRebuildGeomSearchPatches()
virtual void add(const numeric_index_type i, const T value)=0
bool _safe_access_tagged_matrices
Is it safe to retrieve data from tagged matrices.
Definition: SubProblem.h:1110
std::set< TagID > _linear_vector_tags
Temporary storage for filtered vector tags for linear systems.
Class that represents the dependecy as a graph.
Moose::Kokkos::MaterialPropertyStorage & _kokkos_bnd_material_props
DiracKernelInfo _dirac_kernel_info
Definition: SubProblem.h:1051
A MultiApp represents one or more MOOSE applications that are running simultaneously.
Definition: MultiApp.h:112
const TagName PREVIOUS_NL_SOLUTION_TAG
Definition: MooseTypes.C:28
void updateBoundaryVariableDependency(std::set< MooseVariableFieldBase *> &needed_moose_vars, THREAD_ID tid=0) const
processor_id_type processor_id() const
void addObject(std::shared_ptr< FVInitialConditionBase > object, THREAD_ID tid, bool recurse=true)
Add object to the warehouse.
std::vector< T * > & queryIntoUnsorted(std::vector< T *> &results, Args &&... args)
queryInto executes the query and stores the results in the given vector.
Definition: TheWarehouse.h:324
const libMesh::ConstElemRange & getNonlinearEvaluableElementRange()
A class for storing the names of MooseObject by tag and object name.
MaterialPropertyStorage & _material_props
Base class for Postprocessors that produce a vector of values.
virtual Order default_order() const=0
void prepareMaterials(const std::unordered_set< unsigned int > &consumer_needed_mat_props, const SubdomainID blk_id, const THREAD_ID tid)
Add the MooseVariables and the material properties that the current materials depend on to the depend...
virtual void addFVKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
virtual void addFVBC(const std::string &fv_bc_name, const std::string &name, InputParameters &parameters)
libMesh::Order _max_scalar_order
Maximum scalar variable order.
virtual void addGhostedBoundary(BoundaryID boundary_id) override
Will make sure that all necessary elements from boundary_id are ghosted to this processor.
virtual bool hasFunction(const std::string &name, const THREAD_ID tid=0)
Adaptivity & adaptivity()
bool hasActiveMaterialProperties(const THREAD_ID tid) const
Method to check whether or not a list of active material roperties has been set.
ExecuteMooseObjectWarehouse< Transfer > _between_multi_app_transfers
Transfers executed just before MultiApps to transfer data between them.
bool isRecovering() const
Whether or not this is a "recover" calculation.
Definition: MooseApp.C:1884
SystemBase & sys()
Get the system this variable is part of.
virtual void cacheJacobian(const THREAD_ID tid) override
auto min(const L &left, const R &right)
TYPE_VECTOR
void jacobianSetup() override
virtual std::size_t numSolverSystems() const override
virtual void addHDGKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
virtual NumericVector< Number > & getVector(const std::string &name)
Get a raw NumericVector by name.
Definition: SystemBase.C:933
Restartable::ManagedValue< RestartableEquationSystems > _req
The EquationSystems object, wrapped for restart.
virtual unsigned int currentLinearSysNum() const override
std::vector< libMesh::CouplingMatrix > _nonlocal_cm
nonlocal coupling matrix
virtual void reinitNodeFace(const Node *node, BoundaryID bnd_id, const THREAD_ID tid) override
virtual void reinitOffDiagScalars(const THREAD_ID tid) override
processor_id_type processor_id() const
virtual void reinitElemPhys(const Elem *elem, const std::vector< Point > &phys_points_in_elem, const THREAD_ID tid) override
std::vector< std::unordered_map< BoundaryID, bool > > _interface_mat_side_cache
Cache for calculating materials on interface.
virtual void addObject(std::shared_ptr< T > object, THREAD_ID tid=0, bool recurse=true) override
Adds an object to the storage structure.
void initKokkosStatefulProps()
const std::vector< std::string > & get_nodal_var_names()
std::string getRestartRecoverFileBase() const
The file_base for the recovery file.
Definition: MooseApp.h:494
virtual void addJacobianNeighborLowerD(const THREAD_ID tid) override
virtual void prepareNeighborShapes(unsigned int var, const THREAD_ID tid) override
MooseObjectWarehouse< Marker > _markers
FVInitialConditionWarehouse _fv_ics
void setVerboseProblem(bool verbose)
Make the problem be verbose.
virtual void setNeighborSubdomainID(const Elem *elem, unsigned int side, const THREAD_ID tid) override
virtual const VectorTag & getVectorTag(const TagID tag_id) const
Get a VectorTag from a TagID.
Definition: SubProblem.C:162
MaterialBases compute MaterialProperties.
Definition: MaterialBase.h:62
virtual void initialAdaptMesh()
void updatePointLocator(const MooseMesh &mesh)
Called during FEProblemBase::meshChanged() to update the PointLocator object used by the DiracKernels...
virtual void addResidualScalar(const THREAD_ID tid=0)
Moose::Kokkos::MaterialPropertyStorage & _kokkos_neighbor_material_props
This is a template class that implements the workhorse compute and computeNodal methods.
MaterialWarehouse _all_materials
const MeshBase::element_iterator activeLocalElementsEnd()
Definition: MooseMesh.C:3137
virtual void addCachedResidual(const THREAD_ID tid) override
void declareControllable(const std::string &name, std::set< ExecFlagType > execute_flags={})
Declare the given parameters as controllable.
for(PetscInt i=0;i< nvars;++i)
void clearNearestNodeLocators()
Clear out the Penetration Locators so they will redo the search.
Moose::PetscSupport::PetscOptions _petsc_options
PETSc option storage.
libMesh::StoredRange< MooseMesh::const_bnd_node_iterator, const BndNode * > * getBoundaryNodeRange()
Definition: MooseMesh.C:1339
virtual const std::vector< std::shared_ptr< Convergence > > & getConvergenceObjects(const THREAD_ID tid=0) const
Gets the Convergence objects.
void ErrorVector unsigned int
virtual void clearActiveElementalMooseVariables(const THREAD_ID tid) override
Clear the active elemental MooseVariableFEBase.
auto index_range(const T &sizable)
Base class for user-specific data.
Definition: UserObject.h:40
void timestepSetup()
Calls the timestepSetup function for each of the output objects.
void allowOutput(bool state)
Ability to enable/disable all output calls.
virtual void cacheJacobian(const THREAD_ID tid)
Definition: SubProblem.C:1317
virtual Sampler & getSampler(const std::string &name, const THREAD_ID tid=0)
const std::string & _type
The type of this class.
Definition: MooseBase.h:360
virtual void outputStep(ExecFlagType type)
Output the current step.
void projectInitialConditionOnCustomRange(libMesh::ConstElemRange &elem_range, ConstBndNodeRange &bnd_node_range, const std::optional< std::set< VariableName >> &target_vars=std::nullopt)
Project initial conditions for custom elem_range and bnd_node_range This is needed when elements/boun...
virtual unsigned int nlSysNum(const NonlinearSystemName &nl_sys_name) const override
OutputWarehouse & getOutputWarehouse()
Get the OutputWarehouse objects.
Definition: MooseApp.C:2525
MooseEnum _verbose_setup
Whether or not to be verbose during setup.
static InputParameters validParams()
RedistributeProperties is used for its redistribute() callback, which ensures that any stateful prope...
unsigned int state
The state.
virtual void computeJacobianTags(const std::set< TagID > &tags)
Form multiple matrices, and each is associated with a tag.
void computeSystems(const ExecFlagType &type)
Do generic system computations.
SolutionIterationType
Definition: MooseTypes.h:269
MooseMesh * _displaced_mesh
void resize(unsigned int n_qpoints)
Resize the data to hold properties for n_qpoints quadrature points.
Definition: MaterialData.C:21
bool _has_mortar
Whether the simulation requires mortar coupling.
void computeLinearSystemTags(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags, const bool compute_gradients=true)
Compute the right hand side and the system matrix of the system for given tags.
Definition: LinearSystem.C:154
libMesh::Order getMaxScalarOrder() const
void execTransfers(ExecFlagType type)
Execute the Transfers associated with the ExecFlagType.
void addNotZeroedVectorTag(const TagID tag)
Adds a vector tag to the list of vectors that will not be zeroed when other tagged vectors are...
Definition: SubProblem.C:150
Base variable class.
void restoreState(bool verbose=false)
When a time step fails, this method is called to revert the current reporter values to their old stat...
Definition: ReporterData.C:24
void meshChanged()
Declares that the MooseMesh has changed, invalidates cached data and rebuilds caches.
Definition: MooseMesh.C:909
void buildPRefinementAndCoarseningMaps(Assembly *assembly)
Definition: MooseMesh.C:2418
const std::vector< ConvergenceName > & getLinearConvergenceNames() const
Gets the linear convergence object name(s).
unsigned int THREAD_ID
Definition: MooseTypes.h:237
virtual void ghostGhostedBoundaries() override
Causes the boundaries added using addGhostedBoundary to actually be ghosted.
const ExecFlagType EXEC_POST_ADAPTIVITY
Definition: Moose.C:58
void add_ghosting_functor(GhostingFunctor &ghosting_functor)
MaterialWarehouse _materials
uint8_t dof_id_type
virtual bool adaptMesh()
virtual void addJacobianScalar(const THREAD_ID tid=0)
virtual void addDiracKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
An instance of this object type has one copy per thread that runs on each thread. ...
MooseObjectWarehouse< IntegratedBCBase > _nonlocal_integrated_bcs
nonlocal integrated_bcs
virtual void computeResidualTag(const NumericVector< libMesh::Number > &soln, NumericVector< libMesh::Number > &residual, TagID tag)
Form a residual vector for a given tag.
virtual VectorMooseVariable & getVectorVariable(const THREAD_ID tid, const std::string &var_name) override
Returns the variable reference for requested VectorMooseVariable which may be in any system...
std::shared_ptr< LineSearch > _line_search
void initXFEM(std::shared_ptr< XFEMInterface > xfem)
Create XFEM controller object.
const std::set< SubdomainID > & meshSubdomains() const
Returns a read-only reference to the set of subdomains currently present in the Mesh.
Definition: MooseMesh.C:3251
SubdomainID getSubdomainID(const SubdomainName &subdomain_name) const
Get the associated subdomain ID for the subdomain name.
Definition: MooseMesh.C:1781
const FEType & type() const
Base class for all Transfer objects.
Definition: Transfer.h:36
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...
void parallelBarrierNotify(const Parallel::Communicator &comm, bool messaging)
Definition: MooseUtils.C:327
virtual void neighborSubdomainSetup(SubdomainID subdomain, const THREAD_ID tid)
void setupFiniteVolumeMeshData() const
Sets up the additional data needed for finite volume computations.
Definition: MooseMesh.C:4152
virtual void addCachedJacobian(const THREAD_ID tid) override
virtual void residualSetup(THREAD_ID tid=0) const
virtual void sizeZeroes(unsigned int size, const THREAD_ID tid)
virtual Real computeDamping(const NumericVector< libMesh::Number > &soln, const NumericVector< libMesh::Number > &update)
std::vector< Real > _real_zero
Convenience zeros.
MooseObjectWarehouse< KernelBase > _nonlocal_kernels
nonlocal kernels
void checkCoordinateSystems()
Verify that there are no element type/coordinate type conflicts.
bool isParamValid(const std::string &name) const
This method returns parameters that have been initialized in one fashion or another, i.e.
unsigned int getMaxQps() const
const ExecFlagType EXEC_INITIAL
Definition: Moose.C:30
virtual libMesh::System & system() override
Get the reference to the libMesh system.
bool _verbose_multiapps
Whether or not to be verbose with multiapps.
Key structure for APIs manipulating global vectors/matrices.
Definition: Assembly.h:844