# 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 having a radius of 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"; open_system(mdl)```

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 ${\mathit{r}}_{\mathit{t}}$ provided at every time step is

`${\mathit{r}}_{1}=10\left(\left({{\mathit{x}}_{\mathit{t}}}^{2}+{{\mathit{y}}_{\mathit{t}}}^{2}+{\theta }_{\mathit{t}}{\text{\hspace{0.17em}}}^{2}\right)<0.5\right)$`

`${\mathit{r}}_{2}=-100\left(|{\mathit{x}}_{\mathit{t}}|\ge 20\text{\hspace{0.17em}}||\text{\hspace{0.17em}}|{\mathit{y}}_{\mathit{t}}|\ge 20\right)$`

`${\mathit{r}}_{3}=-\left(0.2{\left({\mathit{R}}_{\mathit{t}-1}+{\mathit{L}}_{\mathit{t}-1}\right)}^{2\text{\hspace{0.17em}}}+0.3{\left({\mathit{R}}_{\mathit{t}-1}-{\mathit{L}}_{\mathit{t}-1}\right)}^{2}+0.03{{\mathit{x}}_{\mathit{t}}}^{2}+0.03{{\mathit{y}}_{\mathit{t}}}^{2}+0.02{\theta }_{\mathit{t}}{\text{\hspace{0.17em}}}^{2}\right)$`

`${\mathit{r}}_{\mathit{t}}={\mathit{r}}_{1}+{\mathit{r}}_{2}+{\mathit{r}}_{3}$`

where:

• ${\mathit{x}}_{\mathit{t}}$ is the position of the robot along the x-axis.

• ${\mathit{y}}_{\mathit{t}}$ is the position of the robot along the y-axis.

• $\theta {\text{\hspace{0.17em}}}_{\mathit{t}}$ is the orientation of the robot.

• ${\mathit{L}}_{\mathit{t}-1}$ is the control effort from the left thruster.

• ${\mathit{R}}_{\mathit{t}-1}$ is the control effort from the right thruster.

• ${\mathit{r}}_{1}$ is the reward when the robot is close to the goal.

• ${\mathit{r}}_{2}$ is the penalty when the robot drives beyond 20 m in either the x or y direction. The simulation is terminated when ${\mathit{r}}_{2}<0$.

• ${\mathit{r}}_{3}$ 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 a Simulink model containing an RL Agent block that is ready for training.

