10 #ifdef MOOSE_LIBTORCH_ENABLED 24 params.
addClassDescription(
"Controls the value of multiple controllable input parameters using a " 25 "Libtorch-based neural network.");
27 "The input parameter(s) to control.");
29 "responses",
"The responses (prostprocessors) which are used for the control.");
31 "response_shift_factors",
32 "Constants which will be used to shift the response values. This is used for the " 33 "manipulation of the neural net inputs for better training efficiency.");
35 "response_scaling_factors",
36 "Constants which will be used to multiply the shifted response values. This is used for " 37 "the manipulation of the neural net inputs for better training efficiency.");
38 params.
addParam<std::string>(
"filename",
39 "Define if the neural net is supposed to be loaded from a file.");
40 params.
addParam<
bool>(
"torch_script_format",
42 "If we want to load the neural net using the torch-script format.");
46 "Number of time steps to use in the input data, if larger than 1, " 47 "data from the previous timesteps will be used as well as inputs in the training.");
48 params.
addParam<std::vector<unsigned int>>(
"num_neurons_per_layer",
49 "The number of neurons on each hidden layer.");
50 params.
addParam<std::vector<std::string>>(
51 "activation_function",
52 std::vector<std::string>({
"relu"}),
53 "The type of activation functions to use. It is either one value " 54 "or one value per hidden layer.");
57 "action_scaling_factors",
58 "Scale factor that multiplies the NN output to obtain a physically meaningful value.");
65 _old_responses(declareRestartableData<
std::vector<
std::vector<
Real>>>(
"old_responses")),
66 _control_names(getParam<
std::vector<
std::string>>(
"parameters")),
67 _current_control_signals(
std::vector<
Real>(_control_names.size(), 0.0)),
68 _response_names(getParam<
std::vector<PostprocessorName>>(
"responses")),
69 _input_timesteps(getParam<unsigned
int>(
"input_timesteps")),
70 _response_shift_factors(isParamValid(
"response_shift_factors")
71 ? getParam<
std::vector<
Real>>(
"response_shift_factors")
72 :
std::vector<
Real>(_response_names.size(), 0.0)),
73 _response_scaling_factors(isParamValid(
"response_scaling_factors")
74 ? getParam<
std::vector<
Real>>(
"response_scaling_factors")
75 :
std::vector<
Real>(_response_names.size(), 1.0)),
76 _action_scaling_factors(isParamValid(
"action_scaling_factors")
77 ? getParam<
std::vector<
Real>>(
"action_scaling_factors")
78 :
std::vector<
Real>(_control_names.size(), 1.0))
83 {
"num_neurons_per_layer",
"activation_function"},
84 !getParam<bool>(
"torch_script_format"));
88 "The number of shift factors is not the same as the number of responses!");
92 "response_scaling_factors",
93 "The number of normalization coefficients is not the same as the number of responses!");
97 "The number of normalization coefficients is not the same as the number of " 98 "controlled parameters!");
102 for (
unsigned int resp_i = 0; resp_i <
_response_names.size(); ++resp_i)
109 std::string filename = getParam<std::string>(
"filename");
110 if (getParam<bool>(
"torch_script_format"))
111 _nn = std::make_shared<Moose::TorchScriptModule>(filename);
116 std::vector<unsigned int> num_neurons_per_layer =
117 getParam<std::vector<unsigned int>>(
"num_neurons_per_layer");
118 std::vector<std::string> activation_functions =
120 ? getParam<std::vector<std::string>>(
"activation_function")
121 : std::vector<std::string>({
"relu"});
122 auto nn = std::make_shared<Moose::LibtorchArtificialNeuralNet>(
123 filename, num_inputs, num_outputs, num_neurons_per_layer, activation_functions);
127 torch::load(nn, filename);
128 _nn = std::make_shared<Moose::LibtorchArtificialNeuralNet>(*nn);
130 catch (
const c10::Error & e)
133 "The requested pytorch parameter file could not be loaded. This can either be the" 134 "result of the file not existing or a misalignment in the generated container and" 135 "the data in the file. Make sure the dimensions of the generated neural net are the" 136 "same as the dimensions of the parameters in the input file!\n",
162 torch::Tensor action =
_nn->forward(input_tensor);
165 for (
unsigned int control_i = 0; control_i < n_controls; ++control_i)
184 "The index of the requested control signal is not in the [0," +
191 const std::string & param_name,
192 const std::vector<std::string> & conditional_params,
193 bool should_be_defined)
196 for (
const auto & param : conditional_params)
199 "This parameter should",
200 (should_be_defined ?
" " :
" not "),
220 _nn = std::make_shared<Moose::LibtorchArtificialNeuralNet>(input_nn);
231 for (
const auto & step_i :
make_range(num_old_timesteps))
234 torch::Tensor input_tensor;
237 return input_tensor.transpose(0, 1);
244 mooseError(
"The neural network in the controller must exist!");
A time-dependent, neural network-based control of multiple input parameters.
const std::vector< PostprocessorName > & _response_names
Names of the postprocessors which contain the observations of the system.
const std::vector< Real > _action_scaling_factors
Multipliers for the actions.
std::vector< Real > _current_response
The values of the current observed postprocessor values.
const std::vector< Real > _response_scaling_factors
Scaling constants (multipliers) for the responses.
static InputParameters validParams()
Class constructor.
LibtorchNeuralNetControl(const InputParameters ¶meters)
Construct using input parameters.
const Moose::LibtorchNeuralNetBase & controlNeuralNet() const
Return a reference to the stored neural network.
static InputParameters validParams()
std::shared_ptr< Moose::LibtorchNeuralNetBase > _nn
Pointer to the neural net object which is supposed to be used to control the parameter values...
Real getSignal(const unsigned int signal_index) const
Get the (signal_index)-th signal of the control neural net.
registerMooseObject("MooseApp", LibtorchNeuralNetControl)
torch::Tensor prepareInputTensor()
Function that prepares the input tensor for the controller neural network.
const std::vector< std::string > & _control_names
The names of the controllable parameters.
bool isParamValid(const std::string &name) const
Test if the supplied parameter is valid.
bool hasControlNeuralNet() const
Return true if the object already has a neural netwok.
void vectorToTensor(std::vector< DataType > &vector, torch::Tensor &tensor, const bool detach=false)
Utility function that converts a standard vector to a torch::Tensor.
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 ...
std::vector< std::vector< Real > > & _old_responses
This variable is populated if the controller needs acess to older values of the observed postprocesso...
virtual const PostprocessorValue & getPostprocessorValueByName(const PostprocessorName &name) const
Retrieve the value of the Postprocessor.
bool isParamSetByUser(const std::string &nm) const
Test if the supplied parameter is set by a user, as opposed to not set or set to default.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
const unsigned int _input_timesteps
Number of timesteps to use as input data from the reporters (this influences how many past results ar...
This base class is meant to gather the functions and members common in every neural network based on ...
Base class for Control objects.
IntRange< T > make_range(T beg, T end)
void mooseError(Args &&... args) const
Emits an error prefixed with object name and type.
const InputParameters & parameters() const
Get the parameters of the object.
virtual void execute() override
Execute neural network to determine the controllable parameter values.
std::vector< const Real * > _response_values
Links to the current response postprocessor values.
void updateCurrentResponse()
Function that updates the values of the current response.
void loadControlNeuralNet(const Moose::LibtorchArtificialNeuralNet &input_nn)
Function responsible for loading the neural network for the controller.
std::vector< Real > _current_control_signals
The control signals from the last evaluation of the controller.
void ErrorVector unsigned int
auto index_range(const T &sizable)
void conditionalParameterError(const std::string ¶m_name, const std::vector< std::string > &conditional_param, bool should_be_defined=true)
Function responsible for checking for potential user errors in the input file.
const std::vector< Real > _response_shift_factors
Shifting constants for the responses.