main content

generate reward function from a model verification block for a water tank system -凯发k8网页登录

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.

introduction

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. for more information, see check step response characteristics (simulink design optimization).

open the block to view the desired step response specifications.

verifblk = mdl   "/waterlevelstepresponse";
open_system(verifblk)

figure check step response characteristics [1] - waterlevelstepresponse contains an axes object and other objects of type uiflowcontainer, uimenu, uitoolbar. the axes object contains 9 objects of type patch, line.

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.

generaterewardfunction(blk)

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 10.

  • the default exterior penalty function method is step. change the method to quadratic.

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.

type rewardfunctionvfb.m
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 ref from the last 5 time steps, and the height error is err = ref - h.

  • the action is the voltage v applied to the pump.

  • the sample time ts is 0.1 s.

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 rlsimulinkenv function.

agentblk = mdl   "/rl agent";
env = rlsimulinkenv(mdl, agentblk, oinfo, ainfo);

create a reinforcement learning agent

fix the random seed for reproducibility.

rng(100)

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.

plot(criticnet);

figure contains an axes object. the axes object contains an object of type graphplot.

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 network to dlnetwork object without initializing.
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 ainfo).

define the network as an array of layer objects.

actornet = [
    featureinputlayer(numobs)
    fullyconnectedlayer(128)
    relulayer()
    fullyconnectedlayer(128)
    relulayer()
    fullyconnectedlayer(numact)];

plot the actor network.

plot(layergraph(actornet));

figure contains an axes object. the axes object contains an object of type graphplot.

create a deterministic actor function that is responsible for modeling the policy of the agent. for more information, see rlcontinuousdeterministicactor.

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 0.

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 rltd3agent.

agent = rltd3agent(actor, [critic1, critic2], agentopts);

closed loop response

simulate the model to view the closed loop step response of the untrained agent.

sim(mdl);

figure check step response characteristics [1] - waterlevelstepresponse contains an axes object and other objects of type uiflowcontainer, uimenu, uitoolbar. the axes object contains 10 objects of type patch, line. this object represents waterlevelstepresponse.

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 tf is 10 s.

  • stop the training when the agent receives an average cumulative reward greater than -5 over 20 consecutive 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 dotraining to false. to train the agent yourself, set dotraining to true.

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.

sim(mdl);

figure check step response characteristics [1] - waterlevelstepresponse contains an axes object and other objects of type uiflowcontainer, uimenu, uitoolbar. the axes object contains 10 objects of type patch, line. this object represents waterlevelstepresponse.

see also

functions

objects

blocks

related examples

more about

网站地图