```integratedMdl = "IntegratedFlyingRobot"; [~,agentBlk,obsInfo,actInfo] = ... 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 vector for this environment is ${\left[\begin{array}{ccccccc}\mathit{x}& \mathit{y}& \stackrel{˙}{\mathit{x}}& \stackrel{˙}{\mathit{y}}& \mathrm{sin}\left(\theta \text{\hspace{0.17em}}\right)& \mathrm{cos}\left(\theta \right)& \stackrel{˙}{\theta \text{\hspace{0.17em}}}\end{array}\right]}^{\mathit{T}}$. Assign a name to the environment observation channel.

`obsInfo.Name = "observations";`

The action vector for this environment is ${\left[\begin{array}{cc}{\mathit{T}}_{\mathit{R}}& {\mathit{T}}_{\mathit{L}}\end{array}\right]}^{\mathit{T}}$. Assign a name, as well as upper and lower limits, to the environment action channel.

```actInfo.Name = "thrusts"; actInfo.LowerLimit = -ones(prod(actInfo.Dimension),1); actInfo.UpperLimit = ones(prod(actInfo.Dimension),1);```

Note that `prod(obsInfo.Dimension)` and `prod(actInfo.Dimension)` return the number of dimensions of the observation and action spaces, respectively, regardless of whether they are arranged as row vectors, column vectors, or matrices.

### Create Environment Object

Create an environment object using the integrated Simulink model.

```env = rlSimulinkEnv( ... integratedMdl, ... agentBlk, ... obsInfo, ... actInfo);```

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

`rng(0)`

### Create DDPG agent

DDPG agents use a parametrized Q-value function approximator to estimate the value of the policy. A Q-value function critic takes the current observation and an action as inputs and returns a single scalar as output (the estimated discounted cumulative long-term reward given the action from the state corresponding to the current observation, and following the policy thereafter).

To model the parametrized Q-value function within the critic, use a neural network with two input layers (one for the observation channel, as specified by `obsInfo`, and the other for the action channel, as specified by `actInfo`) and one output layer (which returns the scalar value).

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.

```% Specify the number of outputs for the hidden layers. hiddenLayerSize = 100; % Define observation path layers observationPath = [ featureInputLayer( ... prod(obsInfo.Dimension),Name="obsInLyr") fullyConnectedLayer(hiddenLayerSize) reluLayer fullyConnectedLayer(hiddenLayerSize) additionLayer(2,Name="add") reluLayer fullyConnectedLayer(hiddenLayerSize) reluLayer fullyConnectedLayer(1,Name="fc4") ]; % Define action path layers actionPath = [ featureInputLayer( ... prod(actInfo.Dimension), ... Name="actInLyr") fullyConnectedLayer(hiddenLayerSize,Name="fc5") ]; % 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); % Display the number of parameters summary(criticNetwork)```
``` Initialized: true Number of learnables: 21.4k Inputs: 1 'obsInLyr' 7 features 2 'actInLyr' 2 features ```

Create the critic using `criticNetwork`, the environment specifications, and the names of the network input layers to be connected to the observation and action channels. For more information see `rlQValueFunction` (Reinforcement Learning Toolbox).

```critic = rlQValueFunction(criticNetwork,obsInfo,actInfo,... ObservationInputNames="obsInLyr",ActionInputNames="actInLyr");```

DDPG agents use 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 `actInfo`).

Define the network as an array of layer objects.

```actorNetwork = [ featureInputLayer(prod(obsInfo.Dimension)) fullyConnectedLayer(hiddenLayerSize) reluLayer fullyConnectedLayer(hiddenLayerSize) reluLayer fullyConnectedLayer(hiddenLayerSize) reluLayer fullyConnectedLayer(prod(actInfo.Dimension)) tanhLayer ];```

Convert the array of layer object to a `dlnetwork` object and display the number of parameters.

```actorNetwork = dlnetwork(actorNetwork); summary(actorNetwork)```
``` Initialized: true Number of learnables: 21.2k Inputs: 1 'input' 7 features ```

Define the actor using `actorNetwork`, and the specifications for the action and observation channels. For more information, see `rlContinuousDeterministicActor` (Reinforcement Learning Toolbox).

`actor = rlContinuousDeterministicActor(actorNetwork,obsInfo,actInfo);`

Specify options for the critic and the actor using `rlOptimizerOptions` (Reinforcement Learning Toolbox).

```criticOptions = rlOptimizerOptions(LearnRate=1e-03,GradientThreshold=1); actorOptions = rlOptimizerOptions(LearnRate=1e-04,GradientThreshold=1);```

Specify the DDPG agent options using `rlDDPGAgentOptions` (Reinforcement Learning Toolbox), include the training options for the actor and critic.

```agentOptions = rlDDPGAgentOptions(... SampleTime=Ts,... ActorOptimizerOptions=actorOptions,... CriticOptimizerOptions=criticOptions,... ExperienceBufferLength=1e6 ,... MiniBatchSize=256); agentOptions.NoiseOptions.Variance = 1e-1; agentOptions.NoiseOptions.VarianceDecayRate = 1e-6;```

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

`agent = rlDDPGAgent(actor,critic,agentOptions);`

Alternatively, you can create the agent first, and then access its option object and modify the options using dot notation.

### 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(... MaxEpisodes=maxepisodes,... MaxStepsPerEpisode=maxsteps,... StopOnError="on",... Verbose=false,... Plots="training-progress",... StopTrainingCriteria="AverageReward",... StopTrainingValue=415,... ScoreAveragingWindowLength=10,... SaveAgentCriteria="EpisodeReward",... SaveAgentValue=415); ```

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); else % Load the pretrained agent for the example. load("FlyingRobotDDPG.mat","agent") end```

### 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);```