added simple reacher task
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
from gym.envs.registration import register
|
||||
|
||||
register(
|
||||
id='ALRReacher-v0',
|
||||
entry_point='alr_envs.mujoco:ALRReacherEnv',
|
||||
max_episode_steps=1000,
|
||||
)
|
||||
|
||||
register(
|
||||
id='SimpleReacher-v0',
|
||||
entry_point='alr_envs.classic_control:SimpleReacherEnv',
|
||||
max_episode_steps=200,
|
||||
kwargs={
|
||||
"n_links": 5,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
from alr_envs.classic_control.simple_reacher import SimpleReacherEnv
|
||||
@@ -0,0 +1,166 @@
|
||||
import gym
|
||||
import numpy as np
|
||||
from gym import spaces, utils
|
||||
from gym.utils import seeding
|
||||
|
||||
import matplotlib as mpl
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
mpl.use('Qt5Agg') # or can use 'TkAgg', whatever you have/prefer
|
||||
|
||||
|
||||
class SimpleReacherEnv(gym.Env, utils.EzPickle):
|
||||
"""
|
||||
Simple Reaching Task without any physics simulation.
|
||||
Returns no reward until 150 time steps. This allows the agent to explore the space, but requires precise actions
|
||||
towards the end of the trajectory.
|
||||
"""
|
||||
|
||||
def __init__(self, n_links):
|
||||
super().__init__()
|
||||
self.link_lengths = np.ones(n_links)
|
||||
self.n_links = n_links
|
||||
self.dt = 0.1
|
||||
|
||||
self._goal_pos = None
|
||||
|
||||
self.joints = None
|
||||
self._joint_angle = None
|
||||
self._angle_velocity = None
|
||||
|
||||
self.max_torque = 1 # 10
|
||||
|
||||
action_bound = np.ones((self.n_links,))
|
||||
state_bound = np.hstack([
|
||||
[np.pi] * self.n_links,
|
||||
[np.inf] * self.n_links,
|
||||
[np.inf],
|
||||
[np.inf] # TODO: Maybe
|
||||
])
|
||||
self.action_space = spaces.Box(low=-action_bound, high=action_bound, shape=action_bound.shape)
|
||||
self.observation_space = spaces.Box(low=-state_bound, high=state_bound, shape=state_bound.shape)
|
||||
|
||||
self.fig = None
|
||||
self.metadata = {'render.modes': ["human"]}
|
||||
|
||||
self._steps = 0
|
||||
self.seed()
|
||||
|
||||
def step(self, action):
|
||||
|
||||
action = self._scale_action(action)
|
||||
|
||||
self._angle_velocity = self._angle_velocity + self.dt * action
|
||||
self._joint_angle = angle_normalize(self._joint_angle + self.dt * self._angle_velocity)
|
||||
self._update_joints()
|
||||
self._steps += 1
|
||||
|
||||
reward = self._get_reward(action)
|
||||
|
||||
# done = np.abs(self.end_effector - self._goal_pos) < 0.1
|
||||
done = False
|
||||
|
||||
return self._get_obs().copy(), reward, done, {}
|
||||
|
||||
def _scale_action(self, action):
|
||||
"""
|
||||
scale actions back in order to provide normalized actions \in [0,1]
|
||||
|
||||
Args:
|
||||
action: action to scale
|
||||
|
||||
Returns: action according to self.max_torque
|
||||
|
||||
"""
|
||||
|
||||
ub = self.max_torque
|
||||
lb = -self.max_torque
|
||||
|
||||
action = lb + (action + 1.) * 0.5 * (ub - lb)
|
||||
return np.clip(action, lb, ub)
|
||||
|
||||
def _get_obs(self):
|
||||
return [self._joint_angle, self._angle_velocity, self.end_effector - self._goal_pos, self._steps]
|
||||
|
||||
def _update_joints(self):
|
||||
"""
|
||||
update joints to get new end effector position. The other links are only required for rendering.
|
||||
Returns:
|
||||
|
||||
"""
|
||||
angles = np.cumsum(self._joint_angle)
|
||||
x = self.link_lengths * np.vstack([np.cos(angles), np.sin(angles)])
|
||||
self.joints[1:] = self.joints[0] + np.cumsum(x.T, axis=0)
|
||||
|
||||
def _get_reward(self, action):
|
||||
diff = self.end_effector - self._goal_pos
|
||||
distance = 0
|
||||
|
||||
# TODO: Is this the best option
|
||||
if self._steps > 150:
|
||||
distance = np.exp(-0.1 * diff ** 2).mean()
|
||||
# distance -= (diff ** 2).mean()
|
||||
|
||||
# distance -= action ** 2
|
||||
return distance
|
||||
|
||||
def reset(self):
|
||||
|
||||
# TODO: maybe do initialisation more random?
|
||||
# Sample only orientation of first link, i.e. the arm is always straight.
|
||||
self._joint_angle = np.hstack([[self.np_random.uniform(-np.pi, np.pi)], np.zeros(self.n_links - 1)])
|
||||
self._angle_velocity = np.zeros(self.n_links)
|
||||
self.joints = np.zeros((self.n_links + 1, 2))
|
||||
self._update_joints()
|
||||
|
||||
self._goal_pos = self._get_random_goal()
|
||||
return self._get_obs().copy()
|
||||
|
||||
def _get_random_goal(self):
|
||||
center = self.joints[0]
|
||||
|
||||
# Sample uniformly in circle with radius R around center of reacher.
|
||||
R = np.sum(self.link_lengths)
|
||||
r = R * np.sqrt(self.np_random.uniform())
|
||||
theta = self.np_random.uniform() * 2 * np.pi
|
||||
return center + r * np.stack([np.cos(theta), np.sin(theta)])
|
||||
|
||||
def seed(self, seed=None):
|
||||
self.np_random, seed = seeding.np_random(seed)
|
||||
return [seed]
|
||||
|
||||
def render(self, mode='human'): # pragma: no cover
|
||||
if self.fig is None:
|
||||
self.fig = plt.figure()
|
||||
plt.ion()
|
||||
plt.show()
|
||||
else:
|
||||
plt.figure(self.fig.number)
|
||||
|
||||
plt.cla()
|
||||
|
||||
# Arm
|
||||
plt.plot(self.joints[:, 0], self.joints[:, 1], 'ro-', markerfacecolor='k')
|
||||
|
||||
# goal
|
||||
goal_pos = self._goal_pos.T
|
||||
plt.plot(goal_pos[0], goal_pos[1], 'gx')
|
||||
# distance between end effector and goal
|
||||
plt.plot([self.end_effector[0], goal_pos[0]], [self.end_effector[1], goal_pos[1]], 'g--')
|
||||
|
||||
lim = np.sum(self.link_lengths) + 0.5
|
||||
plt.xlim([-lim, lim])
|
||||
plt.ylim([-lim, lim])
|
||||
plt.draw()
|
||||
plt.pause(0.0001)
|
||||
|
||||
def close(self):
|
||||
del self.fig
|
||||
|
||||
@property
|
||||
def end_effector(self):
|
||||
return self.joints[self.n_links].T
|
||||
|
||||
|
||||
def angle_normalize(x):
|
||||
return ((x + np.pi) % (2 * np.pi)) - np.pi
|
||||
@@ -0,0 +1 @@
|
||||
from alr_envs.mujoco.alr_reacher import ALRReacherEnv
|
||||
@@ -0,0 +1,46 @@
|
||||
import numpy as np
|
||||
import os
|
||||
from gym import utils
|
||||
from gym.envs.mujoco import mujoco_env
|
||||
|
||||
|
||||
class ALRReacherEnv(mujoco_env.MujocoEnv, utils.EzPickle):
|
||||
def __init__(self):
|
||||
utils.EzPickle.__init__(self)
|
||||
mujoco_env.MujocoEnv.__init__(self, os.path.join(os.path.dirname(__file__), "assets", 'reacher_5links.xml'), 2)
|
||||
|
||||
def step(self, a):
|
||||
vec = self.get_body_com("fingertip") - self.get_body_com("target")
|
||||
reward_dist = - np.linalg.norm(vec)
|
||||
reward_ctrl = - np.square(a).sum()
|
||||
reward = reward_dist + reward_ctrl
|
||||
self.do_simulation(a, self.frame_skip)
|
||||
ob = self._get_obs()
|
||||
done = False
|
||||
return ob, reward, done, dict(reward_dist=reward_dist, reward_ctrl=reward_ctrl)
|
||||
|
||||
def viewer_setup(self):
|
||||
self.viewer.cam.trackbodyid = 0
|
||||
|
||||
def reset_model(self):
|
||||
qpos = self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nq) + self.init_qpos
|
||||
while True:
|
||||
self.goal = self.np_random.uniform(low=-.2, high=.2, size=2)
|
||||
if np.linalg.norm(self.goal) < 0.2:
|
||||
break
|
||||
qpos[-2:] = self.goal
|
||||
qvel = self.init_qvel + self.np_random.uniform(low=-.005, high=.005, size=self.model.nv)
|
||||
qvel[-2:] = 0
|
||||
self.set_state(qpos, qvel)
|
||||
|
||||
return self._get_obs()
|
||||
|
||||
def _get_obs(self):
|
||||
theta = self.sim.data.qpos.flat[:5]
|
||||
return np.concatenate([
|
||||
np.cos(theta),
|
||||
np.sin(theta),
|
||||
self.sim.data.qpos.flat[5:], # this is goal position
|
||||
self.sim.data.qvel.flat[:5], # this is angular velocity
|
||||
self.get_body_com("fingertip") - self.get_body_com("target")
|
||||
])
|
||||
@@ -0,0 +1,54 @@
|
||||
<mujoco model="reacher">
|
||||
<compiler angle="radian" inertiafromgeom="true"/>
|
||||
<default>
|
||||
<joint armature="1" damping="1" limited="true"/>
|
||||
<geom contype="0" friction="1 0.1 0.1" rgba="0.7 0.7 0 1"/>
|
||||
</default>
|
||||
<option gravity="0 0 -9.81" integrator="RK4" timestep="0.01"/>
|
||||
<worldbody>
|
||||
<!-- Arena -->
|
||||
<geom conaffinity="0" contype="0" name="ground" pos="0 0 0" rgba="0.9 0.9 0.9 1" size="1 1 10" type="plane"/>
|
||||
<geom conaffinity="0" fromto="-.6 -.6 .01 .6 -.6 .01" name="sideS" rgba="0.9 0.4 0.6 1" size=".02" type="capsule"/>
|
||||
<geom conaffinity="0" fromto=" .6 -.6 .01 .6 .6 .01" name="sideE" rgba="0.9 0.4 0.6 1" size=".02" type="capsule"/>
|
||||
<geom conaffinity="0" fromto="-.6 .6 .01 .6 .6 .01" name="sideN" rgba="0.9 0.4 0.6 1" size=".02" type="capsule"/>
|
||||
<geom conaffinity="0" fromto="-.6 -.6 .01 -.6 .6 .01" name="sideW" rgba="0.9 0.4 0.6 1" size=".02" type="capsule"/>
|
||||
<!-- Arm -->
|
||||
<geom conaffinity="0" contype="0" fromto="0 0 0 0 0 0.02" name="root" rgba="0.9 0.4 0.6 1" size=".011" type="cylinder"/>
|
||||
<body name="body0" pos="0 0 .01">
|
||||
<geom fromto="0 0 0 0.1 0 0" name="link0" rgba="0.0 0.4 0.6 1" size=".01" type="capsule"/>
|
||||
<joint axis="0 0 1" limited="false" name="joint0" pos="0 0 0" type="hinge"/>
|
||||
<body name="body1" pos="0.1 0 0">
|
||||
<joint axis="0 0 1" limited="false" name="joint1" pos="0 0 0" type="hinge"/>
|
||||
<geom fromto="0 0 0 0.1 0 0" name="link1" rgba="0.0 0.4 0.6 1" size=".01" type="capsule"/>
|
||||
<body name="body2" pos="0.1 0 0">
|
||||
<joint axis="0 0 1" limited="false" name="joint2" pos="0 0 0" type="hinge"/>
|
||||
<geom fromto="0 0 0 0.1 0 0" name="link2" rgba="0.0 0.4 0.6 1" size=".01" type="capsule"/>
|
||||
<body name="body3" pos="0.1 0 0">
|
||||
<joint axis="0 0 1" limited="false" name="joint3" pos="0 0 0" type="hinge"/>
|
||||
<geom fromto="0 0 0 0.1 0 0" name="link3" rgba="0.0 0.4 0.6 1" size=".01" type="capsule"/>
|
||||
<body name="body4" pos="0.1 0 0">
|
||||
<joint axis="0 0 1" limited="true" name="joint4" pos="0 0 0" range="-3.0 3.0" type="hinge"/>
|
||||
<geom fromto="0 0 0 0.1 0 0" name="link4" rgba="0.0 0.4 0.6 1" size=".01" type="capsule"/>
|
||||
<body name="fingertip" pos="0.11 0 0">
|
||||
<geom contype="0" name="fingertip" pos="0 0 0" rgba="0.0 0.8 0.6 1" size=".01" type="sphere"/>
|
||||
</body>
|
||||
</body>
|
||||
</body>
|
||||
</body>
|
||||
</body>
|
||||
</body>
|
||||
<!-- Target -->
|
||||
<body name="target" pos=".1 -.1 .01">
|
||||
<joint armature="0" axis="1 0 0" damping="0" limited="true" name="target_x" pos="0 0 0" range="-.27 .27" ref=".1" stiffness="0" type="slide"/>
|
||||
<joint armature="0" axis="0 1 0" damping="0" limited="true" name="target_y" pos="0 0 0" range="-.27 .27" ref="-.1" stiffness="0" type="slide"/>
|
||||
<geom conaffinity="0" contype="0" name="target" pos="0 0 0" rgba="0.9 0.2 0.2 1" size=".009" type="sphere"/>
|
||||
</body>
|
||||
</worldbody>
|
||||
<actuator>
|
||||
<motor ctrllimited="true" ctrlrange="-1.0 1.0" gear="200.0" joint="joint0"/>
|
||||
<motor ctrllimited="true" ctrlrange="-1.0 1.0" gear="200.0" joint="joint1"/>
|
||||
<motor ctrllimited="true" ctrlrange="-1.0 1.0" gear="200.0" joint="joint2"/>
|
||||
<motor ctrllimited="true" ctrlrange="-1.0 1.0" gear="200.0" joint="joint3"/>
|
||||
<motor ctrllimited="true" ctrlrange="-1.0 1.0" gear="200.0" joint="joint4"/>
|
||||
</actuator>
|
||||
</mujoco>
|
||||
Reference in New Issue
Block a user