water distribution system scheduling using reinforcement learning -凯发k8网页登录
this example shows how to learn an optimal pump scheduling policy for a water distribution system using reinforcement learning (rl).
water distribution system
the following figure shows a water distribution system.
here:
is the amount of water supplied to the water tank from a reservoir.
is the amount of water flowing out of the tank to satisfy usage demand.
the objective of the reinforcement learning agent is to schedule the number of pumps running to both minimize the energy usage of the system and satisfy the usage demand (). the dynamics of the tank system are governed by the following equation.
here, and . the demand over a 24 hour period is a function of time given as
where is the expected demand and represents the demand uncertainty, which is sampled from a uniform random distribution.
the supply is determined by the number of pumps running, according to following mapping.
to simplify the problem, power consumption is defined as the number of pumps running, .
the following function is the reward for this environment. to avoid overflowing or emptying the tank, an additional cost is added if the water height is close to the maximum or minimum water levels, or , respectively.
generate demand profile
to generate and a water demand profile based on the number of days considered, use the generatewaterdemand
function defined at the end of this example.
num_days = 4; % number of days
[waterdemand,t_max] = generatewaterdemand(num_days);
view the demand profile.
plot(waterdemand)
open and configure model
open the distribution system simulink model.
mdl = "watertankscheduling";
open_system(mdl)
in addition to the reinforcement learning agent, a simple baseline controller is defined in the control law matlab function block. this controller activates a certain number of pumps depending on the water level.
specify the initial water height.
h0 = 3; % m
specify the model parameters.
sampletime = 0.2; h_max = 7; % max tank height (m) a_tank = 40; % area of tank (m^2)
create environment interface for rl agent
to create an environment interface for the simulink model, first define the action and observation specifications, actinfo
and obsinfo
, respectively. the agent action is the selected number of pumps. the agent observation is the water height, which is measured as a continuous-time signal.
actinfo = rlfinitesetspec([0,1,2,3]); obsinfo = rlnumericspec([1,1]);
create the environment interface.
env = rlsimulinkenv(mdl,mdl "/rl agent",obsinfo,actinfo);
specify a custom reset function, which is defined at the end of this example, that randomizes the initial water height and the water demand. doing so allows the agent to be trained on different initial water levels and water demand functions for each episode.
env.resetfcn = @(in)localresetfcn(in);
the actor and critic networks are initialized randomly. ensure reproducibility by fixing the seed of the random generator.
rng(0);
create dqn agent
dqn agents use a parametrized q-value function approximator to estimate the value of the policy. since dqn agents have a discrete action space, you have the option to create a vector (that is multi-output) q-value function critic, which is generally more efficient than a comparable single-output critic.
a vector q-value function takes only the observation as input and returns as output a single vector with as many elements as the number of possible actions. the value of each output element represents the expected discounted cumulative long-term reward when an agent starts from the state corresponding to the given observation and executes the action corresponding to the element number (and follows a given policy afterwards)
to model the parametrized q-value function within the critic, use a non-recurrent neural network. to use a recurrent neural network, set uselstm
to true
. note that prod(obsinfo.dimension)
returns the number of dimensions of the observation space (regardless of whether they are arranged as a row vector, column vector, or matrix, while numel(actinfo.elements)
returns the number of elements of the discrete action space.
uselstm = false; if uselstm layers = [ sequenceinputlayer(prod(obsinfo.dimension)) fullyconnectedlayer(32) relulayer lstmlayer(32) fullyconnectedlayer(32) relulayer fullyconnectedlayer(numel(actinfo.elements)) ]; else layers = [ featureinputlayer(obsinfo.dimension(1)) fullyconnectedlayer(32) relulayer fullyconnectedlayer(32) relulayer fullyconnectedlayer(32) relulayer fullyconnectedlayer(numel(actinfo.elements)) ]; end
convert to a dlnetwork
object and display the number of parameters.
dnn = dlnetwork(layers); summary(dnn)
initialized: true number of learnables: 2.3k inputs: 1 'input' 1 features
create a critic using rlvectorqvaluefunction
using the defined deep neural network and the environment specifications.
critic = rlvectorqvaluefunction(dnn,obsinfo,actinfo);
create dqn agent
specify training options for the critic and the actor using rloptimizeroptions
.
criticopts = rloptimizeroptions(learnrate=0.001,gradientthreshold=1);
specify the ddpg agent options using . if you are using an lstm network, set the sequence length to 20
.
opt = rldqnagentoptions(sampletime=sampletime); if uselstm opt.sequencelength = 20; else opt.sequencelength = 1; end opt.discountfactor = 0.995; opt.experiencebufferlength = 1e6; opt.epsilongreedyexploration.epsilondecay = 1e-5; opt.epsilongreedyexploration.epsilonmin = .02;
include the training options for the critic.
opt.criticoptimizeroptions = criticopts;
create the agent using the critic and the options object.
agent = rldqnagent(critic,opt);
train agent
to train the agent, first specify the training options. for this example, use the following options.
run training for 1000 episodes, with each episode lasting at
ceil(t_max/ts)
time steps.display the training progress in the episode manager dialog box (set the
plots
option)
specify the options for training using an rltrainingoptions
object.
trainopts = rltrainingoptions(... maxepisodes=1000, ... maxstepsperepisode=ceil(t_max/sampletime), ... verbose=false, ... plots="training-progress",... stoptrainingcriteria="episodecount",... stoptrainingvalue=1000,... scoreaveragingwindowlength=100);
while you do not do it for this example, you can save agents during the training process. for example, the following options save every agent with a reward value greater than or equal to -42
.
save agents using saveagentcriteria if necessary trainopts.saveagentcriteria = "episodereward"; trainopts.saveagentvalue = -42;
train the agent using the train
function. training this agent is a computationally intensive process that takes several hours 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 % connect the rl agent block by toggling % the manual switch block set_param(mdl "/manual switch","sw","0"); % train the agent. trainingstats = train(agent,env,trainopts); else % load the pretrained agent for the example. load("simulinkwaterdistributiondqn.mat","agent") end
the following figure shows the training progress.
simulate dqn agent
to validate the performance of the trained agent, simulate it in the water-tank environment. for more information on agent simulation, see rlsimulationoptions
and sim
.
to simulate the agent performance, connect the rl agent block by toggling the manual switch block.
set_param(mdl "/manual switch","sw","0");
set the maximum number of steps for each simulation and the number of simulations. for this example, run 30 simulations. the environment reset function sets a different initial water height and water demand are different in each simulation.
numsimulations = 30;
simoptions = rlsimulationoptions(maxsteps=t_max/sampletime,...
numsimulations= numsimulations);
to compare the agent with the baseline controller under the same conditions, reset the initial random seed used in the environment reset function.
env.resetfcn("reset seed");
simulate the agent against the environment.
experiencedqn = sim(env,agent,simoptions);
simulate baseline controller
to compare dqn agent with the baseline controller, you must simulate the baseline controller using the same simulation options and initial random seed for the reset function.
enable the baseline controller.
set_param(mdl "/manual switch","sw","1");
to compare the agent with the baseline controller under the same conditions, reset the random seed used in the environment reset function.
env.resetfcn("reset seed");
simulate the baseline controller against the environment.
experiencebaseline = sim(env,agent,simoptions);
compare dqn agent with baseline controller
initialize cumulative reward result vectors for both the agent and baseline controller.
resultvectordqn = zeros(numsimulations, 1); resultvectorbaseline = zeros(numsimulations,1);
calculate cumulative rewards for both the agent and the baseline controller.
for ct = 1:numsimulations resultvectordqn(ct) = sum(experiencedqn(ct).reward); resultvectorbaseline(ct) = sum(experiencebaseline(ct).reward); end
plot the cumulative rewards.
plot([resultvectordqn resultvectorbaseline],"o") set(gca,"xtick",1:numsimulations) xlabel("simulation number") ylabel("cumulative reward") legend("dqn","baseline","location","northeastoutside")
the cumulative reward obtained by the agent is consistently around –40. this value is much greater than the average reward obtained by the baseline controller. therefore, the dqn agent consistently outperforms the baseline controller in terms of energy savings.
local functions
water demand function
function [waterdemand,t_max] = generatewaterdemand(num_days) t = 0:(num_days*24)-1; % hr t_max = t(end); demand_mean = [28, 28, 28, 45, 55, 110, ... 280, 450, 310, 170, 160, 145, ... 130, 150, 165, 155, 170, 265, ... 360, 240, 120, 83, 45, 28 ]'; % m^3/hr demand = repmat(demand_mean,1,num_days); demand = demand(:); % add noise to demand a = -25; % m^3/hr b = 25; % m^3/hr demand_noise = a (b-a).*rand(numel(demand),1); waterdemand = timeseries(demand demand_noise,t); waterdemand.name = "water demand"; waterdemand.timeinfo.units = "hours"; end
reset function
function in = localresetfcn(in) % use a persistent random seed value to evaluate the agent % and the baseline controller under the same conditions. persistent randomseed if isempty(randomseed) randomseed = 0; end if strcmp(in,"reset seed") randomseed = 0; return end randomseed = randomseed 1; rng(randomseed) % randomize water demand. num_days = 4; h_max = 7; [waterdemand,~] = generatewaterdemand(num_days); assignin("base","waterdemand",waterdemand) % randomize initial height. h0 = 3*randn; while h0 <= 0 || h0 >= h_max h0 = 3*randn; end blk = "watertankscheduling/water tank system/initial water height"; in = setblockparameter(in,blk,"value",num2str(h0)); end
see also
functions
train
|sim
|rlsimulinkenv