Building world cart-pole in Gazebo Jetty and training in Gazebo simulation with RL
For the past two weeks, I have been working exclusively on developing the CartPole base project using reinforcement learning.
Cart pole is a classic reinforcement learning exercise. A pole is hinged on top of a cart that can move along a line, and since the pole is unstable in the upright position, it falls as soon as it tilts. The goal is to keep it balanced for as long as possible by pushing the cart left or right. The agent is not given any equations of the system: it only observes the state of the cart and the pole, and learns by trial and error which push to apply in each situation, receiving a reward for every step the pole stays up.
For the development of this initial base project, it has been decided to replicate the functionality of the repository simple_cart_pole de Gazebo as well as separate resources such as: Gazebo Community Meeting video, Stable-Baselines3 docs and Gazebo API Python Interfaces.
Building world cart-pole in Gazebo Jetty
All the physics of the project lives in the SDF, so I wrote my own world instead of reusing the example. The model is a cart (a box on four cylindrical wheels) with a pole on top of it.
The interesting part is how the pole is attached to the cart: it has to stay hooked to it but be free to fall to either side. I solved that with a revolute joint, which works like a hinge:
1
2
3
4
5
6
7
8
9
10
11
12
<joint name="pole_base" type="revolute">
<parent>cart_link</parent>
<child>pole_link</child>
<pose>0 0 -0.625 0 0 0</pose>
<axis>
<xyz>0 1 0</xyz>
<limit>
<lower>-1.4</lower>
<upper>1.4</upper>
</limit>
</axis>
</joint>
The pose places the hinge at the bottom end of the pole, the y axis makes it fall forward or backward along the cart’s direction of motion, and the ±1.4 rad limits stop it before it goes through the cart.
The cart is initially moved with forces applied directly to it from the training script, so the wheels have no motors and the world needs no control plugins.
This is what the world looks like after the creation of the SDF.
Training in Gazebo simulation with RL
The training code works as follows:
At each step, the agent receives an observation, a vector of four values describing the state of the system, and chooses an action. The observations are:
- Cart position: tells the agent how close the cart is to the end of the track, since the episode ends if it goes beyond ±4.8 m.
- Cart velocity: shows whether the cart is heading towards that limit or away from it.
- Pole angle: shows how far the pole has tilted from the vertical, which is what the agent has to correct.
- Pole angular velocity: shows whether the pole is falling or straightening up. Two poles at the same angle need opposite actions depending on this, so without it the agent could only guess.
With this information, the agent has to choose between two actions: apply a force to the cart towards the left, or towards the right. The force has a fixed magnitude, so the agent only decides the direction, and it can change it at every step. This is enough to balance the pole: if it tilts to one side, pushing the cart in that direction moves its base under the pole and straightens it, while pushing the other way makes it fall faster. The agent gets a reward of 1 for every step the pole stays up, and the episode ends if the pole tilts more than 0.48 rad or the cart leaves the track..
To control the simulation I use the Gazebo Python bindings. TestFixture loads the SDF and runs the Gazebo server inside the Python process, and two callbacks let me apply the force to the cart before each physics step and read the state after it. The agent is trained with PPO from Stable-Baselines3, the same algorithm used in the example provided by Gazebo.
train_cart_pole.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import os
import subprocess
import time
import gymnasium as gym
import numpy as np
from stable_baselines3 import PPO
from stable_baselines3.common.env_checker import check_env
from gz.sim import TestFixture, World, world_entity, Model, Link, get_install_prefix
from gz.math import Vector3d
SDF = "/RoboticsAcademy/GAZEBO_MUNDOS/prueba_cart_pole.sdf"
STRENGTH = 20.0
STEP_MS = 1
ACTION_MS = 20
STEPS_PER_ACTION = ACTION_MS // STEP_MS
MAX_EPISODE_STEPS = 500
ROUNDS = 15
STEPS_PER_ROUND = 10_000
EVAL_EPISODES = 10
class CartEnv(gym.Env):
def __init__(self):
super().__init__()
self.action_space = gym.spaces.Discrete(2)
self.observation_space = gym.spaces.Box(-np.inf, np.inf, (4,), np.float32)
self.command = None
self.terminated = False
self.reward = 1.0
self.steps = 0
self.state = np.zeros(4, dtype=np.float32)
self.cart = None
self.pole = None
self.fixture = TestFixture(SDF)
self.fixture.on_pre_update(self.on_pre_update)
self.fixture.on_post_update(self.on_post_update)
self.fixture.finalize()
self.server = self.fixture.server()
def on_pre_update(self, info, ecm):
if info.paused:
return
world = World(world_entity(ecm))
model = Model(world.model_by_name(ecm, "cart_pole"))
self.cart = Link(model.link_by_name(ecm, "cart_link"))
self.pole = Link(model.link_by_name(ecm, "pole_link"))
self.cart.enable_velocity_checks(ecm)
self.pole.enable_velocity_checks(ecm)
if self.command == 1:
self.cart.add_world_force(ecm, Vector3d(STRENGTH, 0, 0))
elif self.command == 0:
self.cart.add_world_force(ecm, Vector3d(-STRENGTH, 0, 0))
def on_post_update(self, info, ecm):
if info.paused or self.pole is None:
return
pole_angle = self.pole.world_pose(ecm).rot().euler().y()
w = self.pole.world_angular_velocity(ecm)
pole_ang_vel = w.y() if w is not None else 0.0
cart_x = self.cart.world_pose(ecm).pos().x()
v = self.cart.world_linear_velocity(ecm)
cart_vel = v.x() if v is not None else 0.0
self.state = np.array([cart_x, cart_vel, pole_angle, pole_ang_vel],
dtype=np.float32)
if not self.terminated:
self.terminated = abs(pole_angle) > 0.48 or abs(cart_x) > 4.8
self.reward = 0.0 if self.terminated else 1.0
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
self.server.reset_all()
self.command = None
self.terminated = False
self.steps = 0
self.server.run(True, STEPS_PER_ACTION, False)
return self.state, {}
def step(self, action):
self.command = int(action)
self.server.run(True, STEPS_PER_ACTION, False)
self.steps += 1
truncated = (not self.terminated) and self.steps >= MAX_EPISODE_STEPS
return self.state, self.reward, self.terminated, truncated, {}
def evaluate(model, env, n_episodes):
totals = []
for _ in range(n_episodes):
obs, _ = env.reset()
done, total = False, 0.0
while not done:
action, _ = model.predict(obs, deterministic=True)
obs, r, terminated, truncated, _ = env.step(int(action))
total += r
done = terminated or truncated
totals.append(total)
return float(np.mean(totals)), float(np.std(totals))
def run_gui():
base = os.path.join(get_install_prefix(), "libexec", "gz", "sim10",
"gz-sim-gui-client")
return subprocess.Popen(base)
def show_best(env, model_path):
model = PPO.load(model_path, device="cpu")
gui = run_gui()
time.sleep(10)
print("Showing the best model. Ctrl+C to exit.")
try:
obs, _ = env.reset()
while True:
action, _ = model.predict(obs, deterministic=True)
obs, _, terminated, truncated, _ = env.step(int(action))
time.sleep(ACTION_MS / 1000)
if terminated or truncated:
obs, _ = env.reset()
except KeyboardInterrupt:
pass
finally:
gui.terminate()
if __name__ == "__main__":
env = CartEnv()
check_env(env)
print("check_env OK")
model = PPO("MlpPolicy", env, verbose=1, device="cpu")
best_mean = -1.0
for i in range(ROUNDS):
model.learn(total_timesteps=STEPS_PER_ROUND, reset_num_timesteps=False)
mean, std = evaluate(model, env, EVAL_EPISODES)
print(f"\n=== Round {i + 1}/{ROUNDS} | steps: {(i + 1) * STEPS_PER_ROUND} "
f"| reward: {mean:.1f} ± {std:.1f} "
f"(~{mean * ACTION_MS / 1000:.1f} s with the pole up) ===\n")
if mean >= best_mean:
best_mean = mean
model.save("cartpole_best")
if mean >= 0.98 * MAX_EPISODE_STEPS and std < 10:
print("Solved, stopping the training.")
break
model.save("cartpole_final")
print(f"Best reward: {best_mean:.1f}")
show_best(env, "cartpole_best")
Here is a video showing the agent in operation, once trained.
Once replication has been achieved, the next task would be to modify the world to incorporate ROS. Adding motors to the wheels and operating based on linear and angular velocity rather than forces.
