This repository has been archived by the owner on Mar 17, 2019. It is now read-only.
forked from openai/gym
-
Notifications
You must be signed in to change notification settings - Fork 278
/
gazebo_circuit2c_turtlebot_camera_nn.py
248 lines (202 loc) · 8.64 KB
/
gazebo_circuit2c_turtlebot_camera_nn.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import gym
import rospy
import roslaunch
import time
import numpy as np
import cv2
import sys
import os
import random
from gym import utils, spaces
from gym_gazebo.envs import gazebo_env
from geometry_msgs.msg import Twist
from std_srvs.srv import Empty
from sensor_msgs.msg import Image
from sensor_msgs.msg import LaserScan
from gym.utils import seeding
from cv_bridge import CvBridge, CvBridgeError
import skimage as skimage
from skimage import transform, color, exposure
from skimage.transform import rotate
from skimage.viewer import ImageViewer
class GazeboCircuit2cTurtlebotCameraNnEnv(gazebo_env.GazeboEnv):
def __init__(self):
# Launch the simulation with the given launchfile name
gazebo_env.GazeboEnv.__init__(self, "GazeboCircuit2cTurtlebotLidar_v0.launch")
self.vel_pub = rospy.Publisher('/mobile_base/commands/velocity', Twist, queue_size=5)
self.unpause = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)
self.pause = rospy.ServiceProxy('/gazebo/pause_physics', Empty)
self.reset_proxy = rospy.ServiceProxy('/gazebo/reset_simulation', Empty)
self.reward_range = (-np.inf, np.inf)
self._seed()
self.last50actions = [0] * 50
self.img_rows = 32
self.img_cols = 32
self.img_channels = 1
def calculate_observation(self,data):
min_range = 0.21
done = False
for i, item in enumerate(data.ranges):
if (min_range > data.ranges[i] > 0):
done = True
return done
def _seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def step(self, action):
rospy.wait_for_service('/gazebo/unpause_physics')
try:
self.unpause()
except (rospy.ServiceException) as e:
print ("/gazebo/unpause_physics service call failed")
'''# 21 actions
max_ang_speed = 0.3
ang_vel = (action-10)*max_ang_speed*0.1 #from (-0.33 to + 0.33)
vel_cmd = Twist()
vel_cmd.linear.x = 0.2
vel_cmd.angular.z = ang_vel
self.vel_pub.publish(vel_cmd)'''
# 3 actions
if action == 0: #FORWARD
vel_cmd = Twist()
vel_cmd.linear.x = 0.2
vel_cmd.angular.z = 0.0
self.vel_pub.publish(vel_cmd)
elif action == 1: #LEFT
vel_cmd = Twist()
vel_cmd.linear.x = 0.05
vel_cmd.angular.z = 0.2
self.vel_pub.publish(vel_cmd)
elif action == 2: #RIGHT
vel_cmd = Twist()
vel_cmd.linear.x = 0.05
vel_cmd.angular.z = -0.2
self.vel_pub.publish(vel_cmd)
data = None
while data is None:
try:
data = rospy.wait_for_message('/scan', LaserScan, timeout=5)
except:
pass
done = self.calculate_observation(data)
image_data = None
success=False
cv_image = None
while image_data is None or success is False:
try:
image_data = rospy.wait_for_message('/camera/rgb/image_raw', Image, timeout=5)
h = image_data.height
w = image_data.width
cv_image = CvBridge().imgmsg_to_cv2(image_data, "bgr8")
#temporal fix, check image is not corrupted
if not (cv_image[h//2,w//2,0]==178 and cv_image[h//2,w//2,1]==178 and cv_image[h//2,w//2,2]==178):
success = True
else:
pass
#print("/camera/rgb/image_raw ERROR, retrying")
except:
pass
rospy.wait_for_service('/gazebo/pause_physics')
try:
#resp_pause = pause.call()
self.pause()
except (rospy.ServiceException) as e:
print ("/gazebo/pause_physics service call failed")
self.last50actions.pop(0) #remove oldest
if action == 0:
self.last50actions.append(0)
else:
self.last50actions.append(1)
action_sum = sum(self.last50actions)
'''# 21 actions
if not done:
# Straight reward = 5, Max angle reward = 0.5
reward = round(15*(max_ang_speed - abs(ang_vel) +0.0335), 2)
# print ("Action : "+str(action)+" Ang_vel : "+str(ang_vel)+" reward="+str(reward))
if action_sum > 45: #L or R looping
#print("90 percent of the last 50 actions were turns. LOOPING")
reward = -5
else:
reward = -200'''
# Add center of the track reward
# len(data.ranges) = 100
laser_len = len(data.ranges)
left_sum = sum(data.ranges[laser_len-(laser_len/5):laser_len-(laser_len/10)]) #80-90
right_sum = sum(data.ranges[(laser_len/10):(laser_len/5)]) #10-20
center_detour = abs(right_sum - left_sum)/5
# 3 actions
if not done:
if action == 0:
reward = 1 / float(center_detour+1)
elif action_sum > 45: #L or R looping
reward = -0.5
else: #L or R no looping
reward = 0.5 / float(center_detour+1)
else:
reward = -1
#print("detour= "+str(center_detour)+" :: reward= "+str(reward)+" ::action="+str(action))
'''x_t = skimage.color.rgb2gray(cv_image)
x_t = skimage.transform.resize(x_t,(32,32))
x_t = skimage.exposure.rescale_intensity(x_t,out_range=(0,255))'''
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
cv_image = cv2.resize(cv_image, (self.img_rows, self.img_cols))
#cv_image = cv_image[(self.img_rows/20):self.img_rows-(self.img_rows/20),(self.img_cols/10):self.img_cols] #crop image
#cv_image = skimage.exposure.rescale_intensity(cv_image,out_range=(0,255))
state = cv_image.reshape(1, 1, cv_image.shape[0], cv_image.shape[1])
return state, reward, done, {}
# test STACK 4
#cv_image = cv_image.reshape(1, 1, cv_image.shape[0], cv_image.shape[1])
#self.s_t = np.append(cv_image, self.s_t[:, :3, :, :], axis=1)
#return self.s_t, reward, done, {} # observation, reward, done, info
def reset(self):
self.last50actions = [0] * 50 #used for looping avoidance
# Resets the state of the environment and returns an initial observation.
rospy.wait_for_service('/gazebo/reset_simulation')
try:
#reset_proxy.call()
self.reset_proxy()
except (rospy.ServiceException) as e:
print ("/gazebo/reset_simulation service call failed")
# Unpause simulation to make observation
rospy.wait_for_service('/gazebo/unpause_physics')
try:
#resp_pause = pause.call()
self.unpause()
except (rospy.ServiceException) as e:
print ("/gazebo/unpause_physics service call failed")
image_data = None
success=False
cv_image = None
while image_data is None or success is False:
try:
image_data = rospy.wait_for_message('/camera/rgb/image_raw', Image, timeout=5)
h = image_data.height
w = image_data.width
cv_image = CvBridge().imgmsg_to_cv2(image_data, "bgr8")
#temporal fix, check image is not corrupted
if not (cv_image[h//2,w//2,0]==178 and cv_image[h//2,w//2,1]==178 and cv_image[h//2,w//2,2]==178):
success = True
else:
pass
#print("/camera/rgb/image_raw ERROR, retrying")
except:
pass
rospy.wait_for_service('/gazebo/pause_physics')
try:
#resp_pause = pause.call()
self.pause()
except (rospy.ServiceException) as e:
print ("/gazebo/pause_physics service call failed")
'''x_t = skimage.color.rgb2gray(cv_image)
x_t = skimage.transform.resize(x_t,(32,32))
x_t = skimage.exposure.rescale_intensity(x_t,out_range=(0,255))'''
cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
cv_image = cv2.resize(cv_image, (self.img_rows, self.img_cols))
#cv_image = cv_image[(self.img_rows/20):self.img_rows-(self.img_rows/20),(self.img_cols/10):self.img_cols] #crop image
#cv_image = skimage.exposure.rescale_intensity(cv_image,out_range=(0,255))
state = cv_image.reshape(1, 1, cv_image.shape[0], cv_image.shape[1])
return state
# test STACK 4
#self.s_t = np.stack((cv_image, cv_image, cv_image, cv_image), axis=0)
#self.s_t = self.s_t.reshape(1, self.s_t.shape[0], self.s_t.shape[1], self.s_t.shape[2])
#return self.s_t