https://mooseframework.inl.gov
Loading...
Searching...
No Matches
PhysicsBase.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#include "PhysicsBase.h"
12#include "MooseUtils.h"
13#include "FEProblemBase.h"
14
15#include "NonlinearSystemBase.h"
16#include "AuxiliarySystem.h"
17#include "BlockRestrictable.h"
18#include "ActionComponent.h"
21#include "MooseVariableScalar.h"
22#include "LinearSystem.h"
23
26{
28 params.addClassDescription("Creates all the objects necessary to solve a particular physics");
29
30 params.addParam<std::vector<SubdomainName>>(
31 "block", {}, "Blocks (subdomains) that this Physics is active on.");
32
33 MooseEnum transient_options("true false same_as_problem", "same_as_problem");
34 params.addParam<MooseEnum>(
35 "transient", transient_options, "Whether the physics is to be solved as a transient");
36
37 params.addParam<bool>("verbose", false, "Flag to facilitate debugging a Physics");
38
39 // Numerical solve parameters
40 params.addParam<std::vector<SolverSystemName>>(
41 "system_names",
42 {"nl0"},
43 "Name of the solver system(s) for the variables. If a single name is specified, "
44 "that system is used for all solver variables.");
45 MooseEnum pc_options("default defer", "defer");
46 params.addParam<MooseEnum>("preconditioning",
47 pc_options,
48 "Which preconditioning to use/add for this Physics, or whether to "
49 "defer to the Preconditioning block, or another Physics");
50
51 // Restart parameters
52 params.addParam<bool>("initialize_variables_from_mesh_file",
53 false,
54 "Determines if the variables that are added by the action are initialized"
55 "from the mesh file (only for Exodus format)");
56 params.addParam<std::string>(
57 "initial_from_file_timestep",
58 "LATEST",
59 "Gives the time step number (or \"LATEST\") for which to read the Exodus solution");
60 params.addParamNamesToGroup("initialize_variables_from_mesh_file initial_from_file_timestep",
61 "Restart from Exodus");
62
63 // Options to turn off tasks
64 params.addParam<bool>("dont_create_solver_variables",
65 false,
66 "Whether to skip the 'add_variable'/'add_variables_physics' task(s)");
67 params.addParam<bool>(
68 "dont_create_ics", false, "Whether to skip the 'add_ic'/'add_fv_ic/add_ics_physics' task(s)");
69 params.addParam<bool>(
70 "dont_create_kernels", false, "Whether to skip the 'add_kernel' task for each kernel type");
71 params.addParam<bool>("dont_create_bcs",
72 false,
73 "Whether to skip the 'add_bc' task for each boundary condition type");
74 params.addParam<bool>("dont_create_functions", false, "Whether to skip the 'add_function' task");
75 params.addParam<bool>(
76 "dont_create_aux_variables", false, "Whether to skip the 'add_aux_variable' task");
77 params.addParam<bool>(
78 "dont_create_aux_kernels", false, "Whether to skip the 'add_aux_kernel' task");
79 params.addParam<bool>(
80 "dont_create_materials",
81 false,
82 "Whether to skip the 'add_material'/'add_materials_physics' task(s) for each material type");
83 params.addParam<bool>(
84 "dont_create_user_objects",
85 false,
86 "Whether to skip the 'add_user_object' task. This does not apply to UserObject derived "
87 "classes being created on a different task (for example: postprocessors, VPPs, correctors)");
88 params.addParam<bool>(
89 "dont_create_correctors", false, "Whether to skip the 'add_correctors' task");
90 params.addParam<bool>(
91 "dont_create_postprocessors", false, "Whether to skip the 'add_postprocessors' task");
92 params.addParam<bool>("dont_create_vectorpostprocessors",
93 false,
94 "Whether to skip the 'add_vectorpostprocessors' task");
96 "dont_create_solver_variables dont_create_ics dont_create_kernels dont_create_bcs "
97 "dont_create_functions dont_create_aux_variables dont_create_aux_kernels "
98 "dont_create_materials dont_create_user_objects dont_create_correctors "
99 "dont_create_postprocessors dont_create_vectorpostprocessors",
100 "Reduce Physics object creation");
101
102 params.addParamNamesToGroup("active inactive", "Advanced");
103 params.addParamNamesToGroup("preconditioning system_names", "Numerical scheme");
104 return params;
105}
106
108 : Action(parameters),
110 _system_names(getParam<std::vector<SolverSystemName>>("system_names")),
111 _verbose(getParam<bool>("verbose")),
112 _preconditioning(getParam<MooseEnum>("preconditioning")),
113 _blocks(getParam<std::vector<SubdomainName>>("block")),
114 _is_transient(getParam<MooseEnum>("transient"))
115{
116 checkSecondParamSetOnlyIfFirstOneTrue("initialize_variables_from_mesh_file",
117 "initial_from_file_timestep");
119 addRequiredPhysicsTask("init_physics");
120 addRequiredPhysicsTask("copy_vars_physics");
121 addRequiredPhysicsTask("check_integrity_early_physics");
122}
123
124void
126{
127 mooseDoOnce(checkRequiredTasks());
128
129 // Lets a derived Physics class implement additional tasks
131
132 // Initialization and variables
133 if (_current_task == "init_physics")
135 else if ((_current_task == "add_variable" || _current_task == "add_variables_physics") &&
136 !getParam<bool>("dont_create_solver_variables"))
138 else if ((_current_task == "add_ic" || _current_task == "add_fv_ic" ||
139 _current_task == "add_ics_physics") &&
140 !getParam<bool>("dont_create_ics"))
142
143 // Kernels
144 else if (_current_task == "add_interpolation_method_physics" &&
145 !getParam<bool>("dont_create_kernels"))
147 else if (_current_task == "add_kernel" && !getParam<bool>("dont_create_kernels"))
148 addFEKernels();
149 else if (_current_task == "add_nodal_kernel" && !getParam<bool>("dont_create_kernels"))
151 else if ((_current_task == "add_fv_kernel" || _current_task == "add_linear_fv_kernel") &&
152 !getParam<bool>("dont_create_kernels"))
153 addFVKernels();
154 else if (_current_task == "add_dirac_kernel" && !getParam<bool>("dont_create_kernels"))
156 else if (_current_task == "add_dg_kernel" && !getParam<bool>("dont_create_kernels"))
157 addDGKernels();
158 else if (_current_task == "add_scalar_kernel" && !getParam<bool>("dont_create_kernels"))
160 else if (_current_task == "add_interface_kernel" && !getParam<bool>("dont_create_kernels"))
162 else if (_current_task == "add_fv_ik" && !getParam<bool>("dont_create_kernels"))
164
165 // Boundary conditions
166 else if (_current_task == "add_bc" && !getParam<bool>("dont_create_bcs"))
167 addFEBCs();
168 else if (_current_task == "add_nodal_bc" && !getParam<bool>("dont_create_bcs"))
169 addNodalBCs();
170 else if ((_current_task == "add_fv_bc" || _current_task == "add_linear_fv_bc") &&
171 !getParam<bool>("dont_create_bcs"))
172 addFVBCs();
173 else if (_current_task == "add_periodic_bc" && !getParam<bool>("dont_create_bcs"))
175
176 // Auxiliary quantities
177 else if (_current_task == "add_function" && !getParam<bool>("dont_create_functions"))
178 addFunctions();
179 else if (_current_task == "add_aux_variable" && !getParam<bool>("dont_create_aux_variables"))
181 else if (_current_task == "add_aux_kernel" && !getParam<bool>("dont_create_aux_kernels"))
183 else if ((_current_task == "add_material" || _current_task == "add_materials_physics") &&
184 !getParam<bool>("dont_create_materials"))
185 addMaterials();
186 else if (_current_task == "add_functor_material" && !getParam<bool>("dont_create_materials"))
188
189 // Multiapp
190 else if (_current_task == "add_multi_app")
191 addMultiApps();
192 else if (_current_task == "add_transfer")
193 addTransfers();
194
195 // User objects and output
196 else if (_current_task == "add_user_object" && !getParam<bool>("dont_create_user_objects"))
198 else if (_current_task == "add_corrector" && !getParam<bool>("dont_create_correctors"))
200 else if (_current_task == "add_postprocessor" && !getParam<bool>("dont_create_postprocessors"))
202 else if (_current_task == "add_vector_postprocessor" &&
203 !getParam<bool>("dont_create_vectorpostprocessors"))
205 else if (_current_task == "add_reporter")
206 addReporters();
207 else if (_current_task == "add_output")
208 addOutputs();
209
210 // Equation solver-related tasks
211 else if (_current_task == "add_preconditioning")
213 else if (_current_task == "add_executioner")
215 else if (_current_task == "add_executor")
216 addExecutors();
217
218 // Checks
219 else if (_current_task == "check_integrity_early_physics")
221 else if (_current_task == "check_integrity")
223
224 // Exodus restart capabilities
225 if (_current_task == "copy_vars_physics")
226 {
228 if (_aux_var_names.size() > 0)
230 }
231}
232
233void
234PhysicsBase::addUserObject(const std::string & uo_type,
235 const std::string & uo_name,
236 InputParameters & params)
237{
238 mooseAssert(
239 [&]()
240 {
241 const auto supplied = getSuppliedUserObjects();
242 return std::find(supplied.begin(), supplied.end(), uo_name) != supplied.end();
243 }(),
244 "The UserObject '" + uo_name + "' added by Physics '" + name() +
245 "' was not declared in getSuppliedUserObjects(). Declare it there so its construction "
246 "order can be resolved.");
247 getProblem().addUserObject(uo_type, uo_name, params);
248}
249
250void
252{
253 if (getParam<bool>("initialize_variables_from_mesh_file"))
255
256 checkSecondParamSetOnlyIfFirstOneTrue("initialize_variables_from_mesh_file",
257 "initial_from_file_timestep");
258}
259
260bool
262{
263 mooseAssert(_problem, "We don't have a problem yet");
264 if (_is_transient == "true")
265 return true;
266 else if (_is_transient == "false")
267 return false;
268 else
269 return getProblem().isTransient();
270}
271
272unsigned int
274{
275 mooseAssert(_mesh, "We dont have a mesh yet");
276 mooseAssert(_dim < 4, "Dimension has not been set yet");
277 return _dim;
278}
279
280std::set<SubdomainID>
281PhysicsBase::getSubdomainIDs(const std::set<SubdomainName> & blocks) const
282{
283 const bool not_block_restricted =
284 (std::find(blocks.begin(), blocks.end(), "ANY_BLOCK_ID") != blocks.end()) ||
286 mooseAssert(_mesh, "Should have a mesh");
287 // use a set for simplicity. Note that subdomain names are unique, except maybe the empty one,
288 // which cannot be specified by the user to the Physics.
289 // MooseMesh::getSubdomainIDs cannot deal with the 'ANY_BLOCK_ID' name
290 std::set<SubdomainID> block_ids_set =
291 not_block_restricted ? _mesh->meshSubdomains() : _mesh->getSubdomainIDs(blocks);
292 return block_ids_set;
293}
294
295std::vector<std::string>
296PhysicsBase::getSubdomainNamesAndIDs(const std::set<SubdomainID> & blocks) const
297{
298 mooseAssert(_mesh, "Should have a mesh");
299 std::vector<std::string> sub_names_ids;
300 sub_names_ids.reserve(blocks.size());
301 for (const auto bid : blocks)
302 {
303 const auto bname = _mesh->getSubdomainName(bid);
304 sub_names_ids.push_back((bname.empty() ? "(unnamed)" : bname) + " (" + std::to_string(bid) +
305 ")");
306 }
307 return sub_names_ids;
308}
309
310void
311PhysicsBase::addBlocks(const std::vector<SubdomainName> & blocks)
312{
313 if (blocks.size())
314 {
315 _blocks.insert(_blocks.end(), blocks.begin(), blocks.end());
316 _dim = _mesh->getBlocksMaxDimension(_blocks);
317 }
318}
319
320void
321PhysicsBase::addBlocksById(const std::vector<SubdomainID> & block_ids)
322{
323 if (block_ids.size())
324 {
325 for (const auto bid : block_ids)
326 _blocks.push_back(_mesh->getSubdomainName(bid));
327 _dim = _mesh->getBlocksMaxDimension(_blocks);
328 }
329}
330
331void
333{
334 for (const auto & block : component.blocks())
335 _blocks.push_back(block);
336}
337
338void
344
345const ActionComponent &
346PhysicsBase::getActionComponent(const ComponentName & comp_name) const
347{
348 return _awh.getAction<ActionComponent>(comp_name);
349}
350
351void
353{
354 // Annoying edge case. We cannot use ANY_BLOCK_ID for kernels and variables since errors got
355 // added downstream for using it, we cannot leave it empty as that sets all objects to not live
356 // on any block
357 if (isParamSetByUser("block") && _blocks.empty())
358 paramError("block",
359 "Empty block restriction is not supported. Comment out the Physics if you are "
360 "trying to disable it.");
361
362 // Components should have added their blocks already.
363 if (_blocks.empty())
364 _blocks.push_back("ANY_BLOCK_ID");
365
366 mooseAssert(_mesh, "We should have a mesh to find the dimension");
367 if (_blocks.size())
368 _dim = _mesh->getBlocksMaxDimension(_blocks);
369 else
370 _dim = _mesh->dimension();
371
372 // Forward physics verbosity to problem to output the setup
373 if (_verbose)
375
376 // If the derived physics need additional initialization very early on
378
379 // Check that the systems exist in the Problem
380 // TODO: try to add the systems to the problem from here instead
381 // NOTE: this must be performed after the "Additional" initialization because the list
382 // of systems might have been adjusted once the dimension of the Physics is known
383 const auto & problem_nl_systems = getProblem().getNonlinearSystemNames();
384 const auto & problem_lin_systems = getProblem().getLinearSystemNames();
385 for (const auto & sys_name : _system_names)
386 if (std::find(problem_nl_systems.begin(), problem_nl_systems.end(), sys_name) ==
387 problem_nl_systems.end() &&
388 std::find(problem_lin_systems.begin(), problem_lin_systems.end(), sys_name) ==
389 problem_lin_systems.end() &&
390 solverVariableNames().size())
391 mooseError("System '", sys_name, "' is not found in the Problem");
392
393 // Cache system number as it makes some logic easier
394 for (const auto & sys_name : _system_names)
395 _system_numbers.push_back(getProblem().solverSysNum(sys_name));
396}
397
398void
400{
401 if (_is_transient == "true" && !getProblem().isTransient())
402 paramError("transient", "We cannot solve a physics as transient in a steady problem");
403
404 // Check that there is a system for each variable
405 if (_system_names.size() != 1 && _system_names.size() != _solver_var_names.size())
406 paramError("system_names",
407 "There should be one system name per solver variable (potentially repeated), or a "
408 "single system name for all variables. Currently you have '" +
409 std::to_string(_system_names.size()) + "' systems specified for '" +
410 std::to_string(_solver_var_names.size()) + "' solver variables.");
411
412 // Check that each variable is present in the expected system
413 unsigned int var_i = 0;
414 for (const auto & var_name : _solver_var_names)
415 {
416 const auto & sys_name = _system_names.size() == 1 ? _system_names[0] : _system_names[var_i++];
417 if (!_problem->getSolverSystem(_problem->solverSysNum(sys_name)).hasVariable(var_name) &&
418 !_problem->getSolverSystem(_problem->solverSysNum(sys_name)).hasScalarVariable(var_name))
419 paramError("system_names",
420 "We expected system '" + sys_name + "' to contain variable '" + var_name +
421 "' but it did not. Make sure the system names closely match the ordering of "
422 "the variables in the Physics.");
423 }
424}
425
426void
427PhysicsBase::copyVariablesFromMesh(const std::vector<VariableName> & variables_to_copy,
428 bool are_solver_var)
429{
430 if (getParam<bool>("initialize_variables_from_mesh_file"))
431 {
432 mooseInfoRepeated("Adding Exodus restart for " + std::to_string(variables_to_copy.size()) +
433 " variables: " + Moose::stringify(variables_to_copy));
434 // TODO Check that the variable types and orders are actually supported for exodus restart
435 for (const auto i : index_range(variables_to_copy))
436 {
437 SystemBase & system = are_solver_var ? getProblem().getSystemBase(_system_numbers.size() == 1
438 ? _system_numbers[0]
439 : _system_numbers[i])
441 const auto & var_name = variables_to_copy[i];
442 system.addVariableToCopy(
443 var_name, var_name, getParam<std::string>("initial_from_file_timestep"));
444 }
445 }
446}
447
448void
449PhysicsBase::addSharedSolverVariable(const std::string & var_type,
450 const VariableName & var_name,
451 InputParameters params)
452{
453 // Saved first as getSolverSystem() looks for the variable among the Physics' solver variables.
454 // Some Physics already saved their variables in their constructor.
455 if (std::find(_solver_var_names.begin(), _solver_var_names.end(), var_name) ==
456 _solver_var_names.end())
457 saveSolverVariableName(var_name);
458 params.set<SolverSystemName>("solver_sys") = getSolverSystem(var_name);
460 .requestVariable(true, var_type, var_name, params, _blocks, name());
461}
462
463void
464PhysicsBase::addSharedAuxVariable(const std::string & var_type,
465 const VariableName & var_name,
466 const InputParameters & params)
467{
468 if (std::find(_aux_var_names.begin(), _aux_var_names.end(), var_name) == _aux_var_names.end())
469 saveAuxVariableName(var_name);
471 .requestVariable(false, var_type, var_name, params, _blocks, name());
472}
473
474void
475PhysicsBase::addSharedSolverVariable(const VariableName & var_name,
476 const std::string & family,
477 const std::string & order,
478 const Real scaling)
479{
480 const std::string var_type = "MooseVariable";
481 InputParameters params = getFactory().getValidParams(var_type);
482 params.set<MooseEnum>("family") = family;
483 params.set<MooseEnum>("order") = order;
484 params.set<std::vector<Real>>("scaling") = {scaling};
485 addSharedSolverVariable(var_type, var_name, params);
486}
487
488void
489PhysicsBase::addSharedAuxVariable(const VariableName & var_name,
490 const std::string & family,
491 const std::string & order)
492{
493 const std::string var_type = "MooseVariable";
494 InputParameters params = getFactory().getValidParams(var_type);
495 params.set<MooseEnum>("family") = family;
496 params.set<MooseEnum>("order") = order;
497 addSharedAuxVariable(var_type, var_name, params);
498}
499
500bool
501PhysicsBase::variableExists(const VariableName & var_name, bool error_if_aux) const
502{
503 if (error_if_aux && _problem->getAuxiliarySystem().hasVariable(var_name))
504 mooseError("Variable '",
505 var_name,
506 "' is supposed to be nonlinear for physics '",
507 name(),
508 "' but it is already defined as auxiliary");
509 else
510 return _problem->hasVariable(var_name);
511}
512
513bool
514PhysicsBase::solverVariableExists(const VariableName & var_name) const
515{
516 return _problem->hasSolverVariable(var_name);
517}
518
519const SolverSystemName &
520PhysicsBase::getSolverSystem(unsigned int variable_index) const
521{
522 mooseAssert(!_system_names.empty(), "We should have a solver system name");
523 if (_system_names.size() == 1)
524 return _system_names[0];
525 else
526 // We trust that the system names and the variable names match one-to-one as it is enforced by
527 // the checkIntegrityEarly() routine.
528 return _system_names[variable_index];
529}
530
531const SolverSystemName &
532PhysicsBase::getSolverSystem(const VariableName & var_name) const
533{
534 mooseAssert(!_system_names.empty(), "We should have a solver system name");
535 // No need to look if only one system for the Physics
536 if (_system_names.size() == 1)
537 return _system_names[0];
538
539 // We trust that the system names and the variable names match one-to-one as it is enforced by
540 // the checkIntegrityEarly() routine.
541 for (const auto variable_index : index_range(_solver_var_names))
542 if (var_name == _solver_var_names[variable_index])
543 return _system_names[variable_index];
544 mooseError("Variable '", var_name, "' was not found within the Physics solver variables.");
545}
546
547void
549{
550 const auto registered_tasks = _action_factory.getTasksByAction(type());
551
552 // Check for missing tasks
553 for (const auto & required_task : _required_tasks)
554 if (!registered_tasks.count(required_task))
555 mooseWarning("Task '" + required_task +
556 "' has been declared as required by a Physics parent class of derived class '" +
557 type() +
558 "' but this task is not registered to the derived class. Registered tasks for "
559 "this Physics are: " +
560 Moose::stringify(registered_tasks));
561}
562
563void
564PhysicsBase::assignBlocks(InputParameters & params, const std::vector<SubdomainName> & blocks) const
565{
566 // We only set the blocks if we don't have `ANY_BLOCK_ID` defined because the subproblem
567 // (through the mesh) errors out if we use this keyword during the addVariable/Kernel
568 // functions
569 if (std::find(blocks.begin(), blocks.end(), "ANY_BLOCK_ID") == blocks.end())
570 params.set<std::vector<SubdomainName>>("block") = blocks;
571 if (blocks.empty())
572 mooseInfoRepeated("Empty block restriction assigned to an object created by Physics '" +
573 name() + "'.\n Did you mean to do this?");
574}
575
576bool
577PhysicsBase::checkBlockRestrictionIdentical(const std::string & object_name,
578 const std::vector<SubdomainName> & blocks,
579 bool error_if_not_identical) const
580{
581 // If identical, we can return fast
582 if (_blocks == blocks)
583 return true;
584 // If one is block restricted to anywhere and the other is block restricted to anywhere manually
585 if ((std::find(_blocks.begin(), _blocks.end(), "ANY_BLOCK_ID") != _blocks.end() &&
587 (std::find(blocks.begin(), blocks.end(), "ANY_BLOCK_ID") != blocks.end() &&
589 return true;
590
591 // Copy, sort and unique is the only way to check that they are actually the same
592 auto copy_blocks = _blocks;
593 auto copy_blocks_other = blocks;
594 std::sort(copy_blocks.begin(), copy_blocks.end());
595 copy_blocks.erase(unique(copy_blocks.begin(), copy_blocks.end()), copy_blocks.end());
596 std::sort(copy_blocks_other.begin(), copy_blocks_other.end());
597 copy_blocks_other.erase(unique(copy_blocks_other.begin(), copy_blocks_other.end()),
598 copy_blocks_other.end());
599
600 if (copy_blocks == copy_blocks_other)
601 return true;
602 std::vector<SubdomainName> diff;
603 std::set_difference(copy_blocks.begin(),
604 copy_blocks.end(),
605 copy_blocks_other.begin(),
606 copy_blocks_other.end(),
607 std::inserter(diff, diff.begin()));
608 if (error_if_not_identical)
609 mooseError("Physics '",
610 name(),
611 "' and object '",
612 object_name,
613 "' have different block restrictions.\nPhysics: ",
615 "\nObject: ",
617 "\nDifference: ",
618 Moose::stringify(diff));
619 else
620 return false;
621}
622
623bool
624PhysicsBase::hasBlocks(const std::vector<SubdomainName> & blocks) const
625{
626 mooseAssert(_blocks.size(), "hasBlocks called before blocks were initialized");
627 return std::all_of(blocks.begin(),
628 blocks.end(),
629 [this](const SubdomainName & block)
630 { return std::find(_blocks.begin(), _blocks.end(), block) != _blocks.end(); });
631}
632
633bool
634PhysicsBase::allMeshBlocks(const std::vector<SubdomainName> & blocks) const
635{
636 mooseAssert(_mesh, "The mesh should exist already");
637 // Try to return faster without examining every single block
638 if (std::find(blocks.begin(), blocks.end(), "ANY_BLOCK_ID") != blocks.end())
639 return true;
640 else if (blocks.size() != _mesh->meshSubdomains().size())
641 return false;
642
643 for (const auto mesh_block : _mesh->meshSubdomains())
644 {
645 const auto & subdomain_name = _mesh->getSubdomainName(mesh_block);
646 // Check subdomain name
647 if (!subdomain_name.empty() &&
648 std::find(blocks.begin(), blocks.end(), subdomain_name) == blocks.end())
649 return false;
650 // no subdomain name, check the IDs being used as names instead
651 else if (std::find(blocks.begin(), blocks.end(), std::to_string(mesh_block)) == blocks.end())
652 return false;
653 }
654 return true;
655}
656
657bool
658PhysicsBase::allMeshBlocks(const std::set<SubdomainName> & blocks) const
659{
660 std::vector<SubdomainName> blocks_vec(blocks.begin(), blocks.end());
661 return allMeshBlocks(blocks_vec);
662}
663
664void
666 const std::vector<std::pair<MooseEnumItem, std::string>> & petsc_pair_options)
667{
668 Moose::PetscSupport::PetscOptions & po = _problem->getPetscOptions();
669 for (const auto solver_sys_num : _system_numbers)
671 petsc_pair_options,
672 _problem->mesh().dimension(),
673 _problem->getSolverSystem(solver_sys_num).prefix(),
674 *this,
675 po);
676}
677
678bool
679PhysicsBase::isVariableFV(const VariableName & var_name) const
680{
681 const auto var = &_problem->getVariable(0, var_name);
682 return var->isFV();
683}
684
685bool
686PhysicsBase::isVariableScalar(const VariableName & var_name) const
687{
688 return _problem->hasScalarVariable(var_name);
689}
690
691bool
692PhysicsBase::shouldCreateVariable(const VariableName & var_name,
693 const std::vector<SubdomainName> & blocks,
694 const bool error_if_aux)
695{
696 if (!variableExists(var_name, error_if_aux))
697 return true;
698 // check block restriction
699 auto & var = _problem->getVariable(0, var_name);
700 const bool not_block_restricted =
701 (std::find(blocks.begin(), blocks.end(), "ANY_BLOCK_ID") != blocks.end()) ||
703 if (!var.blockRestricted() || (!not_block_restricted && var.hasBlocks(blocks)))
704 return false;
705
706 // This is an edge case, which might warrant a warning
707 if (allMeshBlocks(var.blocks()) && not_block_restricted)
708 return false;
709 else
710 mooseError("Variable '" + var_name + "' already exists with subdomain restriction '" +
711 Moose::stringify(var.blocks()) + "' which does not include the subdomains '" +
712 Moose::stringify(blocks) + "', required for this Physics.");
713}
714
715bool
716PhysicsBase::shouldCreateIC(const VariableName & var_name,
717 const std::vector<SubdomainName> & blocks,
718 const bool ic_is_default_ic,
719 const bool error_if_already_defined) const
720{
721 // Handle recover
722 if (ic_is_default_ic && (_app.isRestarting() || _app.isRecovering()))
723 return false;
724 // do not set initial conditions if we are loading fields from the mesh file
725 if (getParam<bool>("initialize_variables_from_mesh_file"))
726 return false;
727 // Different type of ICs, not block restrictable
728 mooseAssert(!isVariableScalar(var_name), "shouldCreateIC not implemented for scalar variables");
729
730 // Process the desired block restriction into a set of subdomain IDs
731 std::set<SubdomainName> blocks_set(blocks.begin(), blocks.end());
732 const auto blocks_ids_set = getSubdomainIDs(blocks_set);
733
734 // Check whether there are any ICs for this variable already in the problem
735 std::set<SubdomainID> blocks_ids_covered;
736 bool has_all_blocks;
737 if (isVariableFV(var_name))
738 {
739 has_all_blocks = _problem->getFVInitialConditionWarehouse().hasObjectsForVariableAndBlocks(
740 var_name, blocks_ids_set, blocks_ids_covered, /*tid =*/0);
741 // FV variables can be initialized by non-FV ICs
742 std::set<SubdomainID> blocks_ids_covered_fe;
743 const bool has_all_blocks_from_feics =
744 _problem->getInitialConditionWarehouse().hasObjectsForVariableAndBlocks(
745 var_name, blocks_ids_set, blocks_ids_covered_fe, /*tid =*/0);
746 // Note we are missing the case with complete but split coverage
747 has_all_blocks = has_all_blocks || has_all_blocks_from_feics;
748 blocks_ids_covered.insert(blocks_ids_covered_fe.begin(), blocks_ids_covered_fe.end());
749 }
750 else
751 has_all_blocks = _problem->getInitialConditionWarehouse().hasObjectsForVariableAndBlocks(
752 var_name, blocks_ids_set, blocks_ids_covered, /*tid =*/0);
753
754 const bool has_some_blocks = !blocks_ids_covered.empty();
755 if (!has_some_blocks)
756 return true;
757
758 if (has_all_blocks)
759 {
760 if (error_if_already_defined)
761 mooseError("ICs for variable '" + var_name + "' have already been defined for blocks '" +
762 Moose::stringify(blocks) + "'.");
763 else
764 return false;
765 }
766
767 // Partial overlap between Physics is not implemented.
768 mooseError("There is a partial overlap between the subdomains covered by pre-existing initial "
769 "conditions (ICs), defined on blocks (ids): " +
770 Moose::stringify(getSubdomainNamesAndIDs(blocks_ids_covered)) +
771 "\n and a newly created IC for variable '" + var_name +
772 "', to be defined on blocks: " + Moose::stringify(blocks) +
773 ".\nWe should be creating the Physics' IC only for non-covered blocks. This is not "
774 "implemented at this time.");
775}
776
777bool
778PhysicsBase::shouldCreateTimeDerivative(const VariableName & var_name,
779 const std::vector<SubdomainName> & blocks,
780 const bool error_if_already_defined) const
781{
782 // Follow the transient setting of the Physics
783 if (!isTransient())
784 return false;
785
786 // Variable is either nonlinear (FV/FE), nodal nonlinear (field of ODEs), linear, or scalar.
787 // The warehouses hosting the time kernels are different for each of these types
788 // Different type of time derivatives, not block restrictable
789 mooseAssert(!isVariableScalar(var_name),
790 "shouldCreateTimeDerivative not implemented for scalar variables");
791 mooseAssert(!_problem->hasAuxiliaryVariable(var_name),
792 "Should not be called with auxiliary variables");
793
794 // Get solver system type
795 const auto var = &_problem->getVariable(0, var_name);
796 const auto var_id = var->number();
797 const auto sys_num = var->sys().number();
798 const auto time_vector_tag =
799 (sys_num < _problem->numNonlinearSystems())
800 ? var->sys().timeVectorTag()
801 // this is not quite correct. Many kernels can contribute to RHS time vector on paper
802 : dynamic_cast<LinearSystem *>(&var->sys())->rightHandSideTimeVectorTag();
803
804 // We just use the warehouse, it should cover every time derivative object type
805 bool all_blocks_covered = true;
806 std::set<SubdomainID> blocks_ids_covered;
807 // we examine subdomain by subdomain, because mutiple kernels could be covering every block in
808 // the 'blocks' parameter
809 for (const auto & block : blocks)
810 {
811 std::vector<MooseObject *> time_kernels;
812 if (block != "ANY_BLOCK_ID")
813 {
814 const auto bid = _mesh->getSubdomainID(block);
815 _problem->theWarehouse()
816 .query()
817 .template condition<AttribSysNum>(sys_num)
818 .template condition<AttribVar>(var_id)
819 .template condition<AttribSubdomains>(bid)
820 // we use the time tag as a proxy for time derivatives
821 .template condition<AttribVectorTags>(time_vector_tag)
822 .queryInto(time_kernels);
823 }
824 else
825 _problem->theWarehouse()
826 .query()
827 .template condition<AttribSysNum>(sys_num)
828 .template condition<AttribVar>(var_id)
829 // we use the time tag as a proxy for time derivatives
830 .template condition<AttribVectorTags>(time_vector_tag)
831 .queryInto(time_kernels);
832
833 if (time_kernels.size())
834 {
835 if (block == "ANY_BLOCK_ID")
836 {
837 for (const auto & time_kernel : time_kernels)
838 if (const auto blk = dynamic_cast<BlockRestrictable *>(time_kernel))
839 blocks_ids_covered.insert(blk->blockIDs().begin(), blk->blockIDs().end());
840 }
841 else
842 blocks_ids_covered.insert(_mesh->getSubdomainID(block));
843 }
844 else
845 all_blocks_covered = false;
846 }
847
848 // From the set of covered blocks, see if the blocks we needed are found
849 if (all_blocks_covered)
850 {
851 std::set<SubdomainName> blocks_set(blocks.begin(), blocks.end());
852 const auto blocks_ids = getSubdomainIDs(blocks_set);
853 if (blocks_ids != blocks_ids_covered)
854 all_blocks_covered = false;
855 }
856 const bool has_some_blocks = !blocks_ids_covered.empty();
857 if (!has_some_blocks)
858 return true;
859 if (all_blocks_covered)
860 {
861 if (error_if_already_defined)
862 mooseError("A time kernel for variable '" + var_name +
863 "' has already been defined on blocks '" + Moose::stringify(blocks) + "'.");
864 else
865 return false;
866 }
867
868 // Partial overlap between Physics is not implemented.
869 mooseError("There is a partial overlap between the subdomains covered by pre-existing time "
870 "derivative kernel(s), defined on blocks (ids): " +
871 Moose::stringify(getSubdomainNamesAndIDs(blocks_ids_covered)) +
872 "\nand a newly created time derivative kernel for variable " + var_name +
873 ", to be defined on blocks: " + Moose::stringify(blocks) +
874 ".\nWe should be creating the Physics' time derivative only for non-covered "
875 "blocks. This is not implemented at this time.");
876}
877
878void
879PhysicsBase::reportPotentiallyMissedParameters(const std::vector<std::string> & param_names,
880 const std::string & object_type,
881 const std::string & object_name) const
882{
883 std::vector<std::string> defaults_unused;
884 std::vector<std::string> user_values_unused;
885 for (const auto & param : param_names)
886 {
887 if (isParamSetByUser(param))
888 user_values_unused.push_back(param);
889 else if (isParamValid(param))
890 defaults_unused.push_back(param);
891 }
892 const std::string object_name_string =
893 object_name.empty() ? "" : ("and name '" + object_name + "' ");
894
895 if (defaults_unused.size() && _verbose)
896 mooseInfoRepeated("Defaults for parameters '" + Moose::stringify(defaults_unused) +
897 "' for object of type '" + object_type + "' " + object_name_string +
898 "were not used because the object was not created by this Physics.");
899 if (user_values_unused.size())
900 {
903 "User-specifed values for parameters '" + Moose::stringify(user_values_unused) +
904 "' for object of type '" + object_type + "' " + object_name_string +
905 "were not used because the corresponding object was not created by this Physics.");
906 else if (_app.unusedFlagIsError())
907 mooseError("User-specified values for parameters '" + Moose::stringify(user_values_unused) +
908 "' for object of type '" + object_type + "' " + object_name_string +
909 "were not used because the corresponding object was not created by this Physics.");
910 }
911}
void mooseInfoRepeated(Args &&... args)
Emit an informational message with the given stringified, concatenated args.
Definition MooseError.h:409
char ** blocks
Base class for components that are defined using an action.
const std::vector< SubdomainName > & blocks() const
Returns the subdomains for the component mesh, if any.
std::set< std::string > getTasksByAction(const std::string &action) const
const T & getAction(const std::string &name) const
Retrieve an action with its name and the desired type.
Base class for actions.
Definition Action.h:38
std::shared_ptr< MooseMesh > & _mesh
Definition Action.h:174
static InputParameters validParams()
Definition Action.C:26
MooseApp & _app
The MOOSE application this is associated with.
Definition MooseBase.h:375
bool addRelationshipManagers(Moose::RelationshipManagerType when_type, const InputParameters &moose_object_pars)
Method to add a relationship manager for the objects being added to the system.
Definition Action.C:148
std::shared_ptr< FEProblemBase > & _problem
Convenience reference to a problem this action works on.
Definition Action.h:178
const std::string & _current_task
The current action (even though we have separate instances for each action)
Definition Action.h:172
ActionWarehouse & _awh
Reference to ActionWarehouse where we store object build by actions.
Definition Action.h:169
An interface that restricts an object to subdomains via the 'blocks' input parameter.
virtual std::vector< std::shared_ptr< UserObject > > addUserObject(const std::string &user_object_name, const std::string &name, InputParameters &parameters)
virtual const SystemBase & systemBaseAuxiliary() const override
Return the auxiliary system object as a base class reference.
void setVerboseProblem(bool verbose)
Make the problem be verbose.
unsigned int solverSysNum(const SolverSystemName &solver_sys_name) const override
const std::vector< LinearSystemName > & getLinearSystemNames() const
const std::vector< NonlinearSystemName > & getNonlinearSystemNames() const
virtual bool isTransient() const override
virtual const SystemBase & getSystemBase(const unsigned int sys_num) const
Get constant reference to a system in this problem.
InputParameters getValidParams(const std::string &name) const
Get valid parameters for the object.
Definition Factory.C:68
Utility class to help check parameters.
void checkSecondParamSetOnlyIfFirstOneTrue(const std::string &param1, const std::string &param2) const
Check that a parameter is set only if the first one is set to true.
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
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 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 addClassDescription(const std::string &doc_string)
This method adds a description of the class that will be displayed in the input file syntax dump.
T & set(const std::string &name, bool quiet_mode=false)
Returns a writable reference to the named parameters.
Linear system to be solved.
bool unusedFlagIsError() const
Returns whether the flag for unused parameters is set to throw an error.
Definition MooseApp.h:1124
void setExodusFileRestart(bool flag)
Set the flag to indicate whether or not we need to use a separate Exodus reader to read the mesh BEFO...
Definition MooseApp.h:434
bool isRestarting() const
Whether or not this is a "restart" calculation.
Definition MooseApp.C:1684
bool isRecovering() const
Whether or not this is a "recover" calculation.
Definition MooseApp.C:1678
bool unusedFlagIsWarning() const
Returns whether the flag for unused parameters is set to throw a warning only.
Definition MooseApp.h:1121
const std::string & type() const
Get the type of this class.
Definition MooseBase.h:93
const std::string & name() const
Get the name of the class.
Definition MooseBase.h:103
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:457
bool isParamSetByUser(const std::string &name) const
Test if the supplied parameter is set by a user, as opposed to not set or set to default.
Definition MooseBase.h:205
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
bool isParamValid(const std::string &name) const
Test if the supplied parameter is valid.
Definition MooseBase.h:199
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition MooseEnum.h:55
A struct for storing the various types of petsc options and values.
ActionFactory & _action_factory
Builds Actions.
Base class to help creating an entire physics.
Definition PhysicsBase.h:31
bool solverVariableExists(const VariableName &var_name) const
Check whether a variable already exists and is a solver variable.
void addSharedAuxVariable(const std::string &var_type, const VariableName &var_name, const InputParameters &params)
Same as addSharedSolverVariable() but for an auxiliary variable, from addAuxiliaryVariables()
const std::vector< VariableName > & auxVariableNames() const
Return the list of aux variables in this physics.
unsigned int _dim
Dimension of the physics, which we expect for now to be the dimension of the mesh NOTE: this is not k...
virtual void addFVBCs()
virtual void addReporters()
virtual void addCorrectors()
void addPetscPairsToPetscOptions(const std::vector< std::pair< MooseEnumItem, std::string > > &petsc_pair_options)
Process the given petsc option pairs into the system solver settings.
static InputParameters validParams()
Definition PhysicsBase.C:25
virtual void checkIntegrity() const
Additional checks performed near the end of the setup phase.
virtual void addFunctions()
virtual void actOnAdditionalTasks()
Routine to add additional setup work on additional registered tasks to a Physics.
Definition PhysicsBase.h:49
virtual void addExecutors()
virtual void addFVInterpolationMethods()
virtual void addMultiApps()
std::set< std::string > _required_tasks
Manually keeps track of the tasks required by each physics as tasks cannot be inherited.
virtual void addExecutioner()
void addBlocksById(const std::vector< SubdomainID > &block_ids)
virtual FEProblemBase & getProblem()
Get the problem for this physics Useful to add objects to the simulation.
void addBlocks(const std::vector< SubdomainName > &blocks)
Add new blocks to the Physics.
std::vector< SolverSystemName > _system_names
System names for the system(s) owning the solver variables.
std::vector< VariableName > _solver_var_names
Vector of the solver variables (nonlinear and linear) in the Physics.
void addUserObject(const std::string &uo_type, const std::string &uo_name, InputParameters &params)
Add a UserObject supplied by this Physics to the problem.
Factory & getFactory()
Get the factory for this physics The factory lets you get the parameters for objects.
std::vector< unsigned int > _system_numbers
System numbers for the system(s) owning the solver variables.
bool shouldCreateIC(const VariableName &var_name, const std::vector< SubdomainName > &blocks, const bool ic_is_default_ic, const bool error_if_already_defined) const
Returns whether this Physics should create the variable.
bool checkBlockRestrictionIdentical(const std::string &object_name, const std::vector< SubdomainName > &blocks, const bool error_if_not_identical=true) const
Check if an external object has the same block restriction.
virtual void addTransfers()
virtual void addOutputs()
bool allMeshBlocks(const std::vector< SubdomainName > &blocks) const
Check if a vector contains all the mesh blocks.
virtual void addInitialConditions()
virtual void addFEBCs()
bool shouldCreateTimeDerivative(const VariableName &var_name, const std::vector< SubdomainName > &blocks, const bool error_if_already_defined) const
Returns whether this Physics should create the variable.
virtual void addFVInterfaceKernels()
std::set< SubdomainID > getSubdomainIDs(const std::set< SubdomainName > &blocks) const
Get the set of subdomain ids for the incoming vector of subdomain names.
virtual void addAuxiliaryKernels()
virtual void addNodalKernels()
void initializePhysics()
Process some parameters that require the problem to be created. Executed on init_physics.
void assignBlocks(InputParameters &params, const std::vector< SubdomainName > &blocks) const
Set the blocks parameter to the input parameters of an object this Physics will create.
unsigned int dimension() const
Return the maximum dimension of the blocks the Physics is active on.
virtual void checkIntegrityEarly() const
Additional checks performed once the executioner / executor has been created.
void reportPotentiallyMissedParameters(const std::vector< std::string > &param_names, const std::string &object_type, const std::string &object_name="") const
When this is called, we are knowingly not using the value of these parameters.
void saveSolverVariableName(const VariableName &var_name)
Keep track of the name of the solver variable defined in the Physics.
const std::vector< VariableName > & solverVariableNames() const
Return the list of solver (nonlinear + linear) variables in this physics.
virtual void addScalarKernels()
void copyVariablesFromMesh(const std::vector< VariableName > &variables_to_copy, bool are_nonlinear=true)
Copy nonlinear or aux variables from the mesh file.
virtual void addComponent(const ActionComponent &component)
Most basic way of adding a component: simply adding the blocks to the block restriction of the Physic...
void prepareCopyVariablesFromMesh() const
Tell the app if we want to use Exodus restart.
std::vector< std::string > getSubdomainNamesAndIDs(const std::set< SubdomainID > &blocks) const
Get the vector of subdomain names and ids for the incoming set of subdomain IDs.
virtual void addPostprocessors()
virtual void addUserObjects()
virtual void addDiracKernels()
virtual void initializePhysicsAdditional()
Additional initialization work that should happen very early, as soon as the problem is created.
virtual void act() override final
Forwards from the action tasks to the implemented addXYZ() in the derived classes If you need more th...
bool variableExists(const VariableName &var_name, bool error_if_aux) const
Check whether a variable already exists.
virtual void addVectorPostprocessors()
virtual void addAuxiliaryVariables()
virtual void addPreconditioning()
MooseEnum _is_transient
Whether the physics is to be solved as a transient.
bool hasBlocks(const std::vector< SubdomainName > &blocks) const
Whether the Physics is defined on those blocks.
std::vector< VariableName > _aux_var_names
Vector of the aux variables in the Physics.
virtual std::vector< UserObjectName > getSuppliedUserObjects() const
Return the names of the UserObjects this Physics adds to the problem.
const SolverSystemName & getSolverSystem(unsigned int variable_index) const
Get the solver system for this variable index.
PhysicsBase(const InputParameters &parameters)
void addSharedSolverVariable(const std::string &var_type, const VariableName &var_name, InputParameters params)
Requests a solver variable that may be shared with other Physics, on the blocks of this Physics.
virtual void addFunctorMaterials()
void saveAuxVariableName(const VariableName &var_name)
Keep track of the name of an aux variable defined in the Physics.
bool shouldCreateVariable(const VariableName &var_name, const std::vector< SubdomainName > &blocks, const bool error_if_aux)
Returns whether this Physics should create the variable.
const ActionComponent & getActionComponent(const ComponentName &comp_name) const
Get a component with the requested name.
virtual InputParameters getAdditionalRMParams() const
Provide additional parameters for the relationship managers.
Definition PhysicsBase.h:38
bool isVariableScalar(const VariableName &var_name) const
Whether the variable is a scalar variable (global single scalar, not a field)
virtual void addMaterials()
bool isVariableFV(const VariableName &var_name) const
Whether the variable is a finite volume variable.
virtual void addInterfaceKernels()
virtual void addFVKernels()
bool isTransient() const
Return whether the Physics is solved using a transient.
std::vector< SubdomainName > _blocks
Keep track of the subdomains the Physics is defined on.
const std::vector< SubdomainName > & blocks() const
Return the blocks this physics is defined on.
Definition PhysicsBase.h:60
virtual void addNodalBCs()
const bool _verbose
Whether to output additional information.
virtual void addFEKernels()
virtual void addRelationshipManagers(Moose::RelationshipManagerType input_rm_type) override
Method to add a relationship manager for the objects being added to the system.
virtual void addSolverVariables()
The default implementation of these routines will do nothing as we do not expect all Physics to be de...
void checkRequiredTasks() const
Check the list of required tasks for missing tasks.
virtual void addDGKernels()
void addRequiredPhysicsTask(const std::string &task)
Add a new required task for all physics deriving from this class NOTE: This does not register the tas...
virtual void addPeriodicBCs()
static PhysicsVariableCoordinator & findOrCreate(ActionWarehouse &awh, ActionFactory &action_factory)
Finds this simulation's coordinator, creating it and adding it to awh (using action_factory) if it do...
void requestVariable(bool nl, const std::string &var_type, const VariableName &var_name, const InputParameters &params, const std::vector< SubdomainName > &blocks, const std::string &requester)
Requests that a shared variable be created on blocks, in addition to any blocks already requested for...
void mooseWarning(Args &&... args) const
Base class for a system (of equations)
Definition SystemBase.h:87
virtual void addVariableToCopy(const std::string &dest_name, const std::string &source_name, const std::string &timestep)
Add info about variable that will be copied.
void addPetscPairsToPetscOptions(const std::vector< std::pair< MooseEnumItem, std::string > > &petsc_pair_options, const unsigned int mesh_dimension, std::string prefix, const ParallelParamObject &param_object, PetscOptions &petsc_options)
Populate name and value pairs in a given PetscOptions object using vectors of input arguments.
std::string stringify(const T &t)
conversion to string
Definition Conversion.h:65
RelationshipManagerType
Main types of Relationship Managers.