https://mooseframework.inl.gov
Loading...
Searching...
No Matches
NEML2Action.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 "NEML2Action.h"
11#include "NEML2ActionCommon.h"
12#include "FEProblem.h"
13#include "Factory.h"
14#include "NEML2Utils.h"
16
17#ifdef NEML2_ENABLED
18#include <algorithm>
19
20// parseLag / lagName / contains are shared with NEML2ModelExecutor and live in NEML2Utils so the
21// NEML2 unity build does not see duplicate definitions.
25
26namespace
27{
28// Map a NEML2 variable base shape to the corresponding MOOSE C++ tensor type string. Returns an
29// empty string if the shape is not (yet) supported. A derivative block's type is obtained by
30// passing the concatenation of the output and input base shapes.
31std::string
32shapeToMooseType(const std::vector<int64_t> & s)
33{
34 if (s.empty())
35 return "Real";
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";
46 return "";
47}
48
49// Build a name -> base-shape lookup for the model's inputs / outputs.
50std::map<std::string, std::vector<int64_t>>
51shapeMap(const std::vector<std::string> & names, const std::vector<std::vector<int64_t>> & shapes)
52{
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];
56 return m;
57}
58}
59#endif
60
61registerMooseAction("MooseApp", NEML2Action, "parse_neml2");
62registerMooseAction("MooseApp", NEML2Action, "add_material");
63registerMooseAction("MooseApp", NEML2Action, "add_user_object");
64
67{
69 params.addClassDescription("Set up the NEML2 material model");
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.");
74 params.addParam<std::string>(
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");
81 return params;
82}
83
85 : Action(params),
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"))
94{
96
97 // Apply parameters under the common area, i.e., under [NEML2]
98 const auto & all_params = _app.getInputParameterWarehouse().getInputParameters();
99 auto & sub_block_params = *(all_params.find(uniqueActionName())->second.get());
100 const auto & common_action = getCommonAction();
101 sub_block_params.applyParameters(common_action.parameters());
102
103 // Set up optional output variable initialization
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())
107 paramError("initialize_outputs",
108 "initialize_outputs should have the same length as initialize_output_values");
109 for (auto i : index_range(init_vars))
110 _initialize_output_values[init_vars[i]] = init_vals[i];
111
112 // Set up additional outputs for each requested material property
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())
116 paramError("export_outputs",
117 "export_outputs should have the same length as export_output_targets");
118 for (auto i : index_range(outputs))
119 _export_output_targets[outputs[i]] = output_targets[i];
120
121#ifdef NEML2_ENABLED
122 // Route NEML2's log output to MOOSE's console before any model is built/introspected.
124
125 _cli_args = getParam<std::vector<std::string>>("cli_args");
126
127 // Build a model handle for setup-time introspection only (reading I/O names + base shapes to
128 // wire the MOOSE<->NEML2 transfers). cpp-eager reads the source 'input' (importing any 'load'
129 // Python extensions); cpp-aoti reads the compiled-artifact folder 'input'. 'cli_args' is
130 // currently not forwarded (NEML2 v3's load takes no extra parse arguments).
131 const bool eager = getParam<bool>("eager");
132 const auto load_files = getParam<std::vector<DataFileName>>("load");
133
134 if (!isParamValid("input"))
136 "input",
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())
140 paramError("load",
141 "The 'load' parameter is only valid with the cpp-eager runtime (eager=true).");
142
143 // Device list (default app device) + per-device chunk sizes; mirrors NEML2ModelInterface so the
144 // introspection handle and the runtime executor resolve devices identically.
145 auto devices = getParam<std::vector<std::string>>("device");
146 if (devices.empty())
147 devices = {at::Device(_app.getLibtorchDevice()).str()};
148 auto db = getParam<std::vector<unsigned int>>("device_batch");
149 if (db.empty())
150 db = {0};
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());
154
155 // Host MPI communicator for the cpp-aoti CUDA scheduler (read at construction only).
156 const auto mpi_comm = comm().get();
157
158 _fname = getParam<DataFileName>("input");
160 std::string(_fname),
161 getParam<std::string>("model"),
162 devices,
163 batch_sizes,
164 &mpi_comm,
165 std::vector<std::string>(load_files.begin(), load_files.end()));
166#endif
167}
168
169const NEML2ActionCommon &
171{
172 auto common_block = _awh.getActions<NEML2ActionCommon>();
173 mooseAssert(common_block.size() == 1, "There must exist one and only one common NEML2 action.");
174 return *common_block[0];
175}
176
177#ifndef NEML2_ENABLED
178
179void
183
184#else
185
186static std::string
187obscureObjectName(const std::string & name,
188 const std::string & prefix,
189 const std::string & suffix,
190 const std::string & block)
191{
192 return "__" + prefix + "_" + name + "_" + suffix + "_" + block + "__";
193}
194
195void
197{
198 if (_current_task == "parse_neml2")
199 {
200 if (_app.parameters().have_parameter<bool>("parse_neml2_only"))
201 if (!_app.parameters().get<bool>("parse_neml2_only"))
202 return;
203 printSummary();
204 }
205
206 if (_current_task == "add_user_object")
207 {
213
215
216 printSummary();
217
218 // Create and register a MOOSEToNEML2 gatherer user object, returning its name
219 auto addGatherer = [&](const std::string & moose_name,
220 const std::string & neml2_name,
221 NEML2Utils::MOOSEIOType moose_type,
222 const std::string & moose_tensor_type,
223 const std::string & suffix,
224 const std::string & type_prefix = "")
225 {
226 auto obj_name = obscureObjectName(moose_name, "moose_to_neml2", suffix, name());
227 auto obj_type = "MOOSE" + type_prefix + moose_tensor_type + "ToNEML2";
228 auto obj_params = _factory.getValidParams(obj_type);
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);
234 return obj_name;
235 };
236
237 // MOOSEToNEML2 input gatherers. The NEML2 target name carries the lag suffix (var~N); the
238 // MOOSE source is the un-lagged base name, and old (lag 1) values are read with the "Old"
239 // gatherer variant.
240 std::vector<UserObjectName> gatherers;
241 for (const auto & input : _inputs)
242 gatherers.push_back(addGatherer(input.name,
243 lagName(input.name, input.history_order),
244 input.moose_type,
245 input.moose_tensor_type,
246 std::to_string(input.history_order),
247 input.history_order == 1 ? "Old" : ""));
248
249 // Additional NEML2Kernels that provide input data
250 for (const auto & kernel_name : getParam<std::vector<std::string>>("input_kernels"))
251 {
252 if (!contains(_model->input_names(), kernel_name))
253 paramError("input_kernels",
254 "The NEML2 kernel ",
255 kernel_name,
256 " name does not match any NEML2 input variable.");
257 gatherers.push_back(kernel_name);
258 }
259
260 // MOOSEToNEML2 model-parameter gatherers (MOOSE data fed in as NEML2 model parameters). The
261 // NEML2 target is the fully-qualified parameter name; the MOOSE source is the user-written
262 // 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"));
267
268 // The index generator UO
269 {
270 auto type = "NEML2BatchIndexGenerator";
271 auto params = _factory.getValidParams(type);
272 params.applyParameters(parameters());
273 _problem->addUserObject(type, _idx_generator_name, params);
274 }
275
276 // The Executor UO
277 {
278 auto type = "NEML2ModelExecutor";
279 auto params = _factory.getValidParams(type);
280 params.applyParameters(parameters());
281 params.set<UserObjectName>("batch_index_generator") = _idx_generator_name;
282 params.set<std::vector<UserObjectName>>("gatherers") = gatherers;
283 params.set<std::vector<UserObjectName>>("param_gatherers") = param_gatherers;
284 _problem->addUserObject(type, _executor_name, params);
285 }
286 }
287
288 if (_current_task == "add_material")
289 {
290 // Create and register a NEML2ToMOOSE material property retriever; `extra` lets each caller
291 // add the bits that are unique to outputs vs. derivatives.
292 auto addRetriever = [&](const std::string & moose_name,
293 const std::string & neml2_var,
294 const std::string & moose_tensor_type,
295 auto && extra)
296 {
297 auto obj_name = obscureObjectName(moose_name, "neml2_to_moose", "", name());
298 auto obj_type = "NEML2ToMOOSE" + moose_tensor_type + "MaterialProperty";
299 auto obj_params = _factory.getValidParams(obj_type);
300 obj_params.set<UserObjectName>("neml2_executor") = _executor_name;
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;
304 if (_export_output_targets.count(moose_name))
305 obj_params.set<std::vector<OutputName>>("outputs") = _export_output_targets[moose_name];
306 extra(obj_params);
307 _problem->addMaterial(obj_type, obj_name, obj_params);
308 };
309
310 // NEML2ToMOOSE output retrievers
311 for (const auto & output : _outputs)
312 {
313 if (output.moose_type != NEML2Utils::MOOSEIOType::MATERIAL)
314 paramError("moose_output_types",
315 "Unsupported type corresponding to the moose output ",
316 output.name);
317 addRetriever(output.name,
318 output.name,
319 output.moose_tensor_type,
320 [&](InputParameters & p)
321 {
322 if (_initialize_output_values.count(output.name))
323 p.set<MaterialPropertyName>("moose_material_property_init") =
324 _initialize_output_values[output.name];
325 });
326 }
327
328 // NEML2ToMOOSE derivative retrievers
329 for (const auto & deriv : _derivs)
330 addRetriever(deriv.name,
331 deriv.y,
332 deriv.moose_tensor_type,
333 [&](InputParameters & p)
334 { p.set<std::string>("neml2_input_derivative") = deriv.x; });
335
336 // NEML2ToMOOSE parameter-derivative retrievers
337 for (const auto & deriv : _param_derivs)
338 addRetriever(deriv.name,
339 deriv.y,
340 deriv.moose_tensor_type,
341 [&](InputParameters & p)
342 { p.set<std::string>("neml2_parameter_derivative") = deriv.x; });
343 }
344}
345
347NEML2Action::inferMOOSEIOType(const std::string & name, bool is_scalar) const
348{
349 // only scalar-typed variables can come from a scalar variable, function, or field variable
350 if (is_scalar)
351 {
352 bool is_time = _problem->isTransient() && (name == "t" || name == "time");
353 bool has_scalar = _problem->hasScalarVariable(name);
354 bool has_func = _problem->hasFunction(name);
355 bool has_var = _problem->hasVariable(name);
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 ",
358 name,
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.");
365 if (is_time)
367 if (has_scalar)
369 if (has_func)
371 if (has_var)
373 // if neither function nor variable exists, let's assume it's a material property
374 // note that we can't explicitly check if a material property with the given name exists,
375 // because materials are added _after_ user objects (see Moose.C)
376 }
377
378 // non-scalar can only come from material properties
380}
381
382void
384{
385 const auto & kernels = getParam<std::vector<std::string>>("input_kernels");
386 const auto & explicit_inputs = getParam<std::vector<std::string>>("inputs");
387 const auto in_shapes = shapeMap(model.input_names(), model.input_base_shapes());
388
389 // Default mapping
390 for (const auto & vname : model.input_names())
391 {
392 const auto [base, order] = parseLag(vname);
393
394 // user requested to skip (by base name)
395 if (contains(_skip_input_variables, base))
396 continue;
397
398 // skip if the input is directly provided by a custom kernel (matched by full NEML2 name)
399 if (contains(kernels, vname))
400 continue;
401
402 // skip stateful (old) inputs when managing state advance on the compute device
403 if (getParam<bool>("manage_state_advance") && order > 0)
404 continue;
405
406 // An order-0 input that is ALSO a model output is an in-place-updated unknown (e.g. an
407 // ImplicitUpdate initial guess that has no old counterpart). The default gatherer would read
408 // its own stale output material -- the previous converged step's value -- as the "current"
409 // initial guess, warm-starting a rate-like unknown from a value that can prevent the return-map
410 // Newton solve from converging. Unless the user maps it explicitly, cold-start it at zero: skip
411 // the gatherer here and let the executor seed a base-shaped zero (broadcast over the batch).
412 if (order == 0 && contains(model.output_names(), vname) && !contains(explicit_inputs, vname))
413 {
414 mooseInfo("NEML2 input '",
415 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'.");
419 continue;
420 }
421
422 const auto & base_shape = in_shapes.at(vname);
423 const auto mtype = shapeToMooseType(base_shape);
424 if (mtype.empty())
426 "NEML2 input variable ", vname, " has a base shape not yet mapped to a MOOSE type.");
427
428 _inputs.push_back(
429 {base, inferMOOSEIOType(base, base_shape.empty()), mtype, static_cast<std::size_t>(order)});
430 }
431
432 // User-specified mapping (overrides default mapping)
433 const auto [input_types, inputs] =
434 getInputParameterMapping<NEML2Utils::MOOSEIOType, std::string>("input_types", "inputs");
435
436 for (auto i : index_range(inputs))
437 {
438 const auto base_i = parseLag(inputs[i]).first;
439 // Check if the input variable also appears in skip_input_variables
440 if (contains(_skip_input_variables, base_i) || contains(_skip_input_variables, inputs[i]))
441 paramError("skip_input_variables",
442 "The input variable ",
443 inputs[i],
444 " is listed in skip_input_variables, but it also appears in inputs. Please "
445 "remove it from either list.");
446 // Check if the input variable exists in the NEML2 model
447 if (!contains(model.input_names(), inputs[i]))
448 paramError("inputs", "The neml2 input variable ", inputs[i], " does not exist.");
449 // Check if the input variable is already gathered by a custom kernel
450 if (contains(kernels, inputs[i]))
451 paramError("inputs",
452 "The input variable ",
453 inputs[i],
454 " is listed in inputs, but it also appears in input_kernels. Please "
455 "remove it from either list.");
456 // Check if the input variable is stateful and manage_state_advance is true
457 if (getParam<bool>("manage_state_advance") && parseLag(inputs[i]).second > 0)
458 paramError("inputs",
459 "The input variable ",
460 inputs[i],
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.");
464
465 // Get the existing mapping for this neml2 input variable and override its MOOSE type
466 for (auto & input : _inputs)
467 if (input.name == base_i)
468 {
469 input.moose_type = input_types[i];
470 break;
471 }
472 }
473}
474
475void
477{
478 if (!getParam<bool>("auto_output"))
479 return;
480
481 const auto out_shapes = shapeMap(model.output_names(), model.output_base_shapes());
482
483 for (const auto & oname : model.output_names())
484 {
485 const auto mtype = shapeToMooseType(out_shapes.at(oname));
486 if (mtype.empty())
488 "NEML2 output variable ", oname, " has a base shape not yet mapped to a MOOSE type.");
489 _outputs.push_back({oname, NEML2Utils::MOOSEIOType::MATERIAL, mtype, /*history_order=*/0});
490 }
491}
492
493void
495{
496 const auto derivs = getParam<std::vector<std::vector<std::string>>>("derivatives");
497 const auto in_shapes = shapeMap(model.input_names(), model.input_base_shapes());
498 const auto out_shapes = shapeMap(model.output_names(), model.output_base_shapes());
499
500 for (auto i : index_range(derivs))
501 {
502 if (derivs[i].size() != 2 && derivs[i].size() != 3)
503 paramError("derivatives",
504 "Each entry in derivatives must have 2 elements (output, input) or 3 "
505 "(output, input, alias).");
506
507 const auto & y = derivs[i][0];
508 const auto & x = derivs[i][1];
509 if (!contains(model.output_names(), y))
510 paramError("derivatives", "The NEML2 output variable ", y, " does not exist.");
511 if (!contains(model.input_names(), x))
512 paramError("derivatives", "The NEML2 input variable ", x, " does not exist.");
513
514 // The derivative block's base shape is the concatenation of the output and input base shapes.
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);
519 if (mtype.empty())
520 mooseError("The NEML2 derivative of ",
521 y,
522 " with respect to ",
523 x,
524 " has a base shape not yet mapped to a MOOSE type.");
525
526 // An optional third element aliases the derivative to a custom material property name.
527 const MaterialPropertyName deriv_name = derivs[i].size() == 3
528 ? MaterialPropertyName(derivs[i][2])
530 _derivs.push_back({deriv_name, y, x, mtype});
531 }
532}
533
534std::string
536 const std::string & user_name,
537 const std::map<std::string, std::vector<int64_t>> & param_shapes) const
538{
539 std::vector<std::string> param_names;
540 for (const auto & [p, s] : param_shapes)
541 param_names.push_back(p);
542
543 if (contains(param_names, user_name))
544 return user_name;
545
546 // Accept an unambiguous trailing ".<user_name>" suffix (e.g. "E" -> "model.E").
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);
552
553 if (matches.size() == 1)
554 return matches[0];
555
556 std::string available;
557 for (const auto & p : param_names)
558 available += (available.empty() ? "" : ", ") + p;
559 if (matches.size() > 1)
560 {
561 std::string m;
562 for (const auto & x : matches)
563 m += (m.empty() ? "" : ", ") + x;
564 mooseError("The NEML2 model parameter name '",
565 user_name,
566 "' is ambiguous; it matches multiple registered parameters: ",
567 m,
568 ". Use the fully-qualified name.");
569 }
570 mooseError("The NEML2 model parameter '",
571 user_name,
572 "' does not exist. Available model parameters: ",
573 available);
574}
575
576void
578{
579 const auto [param_types, params] = getInputParameterMapping<NEML2Utils::MOOSEIOType, std::string>(
580 "parameter_types", "parameters");
581 const auto & pshapes = model.parameter_base_shapes();
582
583 for (auto i : index_range(params))
584 {
585 const auto qn = resolveParameterName(params[i], pshapes);
586 const auto mtype = shapeToMooseType(pshapes.at(qn));
587 if (mtype.empty())
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});
591 }
592}
593
594void
596{
597 const auto derivs = getParam<std::vector<std::vector<std::string>>>("parameter_derivatives");
598 const auto out_shapes = shapeMap(model.output_names(), model.output_base_shapes());
599 const auto & pshapes = model.parameter_base_shapes();
600
601 for (auto i : index_range(derivs))
602 {
603 if (derivs[i].size() != 2 && derivs[i].size() != 3)
604 paramError("parameter_derivatives",
605 "Each entry in parameter_derivatives must have 2 elements (output, parameter) "
606 "or 3 (output, parameter, alias).");
607
608 const auto & y = derivs[i][0];
609 const auto & x_user = derivs[i][1];
610 if (!contains(model.output_names(), y))
611 paramError("parameter_derivatives", "The NEML2 output variable ", y, " does not exist.");
612 const auto x = resolveParameterName(x_user, pshapes);
613
614 // The derivative block's base shape is the concatenation of the output and parameter base
615 // shapes.
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);
620 if (mtype.empty())
621 mooseError("The NEML2 derivative of ",
622 y,
623 " with respect to model parameter ",
624 x,
625 " has a base shape not yet mapped to a MOOSE type.");
626
627 // By default the material-property name uses the user-written parameter name (the qualified
628 // name drives the NEML2-side parameter derivative); an optional third element aliases it.
629 const MaterialPropertyName deriv_name = derivs[i].size() == 3
630 ? MaterialPropertyName(derivs[i][2])
631 : derivativePropertyNameFirst(y, x_user);
632 _param_derivs.push_back({deriv_name, y, x, mtype});
633 }
634}
635
636void
638{
639 // Render a list of variable names for diagnostics.
640 auto names_list = [](const std::vector<std::string> & names)
641 {
642 std::string s;
643 for (const auto & n : names)
644 s += (s.empty() ? "" : ", ") + n;
645 return s;
646 };
647
648 // Guard 1: every variable named in 'initialize_outputs' must be an actual model output. Output
649 // retrievers (which carry the initialization value) are only created for model outputs, so a name
650 // that is not an output silently has no declarer and crashes during stateful initialization.
651 for (const auto & pair : _initialize_output_values)
652 {
653 const std::string out_name = pair.first;
654 if (!contains(model.output_names(), out_name))
655 paramError("initialize_outputs",
656 "'",
657 out_name,
658 "' is not an output of the NEML2 model and therefore cannot be initialized. "
659 "Available model outputs are: ",
660 names_list(model.output_names()),
661 ".");
662 }
663
664 // Guard 2: an old (stateful) material input 'var~N' requires the model to either take 'var' as a
665 // current input or produce it as an output. MOOSE sources the old value from the material
666 // property declared either by another material (when 'var' is also a current model input, e.g.
667 // strain provided by the mechanics) or by this model's output retriever (when 'var' is a model
668 // output). If the model does neither, nothing declares the property whose old value is requested,
669 // and MOOSE segfaults during stateful material property initialization. The common offender is a
670 // state variable pruned from the top-level outputs because a downstream model consumes it (e.g.
671 // GeneralElasticity reads 'orientation'); the fix is to add it to the model's
672 // 'additional_outputs'.
673 for (const auto & input : _inputs)
674 if (input.history_order > 0 && input.moose_type == NEML2Utils::MOOSEIOType::MATERIAL &&
675 !contains(model.input_names(), input.name) && !contains(model.output_names(), input.name))
677 "The NEML2 model takes the old value of '",
678 input.name,
679 "' (",
680 lagName(input.name, input.history_order),
681 ") as an input, but the model neither takes '",
682 input.name,
683 "' as a current input nor produces it as an output, so MOOSE has no source for its "
684 "old value. If '",
685 input.name,
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: ",
688 names_list(model.input_names()),
689 "; model outputs: ",
690 names_list(model.output_names()),
691 ".");
692}
693
694void
696{
697 if (!_app.parameters().have_parameter<bool>("parse_neml2_only"))
698 return;
699
700 // Save formatting of the output stream so that we can restore it later
701 const auto flags = _console.flags();
702
703 // Default width for the summary
704 const int width = 79;
705
706 _console << std::endl;
707 _console << COLOR_CYAN << std::setw(width) << std::setfill('*') << std::left
708 << "NEML2 MATERIAL MODEL SUMMARY BEGIN " << std::setfill(' ') << COLOR_DEFAULT
709 << std::endl;
710
711 // Metadata
712 _console << "NEML2 input file location: " << fname() << std::endl;
713 _console << "NEML2 action path: " << parameters().blockFullpath() << std::endl;
714
715 // List inputs and outputs of the model
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;
724
725 // List transfer between MOOSE and NEML2
726 if (!_app.parameters().get<bool>("parse_neml2_only"))
727 {
728 _console << COLOR_CYAN << std::setw(width) << std::setfill('-') << std::left
729 << "Transfer between MOOSE and NEML2 " << std::setfill(' ') << COLOR_DEFAULT
730 << std::endl;
731
732 _console << "MOOSE --> NEML2" << std::endl;
733
734 // List input transfer, MOOSE -> NEML2
735 for (const auto & input : _inputs)
736 _console << " - " << (input.history_order > 0 ? ("(old) " + input.name) : input.name) << " ("
737 << NEML2Utils::stringify(input.moose_type) << ")" << std::endl;
738
739 _console << "MOOSE <-- NEML2" << std::endl;
740
741 // List output transfer, NEML2 -> MOOSE
742 for (const auto & output : _outputs)
743 _console << " - " << output.name << std::endl;
744
745 // List derivative transfer, NEML2 -> MOOSE
746 for (const auto & deriv : _derivs)
747 _console << " - " << deriv.name << std::endl;
748 }
749
750 _console << COLOR_CYAN << std::setw(width) << std::setfill('*') << std::left
751 << "NEML2 MATERIAL MODEL SUMMARY END " << std::setfill(' ') << COLOR_DEFAULT << std::endl
752 << std::endl;
753
754 // Restore the formatting of the output stream
755 _console.flags(flags);
756}
757
758std::size_t
760{
761 std::size_t max_moose_name_length = 0;
762 for (const auto & input : _inputs)
763 {
764 auto n = input.name.size();
765 if (input.history_order > 0)
766 n += 6; // 6 is the length of "(old) "
767 max_moose_name_length = std::max(max_moose_name_length, n);
768 }
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;
774}
775#endif // NEML2_ENABLED
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.
Base class for actions.
Definition Action.h:38
MooseObjectName uniqueActionName() const
The unique name for accessing input parameters of this action in the InputParameterWarehouse.
Definition Action.h:108
MooseApp & _app
The MOOSE application this is associated with.
Definition MooseBase.h:375
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
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.
Definition Factory.C:68
const std::multimap< MooseObjectName, std::shared_ptr< InputParameters > > & getInputParameters(THREAD_ID tid=0) const
Return const reference to the map containing the InputParameter objects.
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
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.
std::string blockFullpath() const
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.
bool have_parameter(std::string_view name) const
A wrapper around the Parameters base class method.
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.
void applyParameters(const InputParameters &common, const std::vector< std::string > &exclude={}, const bool allow_private=false)
Method for applying common parameters.
torch::DeviceType getLibtorchDevice() const
Get the device torch is supposed to be running on.
Definition MooseApp.h:114
InputParameterWarehouse & getInputParameterWarehouse()
Get the InputParameterWarehouse for MooseObjects.
Definition MooseApp.C:2876
const InputParameters & parameters() const
Get the parameters of the object.
Definition MooseBase.h:131
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
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 T & getParam(const std::string &name) const
Retrieve a parameter for the object.
Definition MooseBase.h:406
void mooseInfo(Args &&... args) const
Definition MooseBase.h:334
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
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.
Definition NEML2Action.h:28
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
Definition NEML2Action.h:41
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 &)
Definition NEML2Action.C:84
std::vector< DerivativeMapping > _param_derivs
MOOSE-NEML2 output-parameter-derivative mappings.
static InputParameters validParams()
Definition NEML2Action.C:66
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 > > &param_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.
Definition NEML2Utils.h:78
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,...
Definition NEML2Utils.h:58
void redirectLogsToConsole(const ConsoleStream &console)
Route NEML2's log output into MOOSE's console.
Definition NEML2Utils.C:45
std::string lagName(const std::string &base, int lag)
Inverse of parseLag: build the variable name for a base name + lag.
Definition NEML2Utils.h:71
void assertNEML2Enabled()
Assert that NEML2 is enabled.
Definition NEML2Utils.C:90
std::string stringify(MOOSEIOType type)
Definition NEML2Utils.C:56
Real deriv(unsigned n, unsigned alpha, unsigned beta, Real x)
bool contains(std::string_view superstring, std::string_view substring)