32shapeToMooseType(
const std::vector<int64_t> & s)
36 if (s == std::vector<int64_t>{3})
37 return "RealVectorValue";
38 if (s == std::vector<int64_t>{6})
39 return "SymmetricRankTwoTensor";
40 if (s == std::vector<int64_t>{3, 3})
41 return "RankTwoTensor";
42 if (s == std::vector<int64_t>{6, 6})
43 return "SymmetricRankFourTensor";
44 if (s == std::vector<int64_t>{3, 3, 3, 3})
45 return "RankFourTensor";
50std::map<std::string, std::vector<int64_t>>
51shapeMap(
const std::vector<std::string> & names,
const std::vector<std::vector<int64_t>> & shapes)
53 std::map<std::string, std::vector<int64_t>> m;
54 for (std::size_t i = 0; i < names.size(); ++i)
55 m[names[i]] = shapes[i];
70 params.
addParam<std::string>(
"executor_name",
71 "Name of the NEML2ModelExecutor user object. The default name is "
72 "'neml2_<model-name>_<block-name>' where <model-name> is the NEML2 "
73 "model's name, and <block-name> is this action sub-block's name.");
75 "batch_index_generator_name",
76 "Name of the NEML2BatchIndexGenerator user object. The default name is "
77 "'neml2_index_<model-name>_<block-name>' where <model-name> is the NEML2 model's name, and "
78 "<block-name> is this action sub-block's name.");
79 params.
addParam<std::vector<SubdomainName>>(
80 "block", {},
"List of blocks (subdomains) where the material model is defined");
86 _executor_name(isParamValid(
"executor_name")
87 ? getParam<
std::string>(
"executor_name")
88 :
"neml2_" + getParam<
std::string>(
"model") +
"_" + name()),
89 _idx_generator_name(isParamValid(
"batch_index_generator_name")
90 ? getParam<
std::string>(
"batch_index_generator_name")
91 :
"neml2_index_" + getParam<
std::string>(
"model") +
"_" + name()),
92 _block(getParam<
std::vector<SubdomainName>>(
"block")),
93 _skip_input_variables(getParam<
std::vector<
std::string>>(
"skip_input_variables"))
99 auto & sub_block_params = *(all_params.find(
uniqueActionName())->second.get());
101 sub_block_params.applyParameters(common_action.parameters());
104 auto init_vars = getParam<std::vector<MaterialPropertyName>>(
"initialize_outputs");
105 auto init_vals = getParam<std::vector<MaterialPropertyName>>(
"initialize_output_values");
106 if (init_vars.size() != init_vals.size())
108 "initialize_outputs should have the same length as initialize_output_values");
109 for (
auto i : index_range(init_vars))
113 auto outputs = getParam<std::vector<MaterialPropertyName>>(
"export_outputs");
114 auto output_targets = getParam<std::vector<std::vector<OutputName>>>(
"export_output_targets");
115 if (outputs.size() != output_targets.size())
117 "export_outputs should have the same length as export_output_targets");
118 for (
auto i : index_range(outputs))
125 _cli_args = getParam<std::vector<std::string>>(
"cli_args");
131 const bool eager = getParam<bool>(
"eager");
132 const auto load_files = getParam<std::vector<DataFileName>>(
"load");
137 "'input' (the NEML2 source '.i' for cpp-eager, or the neml2-compile artifact folder for "
138 "cpp-aoti) is required.");
139 if (!eager && !load_files.empty())
141 "The 'load' parameter is only valid with the cpp-eager runtime (eager=true).");
145 auto devices = getParam<std::vector<std::string>>(
"device");
148 auto db = getParam<std::vector<unsigned int>>(
"device_batch");
151 if (db.size() != 1 && db.size() != devices.size())
152 paramError(
"device_batch",
"'device_batch' must have length 1 or the same length as 'device'.");
153 const std::vector<std::size_t> batch_sizes(db.begin(), db.end());
156 const auto mpi_comm =
comm().
get();
158 _fname = getParam<DataFileName>(
"input");
161 getParam<std::string>(
"model"),
165 std::vector<std::string>(load_files.begin(), load_files.end()));
173 mooseAssert(common_block.size() == 1,
"There must exist one and only one common NEML2 action.");
174 return *common_block[0];
188 const std::string & prefix,
189 const std::string & suffix,
190 const std::string & block)
192 return "__" + prefix +
"_" + name +
"_" + suffix +
"_" + block +
"__";
219 auto addGatherer = [&](
const std::string & moose_name,
220 const std::string & neml2_name,
222 const std::string & moose_tensor_type,
223 const std::string & suffix,
224 const std::string & type_prefix =
"")
227 auto obj_type =
"MOOSE" + type_prefix + moose_tensor_type +
"ToNEML2";
229 obj_params.
set<std::string>(
"from_moose") = moose_name;
230 obj_params.set<std::string>(
"to_neml2") = neml2_name;
231 obj_params.set<
MooseEnum>(
"quantity_type").assign(
static_cast<int>(moose_type));
232 obj_params.set<std::vector<SubdomainName>>(
"block") =
_block;
233 _problem->addUserObject(obj_type, obj_name, obj_params);
240 std::vector<UserObjectName> gatherers;
241 for (
const auto & input :
_inputs)
242 gatherers.push_back(addGatherer(input.
name,
245 input.moose_tensor_type,
246 std::to_string(input.history_order),
247 input.history_order == 1 ?
"Old" :
""));
250 for (
const auto & kernel_name :
getParam<
std::vector<
std::string>>(
"input_kernels"))
256 " name does not match any NEML2 input variable.");
257 gatherers.push_back(kernel_name);
263 std::vector<UserObjectName> param_gatherers;
264 for (
const auto & param :
_params)
265 param_gatherers.push_back(addGatherer(
266 param.moose_name, param.neml2_name, param.moose_type, param.moose_tensor_type,
"param"));
270 auto type =
"NEML2BatchIndexGenerator";
278 auto type =
"NEML2ModelExecutor";
282 params.set<std::vector<UserObjectName>>(
"gatherers") = gatherers;
283 params.set<std::vector<UserObjectName>>(
"param_gatherers") = param_gatherers;
292 auto addRetriever = [&](
const std::string & moose_name,
293 const std::string & neml2_var,
294 const std::string & moose_tensor_type,
298 auto obj_type =
"NEML2ToMOOSE" + moose_tensor_type +
"MaterialProperty";
301 obj_params.set<MaterialPropertyName>(
"to_moose") = moose_name;
302 obj_params.set<std::string>(
"from_neml2") = neml2_var;
303 obj_params.set<std::vector<SubdomainName>>(
"block") =
_block;
307 _problem->addMaterial(obj_type, obj_name, obj_params);
311 for (
const auto & output :
_outputs)
315 "Unsupported type corresponding to the moose output ",
317 addRetriever(output.name,
319 output.moose_tensor_type,
322 if (_initialize_output_values.count(output.name))
323 p.set<MaterialPropertyName>(
"moose_material_property_init") =
324 _initialize_output_values[output.name];
329 for (
const auto & deriv :
_derivs)
332 deriv.moose_tensor_type,
334 { p.set<std::string>(
"neml2_input_derivative") =
deriv.x; });
340 deriv.moose_tensor_type,
342 { p.set<std::string>(
"neml2_parameter_derivative") =
deriv.x; });
356 if (
int(is_time) +
int(has_scalar) +
int(has_func) +
int(has_var) > 1)
357 mooseError(
"Trying to infer MOOSE data type for NEML2 variable ",
359 ". The name matches multiple types (",
360 (is_time ?
"time " :
""),
361 (has_scalar ?
"scalar variable " :
""),
362 (has_func ?
"function " :
""),
363 (has_var ?
"variable " :
""),
364 "). To avoid ambiguity, please explicitly specify the type in the NEML2 action.");
385 const auto & kernels = getParam<std::vector<std::string>>(
"input_kernels");
386 const auto & explicit_inputs = getParam<std::vector<std::string>>(
"inputs");
392 const auto [base, order] = parseLag(vname);
399 if (contains(kernels, vname))
403 if (getParam<bool>(
"manage_state_advance") && order > 0)
412 if (order == 0 && contains(model.
output_names(), vname) && !contains(explicit_inputs, vname))
416 "' is also a model output (an in-place-updated unknown), so it is cold-started at "
417 "zero on every evaluation instead of gathered from its stale output material. To "
418 "supply an explicit initial guess instead, map it via 'inputs'/'moose_inputs'.");
422 const auto & base_shape = in_shapes.at(vname);
423 const auto mtype = shapeToMooseType(base_shape);
426 "NEML2 input variable ", vname,
" has a base shape not yet mapped to a MOOSE type.");
429 {base,
inferMOOSEIOType(base, base_shape.empty()), mtype,
static_cast<std::size_t
>(order)});
433 const auto [input_types, inputs] =
434 getInputParameterMapping<NEML2Utils::MOOSEIOType, std::string>(
"input_types",
"inputs");
436 for (
auto i : index_range(inputs))
438 const auto base_i = parseLag(inputs[i]).first;
442 "The input variable ",
444 " is listed in skip_input_variables, but it also appears in inputs. Please "
445 "remove it from either list.");
448 paramError(
"inputs",
"The neml2 input variable ", inputs[i],
" does not exist.");
450 if (contains(kernels, inputs[i]))
452 "The input variable ",
454 " is listed in inputs, but it also appears in input_kernels. Please "
455 "remove it from either list.");
457 if (getParam<bool>(
"manage_state_advance") && parseLag(inputs[i]).second > 0)
459 "The input variable ",
461 " is listed in inputs, but it is an old (stateful) variable and "
462 "manage_state_advance is true. Please remove it from inputs, or set "
463 "manage_state_advance to false.");
467 if (input.name == base_i)
469 input.moose_type = input_types[i];
478 if (!getParam<bool>(
"auto_output"))
485 const auto mtype = shapeToMooseType(out_shapes.at(oname));
488 "NEML2 output variable ", oname,
" has a base shape not yet mapped to a MOOSE type.");
496 const auto derivs = getParam<std::vector<std::vector<std::string>>>(
"derivatives");
500 for (
auto i : index_range(derivs))
502 if (derivs[i].size() != 2 && derivs[i].size() != 3)
504 "Each entry in derivatives must have 2 elements (output, input) or 3 "
505 "(output, input, alias).");
507 const auto & y = derivs[i][0];
508 const auto & x = derivs[i][1];
510 paramError(
"derivatives",
"The NEML2 output variable ", y,
" does not exist.");
512 paramError(
"derivatives",
"The NEML2 input variable ", x,
" does not exist.");
515 std::vector<int64_t> dshape = out_shapes.at(y);
516 const auto & xs = in_shapes.at(x);
517 dshape.insert(dshape.end(), xs.begin(), xs.end());
518 const auto mtype = shapeToMooseType(dshape);
524 " has a base shape not yet mapped to a MOOSE type.");
527 const MaterialPropertyName deriv_name = derivs[i].size() == 3
528 ? MaterialPropertyName(derivs[i][2])
530 _derivs.push_back({deriv_name, y, x, mtype});
536 const std::string & user_name,
537 const std::map<std::string, std::vector<int64_t>> & param_shapes)
const
539 std::vector<std::string> param_names;
540 for (
const auto & [p, s] : param_shapes)
541 param_names.push_back(p);
543 if (contains(param_names, user_name))
547 std::vector<std::string> matches;
548 const std::string suffix =
"." + user_name;
549 for (
const auto & p : param_names)
550 if (p.size() > suffix.size() && p.compare(p.size() - suffix.size(), suffix.size(), suffix) == 0)
551 matches.push_back(p);
553 if (matches.size() == 1)
556 std::string available;
557 for (
const auto & p : param_names)
558 available += (available.empty() ?
"" :
", ") + p;
559 if (matches.size() > 1)
562 for (
const auto & x : matches)
563 m += (m.empty() ?
"" :
", ") + x;
564 mooseError(
"The NEML2 model parameter name '",
566 "' is ambiguous; it matches multiple registered parameters: ",
568 ". Use the fully-qualified name.");
572 "' does not exist. Available model parameters: ",
579 const auto [param_types, params] = getInputParameterMapping<NEML2Utils::MOOSEIOType, std::string>(
580 "parameter_types",
"parameters");
583 for (
auto i : index_range(params))
586 const auto mtype = shapeToMooseType(pshapes.at(qn));
589 "The NEML2 model parameter ", qn,
" has a base shape not yet mapped to a MOOSE type.");
590 _params.push_back({params[i], qn, param_types[i], mtype});
597 const auto derivs = getParam<std::vector<std::vector<std::string>>>(
"parameter_derivatives");
601 for (
auto i : index_range(derivs))
603 if (derivs[i].size() != 2 && derivs[i].size() != 3)
605 "Each entry in parameter_derivatives must have 2 elements (output, parameter) "
606 "or 3 (output, parameter, alias).");
608 const auto & y = derivs[i][0];
609 const auto & x_user = derivs[i][1];
611 paramError(
"parameter_derivatives",
"The NEML2 output variable ", y,
" does not exist.");
616 std::vector<int64_t> dshape = out_shapes.at(y);
617 const auto & xs = pshapes.at(x);
618 dshape.insert(dshape.end(), xs.begin(), xs.end());
619 const auto mtype = shapeToMooseType(dshape);
623 " with respect to model parameter ",
625 " has a base shape not yet mapped to a MOOSE type.");
629 const MaterialPropertyName deriv_name = derivs[i].size() == 3
630 ? MaterialPropertyName(derivs[i][2])
640 auto names_list = [](
const std::vector<std::string> & names)
643 for (
const auto & n : names)
644 s += (s.empty() ?
"" :
", ") + n;
653 const std::string out_name = pair.first;
658 "' is not an output of the NEML2 model and therefore cannot be initialized. "
659 "Available model outputs are: ",
673 for (
const auto & input :
_inputs)
677 "The NEML2 model takes the old value of '",
680 lagName(input.name, input.history_order),
681 ") as an input, but the model neither takes '",
683 "' as a current input nor produces it as an output, so MOOSE has no source for its "
686 "' is a state variable, add it to the model's 'additional_outputs' in the NEML2 "
687 "input file so that the model produces it. Model inputs: ",
704 const int width = 79;
707 _console << COLOR_CYAN << std::setw(width) << std::setfill(
'*') << std::left
708 <<
"NEML2 MATERIAL MODEL SUMMARY BEGIN " << std::setfill(
' ') << COLOR_DEFAULT
712 _console <<
"NEML2 input file location: " <<
fname() << std::endl;
716 _console << COLOR_CYAN << std::setw(width) << std::setfill(
'-') << std::left
717 <<
"Material model structure " << std::setfill(
' ') << COLOR_DEFAULT << std::endl;
718 _console <<
"NEML2 model inputs:" << std::endl;
719 for (
const auto & iname :
_model->input_names())
720 _console <<
" - " << iname << std::endl;
721 _console <<
"NEML2 model outputs:" << std::endl;
722 for (
const auto & oname :
_model->output_names())
723 _console <<
" - " << oname << std::endl;
728 _console << COLOR_CYAN << std::setw(width) << std::setfill(
'-') << std::left
729 <<
"Transfer between MOOSE and NEML2 " << std::setfill(
' ') << COLOR_DEFAULT
732 _console <<
"MOOSE --> NEML2" << std::endl;
735 for (
const auto & input :
_inputs)
736 _console <<
" - " << (input.history_order > 0 ? (
"(old) " + input.name) : input.name) <<
" ("
739 _console <<
"MOOSE <-- NEML2" << std::endl;
742 for (
const auto & output :
_outputs)
743 _console <<
" - " << output.name << std::endl;
746 for (
const auto & deriv :
_derivs)
747 _console <<
" - " << deriv.name << std::endl;
750 _console << COLOR_CYAN << std::setw(width) << std::setfill(
'*') << std::left
751 <<
"NEML2 MATERIAL MODEL SUMMARY END " << std::setfill(
' ') << COLOR_DEFAULT << std::endl
761 std::size_t max_moose_name_length = 0;
762 for (
const auto & input :
_inputs)
764 auto n = input.name.size();
765 if (input.history_order > 0)
767 max_moose_name_length = std::max(max_moose_name_length, n);
769 for (
const auto & output :
_outputs)
770 max_moose_name_length = std::max(max_moose_name_length, output.name.size());
771 for (
const auto & deriv :
_derivs)
772 max_moose_name_length = std::max(max_moose_name_length, deriv.name.size());
773 return max_moose_name_length;
static std::string obscureObjectName(const std::string &name, const std::string &prefix, const std::string &suffix, const std::string &block)
registerMooseAction("MooseApp", NEML2Action, "parse_neml2")
std::unique_ptr< NEML2ModelHandle > makeNEML2ModelHandle(bool eager, const std::string &input, const std::string &model, const std::vector< std::string > &devices, const std::vector< std::size_t > &batch_sizes, const void *comm, const std::vector< std::string > &load)
Construct a NEML2 model handle for the requested runtime.
void ErrorVector unsigned int
std::vector< const T * > getActions()
Retrieve all actions in a specific type ordered by their names.
MooseObjectName uniqueActionName() const
The unique name for accessing input parameters of this action in the InputParameterWarehouse.
MooseApp & _app
The MOOSE application this is associated with.
std::shared_ptr< FEProblemBase > & _problem
Convenience reference to a problem this action works on.
const std::string & _current_task
The current action (even though we have separate instances for each action)
ActionWarehouse & _awh
Reference to ActionWarehouse where we store object build by actions.
const ConsoleStream _console
An instance of helper class to write streams to the Console objects.
std::ios_base::fmtflags flags() const
Return the current flags.
const MaterialPropertyName derivativePropertyNameFirst(const MaterialPropertyName &base, const SymbolName &c1) const
Helper functions to generate the material property names for the first derivatives.
InputParameters getValidParams(const std::string &name) const
Get valid parameters for the object.
torch::DeviceType getLibtorchDevice() const
Get the device torch is supposed to be running on.
InputParameterWarehouse & getInputParameterWarehouse()
Get the InputParameterWarehouse for MooseObjects.
const InputParameters & parameters() const
Get the parameters of the object.
const std::string & type() const
Get the type of this class.
const std::string & name() const
Get the name of the class.
void paramError(const std::string ¶m, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
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...
const T & getParam(const std::string &name) const
Retrieve a parameter for the object.
void mooseInfo(Args &&... args) const
bool isParamValid(const std::string &name) const
Test if the supplied parameter is valid.
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Input parameters common to all block-restricted NEML2Actions.
static InputParameters commonParams()
Parameters that can be specified EITHER under the common area OR under sub-blocks.
Action to set up NEML2 objects.
std::vector< ParameterMapping > _params
MOOSE-NEML2 model parameter (value) mappings.
void setupParameterDerivativeMappings(const NEML2ModelHandle &)
Set up MOOSE-NEML2 output-parameter-derivative mappings.
void setupInputMappings(const NEML2ModelHandle &)
Set up MOOSE-NEML2 input variable mappings.
std::vector< VariableMapping > _inputs
MOOSE-NEML2 input variable mappings.
const FileName & fname() const
void setupOutputMappings(const NEML2ModelHandle &)
Set up MOOSE-NEML2 output variable mappings.
const NEML2ActionCommon & getCommonAction() const
std::vector< std::string > _skip_input_variables
Input variables to skip (i.e., not to set up mappings for)
std::vector< std::string > _cli_args
List of cli-args.
void setupParameterMappings(const NEML2ModelHandle &)
Set up MOOSE-NEML2 model parameter (value) mappings.
NEML2Action(const InputParameters &)
std::vector< DerivativeMapping > _param_derivs
MOOSE-NEML2 output-parameter-derivative mappings.
static InputParameters validParams()
std::unique_ptr< NEML2ModelHandle > _model
The neml2 model handle, used here only for introspection during setup.
const UserObjectName _idx_generator_name
Name of the NEML2BatchIndexGenerator user object.
void printSummary() const
Print a summary of the NEML2 model.
void setupDerivativeMappings(const NEML2ModelHandle &)
Set up MOOSE-NEML2 derivative mappings.
std::map< MaterialPropertyName, std::vector< OutputName > > _export_output_targets
Material property additional outputs.
std::vector< VariableMapping > _outputs
MOOSE-NEML2 output variable mappings.
void checkStatefulConsistency(const NEML2ModelHandle &) const
Validate consistency between the action configuration and the model's I/O before MOOSE wires up (stat...
const std::vector< SubdomainName > _block
Blocks this sub-block action applies to.
virtual void act() override
Method to add objects to the simulation or perform other setup tasks.
const UserObjectName _executor_name
Name of the NEML2Executor user object.
NEML2Utils::MOOSEIOType inferMOOSEIOType(const std::string &name, bool is_scalar) const
Infer the MOOSE IO type from the variable name (only scalar-typed variables can map to time/scalar/fu...
std::vector< DerivativeMapping > _derivs
MOOSE-NEML2 derivative mappings.
std::map< MaterialPropertyName, MaterialPropertyName > _initialize_output_values
Material property initial conditions.
FileName _fname
Name of the NEML2 input file.
std::string resolveParameterName(const std::string &user_name, const std::map< std::string, std::vector< int64_t > > ¶m_shapes) const
Resolve a user-written parameter name to a fully-qualified NEML2 parameter name.
std::size_t getLongestMOOSEName() const
Get the maximum length of all MOOSE names (for printing purposes)
Runtime-agnostic handle over a NEML2 v3 model.
virtual const std::vector< std::string > & input_names() const =0
virtual const std::vector< std::vector< int64_t > > & output_base_shapes() const =0
virtual const std::map< std::string, std::vector< int64_t > > & parameter_base_shapes() const =0
virtual const std::vector< std::vector< int64_t > > & input_base_shapes() const =0
virtual const std::vector< std::string > & output_names() const =0
Factory & _factory
The Factory associated with the MooseApp.
const Parallel::Communicator & comm() const
bool contains(const std::vector< std::string > &v, const std::string &s)
Whether a vector of strings contains a given string.
std::pair< std::string, int > parseLag(const std::string &name)
Parse NEML2 v3 lag notation: "var~N" is the N-th old value of a variable (var~1 == old var,...
void redirectLogsToConsole(const ConsoleStream &console)
Route NEML2's log output into MOOSE's console.
std::string lagName(const std::string &base, int lag)
Inverse of parseLag: build the variable name for a base name + lag.
void assertNEML2Enabled()
Assert that NEML2 is enabled.
std::string stringify(MOOSEIOType type)
Real deriv(unsigned n, unsigned alpha, unsigned beta, Real x)
bool contains(std::string_view superstring, std::string_view substring)