-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathreacher.py
215 lines (179 loc) · 6.79 KB
/
reacher.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Reacher task."""
# global
import ivy
import gym
import numpy as np
# noinspection PyAttributeOutsideInit
class Reacher(gym.Env):
metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30}
def __init__(self, num_joints=2): # noqa
"""Initialize Reacher environment
Parameters
----------
num_joints
Number of joints in reacher.
"""
self.num_joints = num_joints
self.torque_scale = 1.0
self.dt = 0.05
self.action_space = gym.spaces.Box(
low=-1.0, high=1.0, shape=[num_joints], dtype=np.float32
)
high = np.array([np.inf] * (num_joints * 3 + 2), dtype=np.float32)
self.observation_space = gym.spaces.Box(low=-high, high=high, dtype=np.float32)
self.viewer = None
self._logged_headless_message = False
def get_observation(self):
"""Get observation from environment.
Returns
-------
ret
observation array
"""
ob = (
ivy.reshape(ivy.cos(self.angles), (1, 2)),
ivy.reshape(ivy.sin(self.angles), (1, 2)),
ivy.reshape(self.angle_vels, (1, 2)),
ivy.reshape(self.goal_xy, (1, 2)),
)
ob = ivy.concat(ob, axis=0)
return ivy.reshape(ob, (-1,))
def get_reward(self):
"""Get reward based on current state
Returns
-------
ret
Reward array
"""
# Goal proximity.
x = ivy.sum(ivy.cos(self.angles), axis=-1)
y = ivy.sum(ivy.sin(self.angles), axis=-1)
xy = ivy.concat(
[ivy.expand_dims(x, axis=0), ivy.expand_dims(y, axis=0)], axis=0
)
rew = ivy.reshape(
ivy.exp(-1 * ivy.sum((xy - self.goal_xy) ** 2, axis=-1)), (-1,)
)
return ivy.mean(rew, axis=0, keepdims=True)
def get_state(self):
"""Get current state in environment.
Returns
-------
ret
angles, angular velocities, and goal xy arrays
"""
return self.angles, self.angle_vels, self.goal_xy
def set_state(self, state):
"""Set current state in environment.
Parameters
----------
state
tuple of angles, angular_velocities, and goal xy arrays
Returns
-------
ret
observation array
"""
self.angles, self.angle_vels, self.goal_xy = state
return self.get_observation()
def reset(self):
self.angles = ivy.random_uniform(
low=-np.pi, high=np.pi, shape=(self.num_joints,)
)
self.angle_vels = ivy.random_uniform(low=-1, high=1, shape=(self.num_joints,))
self.goal_xy = ivy.random_uniform(
low=-self.num_joints, high=self.num_joints, shape=(2,)
)
return self.get_observation()
def step(self, action):
"""
Parameters
----------
action
"""
angle_accs = self.torque_scale * action
self.angle_vels = self.angle_vels + self.dt * angle_accs
self.angles = self.angles + self.dt * self.angle_vels
return self.get_observation(), self.get_reward(), False, {}
def render(self, mode="human"):
"""Renders the environment.
The set of supported modes varies per environment. (And some
environments do not support rendering at all.) By convention,
if mode is:
- human: render to the current display or terminal and
return nothing. Usually for human consumption.
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel image, suitable
for turning into a video.
- ansi: Return a string (str) or StringIO.StringIO containing a
terminal-style text representation. The text can include newlines
and ANSI escape sequences (e.g. for colors).
Parameters
----------
mode
Render mode, one of [human|rgb_array], default human
Returns
-------
ret
Rendered image.
"""
if self.viewer is None:
# noinspection PyBroadException
try:
from gym.envs.classic_control import rendering
except Exception:
if not self._logged_headless_message:
print(
"Unable to connect to display. Running the Ivy environment "
"in headless mode..."
)
self._logged_headless_message = True
return
self.viewer = rendering.Viewer(500, 500)
bound = self.num_joints + 0.2
self.viewer.set_bounds(-bound, bound, -bound, bound)
# Goal.
goal_geom = rendering.make_circle(0.2)
goal_geom.set_color(0.4, 0.6, 1.0)
self.goal_tr = rendering.Transform()
goal_geom.add_attr(self.goal_tr)
self.viewer.add_geom(goal_geom)
# Arm segments and joints.
l, r, t, b = 0, 1.0, 0.1, -0.1
self.segment_trs = []
for _ in range(self.num_joints):
# Segment.
segment_geom = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
segment_tr = rendering.Transform()
self.segment_trs.append(segment_tr)
segment_geom.add_attr(segment_tr)
segment_geom.set_color(0.0, 0.0, 0.0)
self.viewer.add_geom(segment_geom)
# Joint.
joint_geom = rendering.make_circle(0.1)
joint_geom.set_color(0.5, 0.5, 0.5)
joint_geom.add_attr(segment_tr)
self.viewer.add_geom(joint_geom)
# End effector.
self.end_geom = rendering.make_circle(0.1)
self.end_tr = rendering.Transform()
self.end_geom.add_attr(self.end_tr)
self.viewer.add_geom(self.end_geom)
self.goal_tr.set_translation(*ivy.to_numpy(self.goal_xy).tolist())
x, y = 0.0, 0.0
for segment_tr, angle in zip(
self.segment_trs, ivy.reshape(self.angles, (-1, 1))
):
segment_tr.set_rotation(ivy.to_numpy(angle)[0])
segment_tr.set_translation(x, y)
x = ivy.to_numpy(x + ivy.cos(ivy.expand_dims(angle, axis=0))[0])[0]
y = ivy.to_numpy(y + ivy.sin(ivy.expand_dims(angle, axis=0))[0])[0]
self.end_tr.set_translation(x, y)
rew = ivy.to_numpy(self.get_reward())[0]
self.end_geom.set_color(1 - rew, rew, 0.0)
return self.viewer.render(return_rgb_array=mode == "rgb_array")
def close(self):
"""Close environment."""
if self.viewer:
self.viewer.close()
self.viewer = None