Generate Reward Function from a Model Verification Block for a Water Tank System
This example shows how to automatically generate a reward function from performance requirement defined in a Simulink® Design Optimization™ model verification block. You then use the generated reward function to train a reinforcement learning agent.
You can use the
generateRewardFunction to generate a reward function for reinforcement learning, starting from performance constraints specified in a Simulink Design Optimization model verification block. The resulting reward signal is a sum of weighted penalties on constraint violations by the current state of the environment.
In this example, you will convert the cost and constraint specifications defined in a Check Step Response Characteristics block for a water tank system into a reward function. You then use the reward function and use it to train an agent to control the water tank.
Specify parameters for this example.
% Watertank parameters a = 2; b = 5; A = 20; % Initial and final height h0 = 1; hf = 2; % Simulation and sample times Tf = 10; Ts = 0.1;
The original model for this example is the watertank Simulink Model (Simulink Control Design).
Open the model.
mdl = "rlWatertankStepInput"; open_system(mdl)
The model in this example has been modified for reinforcement learning. The goal is to control the level of the water in the tank using a reinforcement learning agent, while satisfying the response characteristics defined in the Check Step Response Characteristics block. Open the block to view the desired step response specifications.
verifBlk = mdl + "/WaterLevelStepResponse"; open_system(verifBlk)
Generate a Reward Function
Generate the reward function code from specifications in the WaterLevelStepResponse block using
generateRewardFunction. The code is displayed in the MATLAB Editor.
The generated reward function is a starting point for reward design. You may modify the function by choosing different penalty functions and tuning the penalty weights. For this example, make the following change to the generated code:
The default penalty weight is
1. Set weight to
The default exterior penalty function method is step. Change the method to
After you make changes, the weight and penalty specifications should be as follows:
Weight = 10; Penalty = sum(exteriorPenalty(x,Block1_xmin,Block1_xmax,'quadratic'));
For this example, the modified code has been saved in the MATLAB function file
rewardFunctionVfb.m. Display the generated reward function.
function reward = rewardFunctionVfb(x,t) % REWARDFUNCTION generates rewards from Simulink block specifications. % % x : Input of watertank_stepinput_rl/WaterLevelStepResponse % t : Simulation time (s) % Reinforcement Learning Toolbox % 26-Apr-2021 13:05:16 %#codegen %% Specifications from watertank_stepinput_rl/WaterLevelStepResponse Block1_InitialValue = 1; Block1_FinalValue = 2; Block1_StepTime = 0; Block1_StepRange = Block1_FinalValue - Block1_InitialValue; Block1_MinRise = Block1_InitialValue + Block1_StepRange * 80/100; Block1_MaxSettling = Block1_InitialValue + Block1_StepRange * (1+2/100); Block1_MinSettling = Block1_InitialValue + Block1_StepRange * (1-2/100); Block1_MaxOvershoot = Block1_InitialValue + Block1_StepRange * (1+10/100); Block1_MinUndershoot = Block1_InitialValue - Block1_StepRange * 5/100; if t >= Block1_StepTime if Block1_InitialValue <= Block1_FinalValue Block1_UpperBoundTimes = [0,5; 5,max(5+1,t+1)]; Block1_UpperBoundAmplitudes = [Block1_MaxOvershoot,Block1_MaxOvershoot; Block1_MaxSettling,Block1_MaxSettling]; Block1_LowerBoundTimes = [0,2; 2,5; 5,max(5+1,t+1)]; Block1_LowerBoundAmplitudes = [Block1_MinUndershoot,Block1_MinUndershoot; Block1_MinRise,Block1_MinRise; Block1_MinSettling,Block1_MinSettling]; else Block1_UpperBoundTimes = [0,2; 2,5; 5,max(5+1,t+1)]; Block1_UpperBoundAmplitudes = [Block1_MinUndershoot,Block1_MinUndershoot; Block1_MinRise,Block1_MinRise; Block1_MinSettling,Block1_MinSettling]; Block1_LowerBoundTimes = [0,5; 5,max(5+1,t+1)]; Block1_LowerBoundAmplitudes = [Block1_MaxOvershoot,Block1_MaxOvershoot; Block1_MaxSettling,Block1_MaxSettling]; end Block1_xmax = zeros(1,size(Block1_UpperBoundTimes,1)); for idx = 1:numel(Block1_xmax) tseg = Block1_UpperBoundTimes(idx,:); xseg = Block1_UpperBoundAmplitudes(idx,:); Block1_xmax(idx) = interp1(tseg,xseg,t,'linear',NaN); end if all(isnan(Block1_xmax)) Block1_xmax = Inf; else Block1_xmax = max(Block1_xmax,,'omitnan'); end Block1_xmin = zeros(1,size(Block1_LowerBoundTimes,1)); for idx = 1:numel(Block1_xmin) tseg = Block1_LowerBoundTimes(idx,:); xseg = Block1_LowerBoundAmplitudes(idx,:); Block1_xmin(idx) = interp1(tseg,xseg,t,'linear',NaN); end if all(isnan(Block1_xmin)) Block1_xmin = -Inf; else Block1_xmin = max(Block1_xmin,,'omitnan'); end else Block1_xmin = -Inf; Block1_xmax = Inf; end %% Penalty function weight (specify nonnegative) Weight = 10; %% Compute penalty % Penalty is computed for violation of linear bound constraints. % % To compute exterior bound penalty, use the exteriorPenalty function and % specify the penalty method as 'step' or 'quadratic'. % % Alternaltely, use the hyperbolicPenalty or barrierPenalty function for % computing hyperbolic and barrier penalties. % % For more information, see help for these functions. Penalty = sum(exteriorPenalty(x,Block1_xmin,Block1_xmax,'quadratic')); %% Compute reward reward = -Weight * Penalty; end
To integrate this reward function in the water tank model, open the MATLAB Function block under the Reward Subsystem.
open_system(mdl + "/Reward/Reward Function")
Append the function with the following line of code and save the model.
r = rewardFunctionVfb(x,t);
The MATLAB Function block will now execute
rewardFunctionVfb.m for computing rewards.
For this example, the MATLAB Function block has already been modified and saved.
Create a Reinforcement Learning Environment
The environment dynamics are modeled in the Water-Tank Subsystem. For this environment,
The observations are the reference height
reffrom the last 5 time steps, and the height error is
The action is the voltage
Vapplied to the pump.
The sample time
Create observation and action specifications for the environment.
numObs = 6; numAct = 1; oinfo = rlNumericSpec([numObs 1]); ainfo = rlNumericSpec([numAct 1]);
Create the reinforcement learning environment using the
agentBlk = mdl + "/RL Agent"; env = rlSimulinkEnv(mdl, agentBlk, oinfo, ainfo);
Create a Reinforcement Learning Agent
Fix the random seed for reproducibility.
The agent used in this example is a twin-delayed deep deterministic policy gradient (TD3) agent. TD3 agents use two parametrized Q-value function approximators to estimate the value (that is the expected cumulative long-term reward) of the policy. To model the parametrized Q-value function within both critics, use a neural network with two inputs (the observation and action) and one output (the value of the policy when taking a given action from the state corresponding to a given observation). For more information on TD3 agents, see Twin-Delayed Deep Deterministic (TD3) Policy Gradient Agents.
Define each network path as an array of layer objects. Assign names to the input and output layers of each path. These names allow you to connect the paths and then later explicitly associate the network input and output layers with the appropriate environment channel.
mainPath = [ featureInputLayer(numObs) fullyConnectedLayer(128) concatenationLayer(1, 2, Name="concat") reluLayer() fullyConnectedLayer(128) reluLayer() fullyConnectedLayer(1)]; actionPath = [ featureInputLayer(numAct) fullyConnectedLayer(8, Name="fc_act")]; % Create layerGraph object and add layers criticNet = layerGraph(mainPath); criticNet = addLayers(criticNet, actionPath); % Connect Layers criticNet = connectLayers(criticNet, "fc_act", "concat/in2");
Plot the critic network structure.
Create the critic function objects using
rlQValueFunction. The critic function object encapsulates the critic by wrapping around the critic deep neural network. To make sure the critics have different initial weights, explicitly initialize each network before using them to create the critics.
% Convert the neural network to a dlnetwork object without initializing the networks criticdlNet = dlnetwork(criticNet, Initialize=false); % Create the two critic functions for the TD3 agent critic1 = rlQValueFunction(initialize(criticdlNet), oinfo, ainfo); critic2 = rlQValueFunction(initialize(criticdlNet), oinfo, ainfo);
TD3 agents learn a parametrized deterministic policy over continuous action spaces, which is learned by a continuous deterministic actor. This actor takes the current observation as input and returns as output an action that is a deterministic function of the observation.
To model the parametrized policy within the actor, use a neural network with one input layer (which receives the content of the environment observation channel, as specified by obsInfo) and one output layer (which returns the action to the environment action channel, as specified by
Define the network as an array of layer objects.
actorNet = [ featureInputLayer(numObs) fullyConnectedLayer(128) reluLayer() fullyConnectedLayer(128) reluLayer() fullyConnectedLayer(numAct)];
Plot the actor network.
Create a deterministic actor function that is responsible for modeling the policy of the agent. For more information, see
actordlNet = dlnetwork(actorNet); actor = rlContinuousDeterministicActor(actordlNet, oinfo, ainfo);
Specify the agent options using
rlTD3AgentOptions. The agent trains from an experience buffer of maximum capacity
1e6 by randomly selecting mini-batches of size
256. The discount factor of
0.99 favors long-term rewards.
agentOpts = rlTD3AgentOptions( ... SampleTime=Ts, ... DiscountFactor=0.99, ... ExperienceBufferLength=1e6, ... MiniBatchSize=256);
The exploration model in this TD3 agent is Gaussian. The noise model adds a uniform random value to the action during training. Set the standard deviation of the noise to
0.5. The standard deviation decays at the rate of
1e-5 every agent step until the minimum value of
agentOpts.ExplorationModel.StandardDeviation = 0.5; agentOpts.ExplorationModel.StandardDeviationDecayRate = 1e-5; agentOpts.ExplorationModel.StandardDeviationMin = 0;
Create the TD3 agent using the actor and critic representations. For more information on TD3 agents, see
agent = rlTD3Agent(actor, [critic1, critic2], agentOpts);
Closed Loop Response
Simulate the model to view the closed loop step response of the untrained agent.
Train the Agent
To train the agent, first specify the training options using
rlTrainingOptions. For this example, use the following options:
Run training for at most 100 episodes, with each episode lasting at most
ceil(Tf/Ts)time steps, where the total simulation time
Stop the training when the agent receives an average cumulative reward greater than
20consecutive episodes. At this point, the agent can track the reference height.
trainOpts = rlTrainingOptions(... MaxEpisodes=100, ... MaxStepsPerEpisode=ceil(Tf/Ts), ... StopTrainingCriteria="AverageReward",... StopTrainingValue=-5,... ScoreAveragingWindowLength=20);
Train the agent using the
train function. Training this agent is a computationally intensive process that may take several minutes to complete. To save time while running this example, load a pretrained agent by setting
false. To train the agent yourself, set
doTraining = false; if doTraining trainingStats = train(agent, env, trainOpts); else load("rlWatertankTD3Agent.mat") end
A snapshot of the training progress is shown in the following figure. You can expect different results due to inherent randomness in the training process.
Closed Loop Response of Trained Agent
Simulate the model to view the closed loop step response. The reinforcement learning agent is able to track the reference height while satisfying the step response constraints.
- Tune PI Controller Using Reinforcement Learning
- Train Biped Robot to Walk Using Reinforcement Learning Agents
- Generate Reward Function from a Model Predictive Controller for a Servomotor