Main Content

Train DDPG Agent to Control Flying Robot

This example shows how to train a deep deterministic policy gradient (DDPG) agent to generate trajectories for a flying robot modeled in Simulink®. For more information on DDPG agents, see Deep Deterministic Policy Gradient (DDPG) Agents (Reinforcement Learning Toolbox).

Flying Robot Model

The reinforcement learning environment for this example is a flying robot with its initial condition randomized around a ring of radius 15 m. The orientation of the robot is also randomized. The robot has two thrusters mounted on the side of the body that are used to propel and steer the robot. The training goal is to drive the robot from its initial condition to the origin facing east.

Open the model.

mdl = 'rlFlyingRobotEnv';

Set the initial model state variables.

theta0 = 0;
x0 = -15;
y0 = 0;

Define the sample time Ts and the simulation duration Tf.

Ts = 0.4;
Tf = 30;

For this model:

  • The goal orientation is 0 rad (robot facing east).

  • The thrust from each actuator is bounded from -1 to 1 N

  • The observations from the environment are the position, orientation (sine and cosine of orientation), velocity, and angular velocity of the robot.

  • The reward rt provided at every time step is






  • xt is the position of the robot along the x-axis.

  • yt is the position of the robot along the y-axis.

  • θt is the orientation of the robot.

  • Lt-1 is the control effort from the left thruster.

  • Rt-1 is the control effort from the right thruster.

  • r1 is the reward when the robot is close to the goal.

  • r2 is the penalty when the robot drives beyond 20 m in either the x or y direction. The simulation is terminated when r2<0.

  • r3 is a QR penalty that penalizes distance from the goal and control effort.

Create Integrated Model

To train an agent for the FlyingRobotEnv model, use the createIntegratedEnv function to automatically generate an integrated model with the RL Agent block that is ready for training.

integratedMdl = 'IntegratedFlyingRobot';
[~,agentBlk,observationInfo,actionInfo] = createIntegratedEnv(mdl,integratedMdl);

Actions and Observations

Before creating the environment object, specify names for the observation and action specifications, and bound the thrust actions between -1 and 1.

The observation signals for this environment are observation=[xyx˙y˙sin(θ)cos(θ)θ˙]T.

numObs = prod(observationInfo.Dimension);
observationInfo.Name = 'observations';

The action signals for this environment are action=[TRTL]T .

numAct = prod(actionInfo.Dimension);
actionInfo.LowerLimit = -ones(numAct,1);
actionInfo.UpperLimit =  ones(numAct,1);
actionInfo.Name = 'thrusts';

Create Environment Interface

Create an environment interface for the flying robot using the integrated model.

env = rlSimulinkEnv(integratedMdl,agentBlk,observationInfo,actionInfo);

Reset Function

Create a custom reset function that randomizes the initial position of the robot along a ring of radius 15 m and the initial orientation. For details on the reset function, see flyingRobotResetFcn.

env.ResetFcn = @(in) flyingRobotResetFcn(in);

Fix the random generator seed for reproducibility.


Create DDPG agent

A DDPG agent approximates the long-term reward given observations and actions by using a critic value function representation. To create the critic, first create a deep neural network with two inputs (the observation and action) and one output. For more information on creating a neural network value function representation, see Create Policies and Value Functions (Reinforcement Learning Toolbox).

% Specify the number of outputs for the hidden layers.
hiddenLayerSize = 100; 

observationPath = [
actionPath = [

% Create the layer graph.
criticNetwork = layerGraph(observationPath);
criticNetwork = addLayers(criticNetwork,actionPath);

% Connect actionPath to observationPath.
criticNetwork = connectLayers(criticNetwork,'fc5','add/in2');

% Create dlnetwork from layer graph
criticNetwork = dlnetwork(criticNetwork);

Specify options for the critic using rlOptimizerOptions.

criticOptions = rlOptimizerOptions('LearnRate',1e-03,'GradientThreshold',1);

Create the critic representation using the specified neural network and options. You must also specify the action and observation specification for the critic. For more information, see rlQValueFunction (Reinforcement Learning Toolbox).

critic = rlQValueFunction(criticNetwork,observationInfo,actionInfo,...

A DDPG agent decides which action to take given observations by using an actor representation. To create the actor, first create a deep neural network with one input (the observation) and one output (the action).

Construct the actor similarly to the critic. For more information, see rlContinuousDeterministicActor (Reinforcement Learning Toolbox).

actorNetwork = [
actorNetwork = dlnetwork(actorNetwork);

actorOptions = rlOptimizerOptions('LearnRate',1e-04,'GradientThreshold',1);

actor = rlContinuousDeterministicActor(actorNetwork,observationInfo,actionInfo);

To create the DDPG agent, first specify the DDPG agent options using rlDDPGAgentOptions (Reinforcement Learning Toolbox).

agentOptions = rlDDPGAgentOptions(...
    'ExperienceBufferLength',1e6 ,...
agentOptions.NoiseOptions.Variance = 1e-1;
agentOptions.NoiseOptions.VarianceDecayRate = 1e-6;

Then, create the agent using the specified actor representation, critic representation, and agent options. For more information, see rlDDPGAgent (Reinforcement Learning Toolbox).

agent = rlDDPGAgent(actor,critic,agentOptions);

Train Agent

To train the agent, first specify the training options. For this example, use the following options:

  • Run each training for at most 20000 episodes, with each episode lasting at most ceil(Tf/Ts) time steps.

  • Display the training progress in the Episode Manager dialog box (set the Plots option) and disable the command line display (set the Verbose option to false).

  • Stop training when the agent receives an average cumulative reward greater than 415 over 10 consecutive episodes. At this point, the agent can drive the flying robot to the goal position.

  • Save a copy of the agent for each episode where the cumulative reward is greater than 415.

For more information, see rlTrainingOptions (Reinforcement Learning Toolbox).

maxepisodes = 20000;
maxsteps = ceil(Tf/Ts);
trainingOptions = rlTrainingOptions(...

Train the agent using the train (Reinforcement Learning Toolbox) function. Training 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    
    % Train the agent.
    trainingStats = train(agent,env,trainingOptions);
    % Load the pretrained agent for the example.

Simulate DDPG Agent

To validate the performance of the trained agent, simulate the agent within the environment. For more information on agent simulation, see rlSimulationOptions (Reinforcement Learning Toolbox) and sim (Reinforcement Learning Toolbox).

simOptions = rlSimulationOptions('MaxSteps',maxsteps);
experience = sim(env,agent,simOptions);

{"String":"Figure Flying Robot Visualizer contains an axes object. The axes object contains 3 objects of type quiver, patch, line.","Tex":[],"LaTex":[]}

See Also

(Reinforcement Learning Toolbox) | (Reinforcement Learning Toolbox)

Related Topics