2021-05-12 09:52:25 +02:00
|
|
|
from typing import Union
|
|
|
|
|
2021-01-11 16:08:42 +01:00
|
|
|
import gym
|
|
|
|
import matplotlib.pyplot as plt
|
2021-05-12 09:52:25 +02:00
|
|
|
import numpy as np
|
|
|
|
from gym.utils import seeding
|
2021-01-11 16:08:42 +01:00
|
|
|
from matplotlib import patches
|
2021-03-26 14:05:16 +01:00
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
from alr_envs.classic_control.utils import check_self_collision
|
2021-03-26 14:05:16 +01:00
|
|
|
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-06-24 15:19:05 +02:00
|
|
|
class HoleReacherEnv(gym.Env):
|
2021-03-26 14:05:16 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def __init__(self, n_links: int, hole_x: Union[None, float] = None, hole_depth: Union[None, float] = None,
|
|
|
|
hole_width: float = 1., random_start: bool = False, allow_self_collision: bool = False,
|
2021-05-18 15:27:08 +02:00
|
|
|
allow_wall_collision: bool = False, collision_penalty: float = 1000):
|
2021-05-12 17:48:57 +02:00
|
|
|
|
2021-03-26 14:05:16 +01:00
|
|
|
self.n_links = n_links
|
|
|
|
self.link_lengths = np.ones((n_links, 1))
|
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
self.random_start = random_start
|
2021-03-26 14:05:16 +01:00
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
# provided initial parameters
|
2021-06-25 16:16:56 +02:00
|
|
|
self.initial_x = hole_x # x-position of center of hole
|
|
|
|
self.initial_width = hole_width # width of hole
|
|
|
|
self.initial_depth = hole_depth # depth of hole
|
2021-05-12 09:52:25 +02:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
# temp container for current env state
|
2021-06-25 16:16:56 +02:00
|
|
|
self._tmp_x = None
|
|
|
|
self._tmp_width = None
|
|
|
|
self._tmp_depth = None
|
2021-05-12 17:48:57 +02:00
|
|
|
self._goal = None # x-y coordinates for reaching the center at the bottom of the hole
|
2021-03-26 14:05:16 +01:00
|
|
|
|
|
|
|
# collision
|
2021-01-11 16:08:42 +01:00
|
|
|
self.allow_self_collision = allow_self_collision
|
|
|
|
self.allow_wall_collision = allow_wall_collision
|
|
|
|
self.collision_penalty = collision_penalty
|
|
|
|
|
2021-03-26 14:05:16 +01:00
|
|
|
# state
|
2021-05-12 17:48:57 +02:00
|
|
|
self._joints = None
|
2021-01-11 16:08:42 +01:00
|
|
|
self._joint_angles = None
|
|
|
|
self._angle_velocity = None
|
2021-05-12 09:52:25 +02:00
|
|
|
self._start_pos = np.hstack([[np.pi / 2], np.zeros(self.n_links - 1)])
|
|
|
|
self._start_vel = np.zeros(self.n_links)
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-06-23 18:23:37 +02:00
|
|
|
self._dt = 0.01
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-03-26 14:05:16 +01:00
|
|
|
action_bound = np.pi * np.ones((self.n_links,))
|
2021-01-11 16:08:42 +01:00
|
|
|
state_bound = np.hstack([
|
2021-03-26 14:05:16 +01:00
|
|
|
[np.pi] * self.n_links, # cos
|
|
|
|
[np.pi] * self.n_links, # sin
|
|
|
|
[np.inf] * self.n_links, # velocity
|
2021-05-12 09:52:25 +02:00
|
|
|
[np.inf], # hole width
|
2021-05-18 15:27:08 +02:00
|
|
|
# [np.inf], # hole depth
|
2021-01-11 16:08:42 +01:00
|
|
|
[np.inf] * 2, # x-y coordinates of target distance
|
|
|
|
[np.inf] # env steps, because reward start after n steps TODO: Maybe
|
|
|
|
])
|
|
|
|
self.action_space = gym.spaces.Box(low=-action_bound, high=action_bound, shape=action_bound.shape)
|
|
|
|
self.observation_space = gym.spaces.Box(low=-state_bound, high=state_bound, shape=state_bound.shape)
|
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
# containers for plotting
|
|
|
|
self.metadata = {'render.modes': ["human", "partial"]}
|
2021-01-11 16:08:42 +01:00
|
|
|
self.fig = None
|
2021-05-12 09:52:25 +02:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
self._steps = 0
|
2021-05-12 09:52:25 +02:00
|
|
|
self.seed()
|
|
|
|
|
2021-06-23 18:23:37 +02:00
|
|
|
@property
|
|
|
|
def dt(self) -> Union[float, int]:
|
|
|
|
return self._dt
|
|
|
|
|
2021-07-02 13:09:56 +02:00
|
|
|
# @property
|
|
|
|
# def start_pos(self):
|
|
|
|
# return self._start_pos
|
|
|
|
|
|
|
|
@property
|
|
|
|
def current_pos(self):
|
|
|
|
return self._joint_angles.copy()
|
|
|
|
|
2021-06-25 16:16:56 +02:00
|
|
|
@property
|
2021-07-02 13:09:56 +02:00
|
|
|
def current_vel(self):
|
|
|
|
return self._angle_velocity.copy()
|
2021-06-25 16:16:56 +02:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def step(self, action: np.ndarray):
|
|
|
|
"""
|
|
|
|
A single step with an action in joint velocity space
|
|
|
|
"""
|
2021-05-12 09:52:25 +02:00
|
|
|
|
2021-05-21 15:44:49 +02:00
|
|
|
acc = (action - self._angle_velocity) / self.dt
|
2021-05-12 17:48:57 +02:00
|
|
|
self._angle_velocity = action
|
2021-05-27 17:08:26 +02:00
|
|
|
self._joint_angles = self._joint_angles + self.dt * self._angle_velocity # + 0.001 * np.random.randn(5)
|
2021-05-12 17:48:57 +02:00
|
|
|
self._update_joints()
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
reward, info = self._get_reward(acc)
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
info.update({"is_collided": self._is_collided})
|
2021-05-27 17:08:26 +02:00
|
|
|
self.end_effector_traj.append(np.copy(self.end_effector))
|
2021-05-12 09:52:25 +02:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
self._steps += 1
|
|
|
|
done = self._is_collided
|
2021-05-12 09:52:25 +02:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
return self._get_obs().copy(), reward, done, info
|
2021-02-17 17:48:05 +01:00
|
|
|
|
2021-01-12 10:52:08 +01:00
|
|
|
def reset(self):
|
2021-05-12 09:52:25 +02:00
|
|
|
if self.random_start:
|
2021-06-24 15:06:25 +02:00
|
|
|
# Maybe change more than first seed
|
2021-05-12 09:52:25 +02:00
|
|
|
first_joint = self.np_random.uniform(np.pi / 4, 3 * np.pi / 4)
|
|
|
|
self._joint_angles = np.hstack([[first_joint], np.zeros(self.n_links - 1)])
|
2021-05-12 17:48:57 +02:00
|
|
|
self._start_pos = self._joint_angles.copy()
|
2021-05-12 09:52:25 +02:00
|
|
|
else:
|
|
|
|
self._joint_angles = self._start_pos
|
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
self._generate_hole()
|
|
|
|
self._set_patches()
|
2021-05-12 09:52:25 +02:00
|
|
|
|
|
|
|
self._angle_velocity = self._start_vel
|
2021-03-26 14:05:16 +01:00
|
|
|
self._joints = np.zeros((self.n_links + 1, 2))
|
2021-01-12 10:52:08 +01:00
|
|
|
self._update_joints()
|
|
|
|
self._steps = 0
|
2021-05-27 17:08:26 +02:00
|
|
|
self.end_effector_traj = []
|
2021-01-12 10:52:08 +01:00
|
|
|
|
|
|
|
return self._get_obs().copy()
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def _generate_hole(self):
|
2021-07-19 11:57:06 +02:00
|
|
|
if self.initial_width is None:
|
2021-07-19 14:04:14 +02:00
|
|
|
width = self.np_random.uniform(0.15, 0.5)
|
2021-07-19 11:57:06 +02:00
|
|
|
else:
|
|
|
|
width = np.copy(self.initial_width)
|
|
|
|
if self.initial_x is None:
|
|
|
|
# sample whole on left or right side
|
|
|
|
direction = np.random.choice([-1, 1])
|
|
|
|
# Hole center needs to be half the width away from the arm to give a valid setting.
|
2021-07-19 14:04:14 +02:00
|
|
|
x = direction * self.np_random.uniform(width / 2, 3.5)
|
2021-07-19 11:57:06 +02:00
|
|
|
else:
|
|
|
|
x = np.copy(self.initial_x)
|
|
|
|
if self.initial_depth is None:
|
|
|
|
# TODO we do not want this right now.
|
2021-07-19 14:04:14 +02:00
|
|
|
depth = self.np_random.uniform(1, 1)
|
2021-07-19 11:57:06 +02:00
|
|
|
else:
|
|
|
|
depth = np.copy(self.initial_depth)
|
|
|
|
|
2021-07-19 14:04:14 +02:00
|
|
|
self._tmp_width = width
|
|
|
|
self._tmp_x = x
|
|
|
|
self._tmp_depth = depth
|
|
|
|
self._goal = np.hstack([self._tmp_x, -self._tmp_depth])
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
def _update_joints(self):
|
|
|
|
"""
|
|
|
|
update _joints to get new end effector position. The other links are only required for rendering.
|
|
|
|
Returns:
|
|
|
|
|
|
|
|
"""
|
2021-05-12 17:48:57 +02:00
|
|
|
line_points_in_taskspace = self._get_forward_kinematics(num_points_per_link=20)
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
self._joints[1:, 0] = self._joints[0, 0] + line_points_in_taskspace[:, -1, 0]
|
|
|
|
self._joints[1:, 1] = self._joints[0, 1] + line_points_in_taskspace[:, -1, 1]
|
|
|
|
|
|
|
|
self_collision = False
|
|
|
|
wall_collision = False
|
|
|
|
|
|
|
|
if not self.allow_self_collision:
|
2021-04-21 10:45:34 +02:00
|
|
|
self_collision = check_self_collision(line_points_in_taskspace)
|
2021-01-11 16:08:42 +01:00
|
|
|
if np.any(np.abs(self._joint_angles) > np.pi) and not self.allow_self_collision:
|
|
|
|
self_collision = True
|
|
|
|
|
|
|
|
if not self.allow_wall_collision:
|
2021-05-12 17:48:57 +02:00
|
|
|
wall_collision = self._check_wall_collision(line_points_in_taskspace)
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
self._is_collided = self_collision or wall_collision
|
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def _get_reward(self, acc: np.ndarray):
|
2021-05-18 15:27:08 +02:00
|
|
|
reward = 0
|
|
|
|
# success = False
|
|
|
|
|
|
|
|
if self._steps == 199 or self._is_collided:
|
2021-05-12 17:48:57 +02:00
|
|
|
# return reward only in last time step
|
2021-05-18 15:27:08 +02:00
|
|
|
# Episode also terminates when colliding, hence return reward
|
2021-05-12 17:48:57 +02:00
|
|
|
dist = np.linalg.norm(self.end_effector - self._goal)
|
2021-05-18 15:27:08 +02:00
|
|
|
# success = dist < 0.005 and not self._is_collided
|
|
|
|
reward = - dist ** 2 - self.collision_penalty * self._is_collided
|
2021-05-12 17:48:57 +02:00
|
|
|
|
|
|
|
reward -= 5e-8 * np.sum(acc ** 2)
|
2021-05-18 15:27:08 +02:00
|
|
|
# info = {"is_success": success}
|
2021-05-12 17:48:57 +02:00
|
|
|
|
2021-05-18 15:27:08 +02:00
|
|
|
return reward, {} # info
|
2021-05-12 17:48:57 +02:00
|
|
|
|
2021-01-11 16:08:42 +01:00
|
|
|
def _get_obs(self):
|
|
|
|
theta = self._joint_angles
|
|
|
|
return np.hstack([
|
|
|
|
np.cos(theta),
|
|
|
|
np.sin(theta),
|
|
|
|
self._angle_velocity,
|
2021-06-25 16:16:56 +02:00
|
|
|
self._tmp_width,
|
2021-05-18 15:27:08 +02:00
|
|
|
# self._tmp_hole_depth,
|
2021-05-12 17:48:57 +02:00
|
|
|
self.end_effector - self._goal,
|
2021-01-11 16:08:42 +01:00
|
|
|
self._steps
|
|
|
|
])
|
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def _get_forward_kinematics(self, num_points_per_link=1):
|
2021-01-11 16:08:42 +01:00
|
|
|
theta = self._joint_angles[:, None]
|
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
intermediate_points = np.linspace(0, 1, num_points_per_link) if num_points_per_link > 1 else 1
|
2021-01-11 16:08:42 +01:00
|
|
|
accumulated_theta = np.cumsum(theta, axis=0)
|
2021-05-12 09:52:25 +02:00
|
|
|
end_effector = np.zeros(shape=(self.n_links, num_points_per_link, 2))
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
x = np.cos(accumulated_theta) * self.link_lengths * intermediate_points
|
|
|
|
y = np.sin(accumulated_theta) * self.link_lengths * intermediate_points
|
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
end_effector[0, :, 0] = x[0, :]
|
|
|
|
end_effector[0, :, 1] = y[0, :]
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-03-26 14:05:16 +01:00
|
|
|
for i in range(1, self.n_links):
|
2021-05-12 09:52:25 +02:00
|
|
|
end_effector[i, :, 0] = x[i, :] + end_effector[i - 1, -1, 0]
|
|
|
|
end_effector[i, :, 1] = y[i, :] + end_effector[i - 1, -1, 1]
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
return np.squeeze(end_effector + self._joints[0, :])
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def _check_wall_collision(self, line_points):
|
2021-01-11 16:08:42 +01:00
|
|
|
# all points that are before the hole in x
|
2021-06-25 16:16:56 +02:00
|
|
|
r, c = np.where(line_points[:, :, 0] < (self._tmp_x - self._tmp_width / 2))
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
# check if any of those points are below surface
|
|
|
|
nr_line_points_below_surface_before_hole = np.sum(line_points[r, c, 1] < 0)
|
|
|
|
|
|
|
|
if nr_line_points_below_surface_before_hole > 0:
|
|
|
|
return True
|
|
|
|
|
|
|
|
# all points that are after the hole in x
|
2021-06-25 16:16:56 +02:00
|
|
|
r, c = np.where(line_points[:, :, 0] > (self._tmp_x + self._tmp_width / 2))
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
# check if any of those points are below surface
|
|
|
|
nr_line_points_below_surface_after_hole = np.sum(line_points[r, c, 1] < 0)
|
|
|
|
|
|
|
|
if nr_line_points_below_surface_after_hole > 0:
|
|
|
|
return True
|
|
|
|
|
|
|
|
# all points that are above the hole
|
2021-06-25 16:16:56 +02:00
|
|
|
r, c = np.where((line_points[:, :, 0] > (self._tmp_x - self._tmp_width / 2)) & (
|
|
|
|
line_points[:, :, 0] < (self._tmp_x + self._tmp_width / 2)))
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
# check if any of those points are below surface
|
2021-06-25 16:16:56 +02:00
|
|
|
nr_line_points_below_surface_in_hole = np.sum(line_points[r, c, 1] < -self._tmp_depth)
|
2021-01-11 16:08:42 +01:00
|
|
|
|
|
|
|
if nr_line_points_below_surface_in_hole > 0:
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
def render(self, mode='human'):
|
|
|
|
if self.fig is None:
|
2021-05-12 17:48:57 +02:00
|
|
|
# Create base figure once on the beginning. Afterwards only update
|
2021-05-12 09:52:25 +02:00
|
|
|
plt.ion()
|
2021-01-11 16:08:42 +01:00
|
|
|
self.fig = plt.figure()
|
2021-05-12 09:52:25 +02:00
|
|
|
ax = self.fig.add_subplot(1, 1, 1)
|
|
|
|
|
|
|
|
# limits
|
|
|
|
lim = np.sum(self.link_lengths) + 0.5
|
|
|
|
ax.set_xlim([-lim, lim])
|
|
|
|
ax.set_ylim([-1.1, lim])
|
|
|
|
|
|
|
|
self.line, = ax.plot(self._joints[:, 0], self._joints[:, 1], 'ro-', markerfacecolor='k')
|
2021-05-12 17:48:57 +02:00
|
|
|
self._set_patches()
|
2021-05-12 09:52:25 +02:00
|
|
|
self.fig.show()
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
self.fig.gca().set_title(
|
|
|
|
f"Iteration: {self._steps}, distance: {self.end_effector - self._goal}")
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
if mode == "human":
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
# arm
|
|
|
|
self.line.set_data(self._joints[:, 0], self._joints[:, 1])
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 09:52:25 +02:00
|
|
|
self.fig.canvas.draw()
|
|
|
|
self.fig.canvas.flush_events()
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-01-12 10:52:08 +01:00
|
|
|
elif mode == "partial":
|
|
|
|
if self._steps % 20 == 0 or self._steps in [1, 199] or self._is_collided:
|
|
|
|
# Arm
|
2021-05-12 17:48:57 +02:00
|
|
|
plt.plot(self._joints[:, 0], self._joints[:, 1], 'ro-', markerfacecolor='k',
|
|
|
|
alpha=self._steps / 200)
|
2021-01-12 10:52:08 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
def _set_patches(self):
|
|
|
|
if self.fig is not None:
|
|
|
|
self.fig.gca().patches = []
|
2021-06-25 16:16:56 +02:00
|
|
|
left_block = patches.Rectangle((-self.n_links, -self._tmp_depth),
|
|
|
|
self.n_links + self._tmp_x - self._tmp_width / 2,
|
|
|
|
self._tmp_depth,
|
2021-05-12 17:48:57 +02:00
|
|
|
fill=True, edgecolor='k', facecolor='k')
|
2021-06-25 16:16:56 +02:00
|
|
|
right_block = patches.Rectangle((self._tmp_x + self._tmp_width / 2, -self._tmp_depth),
|
|
|
|
self.n_links - self._tmp_x + self._tmp_width / 2,
|
|
|
|
self._tmp_depth,
|
2021-05-12 17:48:57 +02:00
|
|
|
fill=True, edgecolor='k', facecolor='k')
|
2021-06-25 16:16:56 +02:00
|
|
|
hole_floor = patches.Rectangle((self._tmp_x - self._tmp_width / 2, -self._tmp_depth),
|
|
|
|
self._tmp_width,
|
|
|
|
1 - self._tmp_depth,
|
2021-05-12 17:48:57 +02:00
|
|
|
fill=True, edgecolor='k', facecolor='k')
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-05-12 17:48:57 +02:00
|
|
|
# Add the patch to the Axes
|
|
|
|
self.fig.gca().add_patch(left_block)
|
|
|
|
self.fig.gca().add_patch(right_block)
|
|
|
|
self.fig.gca().add_patch(hole_floor)
|
2021-01-11 16:08:42 +01:00
|
|
|
|
2021-06-24 15:06:25 +02:00
|
|
|
def seed(self, seed=None):
|
|
|
|
self.np_random, seed = seeding.np_random(seed)
|
|
|
|
return [seed]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def end_effector(self):
|
|
|
|
return self._joints[self.n_links].T
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
super().close()
|
|
|
|
if self.fig is not None:
|
|
|
|
plt.close(self.fig)
|