forked from justinhj/astar-algorithm-cpp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimulator.py
More file actions
176 lines (145 loc) · 7.54 KB
/
Copy pathSimulator.py
File metadata and controls
176 lines (145 loc) · 7.54 KB
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
#!/usr/bin/env python3
import os
import sys
sys.path.append(os.getcwd()+'/src')
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from random import randint
class Simulator(object):
resolution: int
map_width: int
map_height: int
value_non_obs: int
value_obs: int
size_obs_width: int
size_obs_height: int
def __init__(self,
map_width_meter: float,
map_height_meter: float,
resolution: int,
value_non_obs: int,
value_obs: int):
"""
Constructor
The cell is empty if value_non_obs, the cell is blocked if value_obs.
"""
# map resolution, how many cells per meter
self.resolution = resolution
# how many cells for width and height
map_width = map_width_meter * resolution
map_height = map_height_meter * resolution
# check if these are integers
assert (map_width.is_integer() == True)
assert (map_height.is_integer() == True)
self.map_width = int(map_width)
self.map_height = int(map_height)
self.value_non_obs = value_non_obs
self.value_obs = value_obs
# create an empty map
self.map_array = self.value_non_obs * np.ones((self.map_height, self.map_width)).astype(int)
def generate_random_obs(self, num_obs: int, size_obs: list):
self.size_obs_width = round(size_obs[0] * self.resolution)
self.size_obs_height = round(size_obs[1] * self.resolution)
if num_obs > 0:
for idx_obs in range(0, num_obs):
# [width, height]
obs_left_bottom_corner = [randint(1,self.map_width-self.size_obs_width-1), randint(1, self.map_height-self.size_obs_height-1)]
obs_mat = self.map_array[obs_left_bottom_corner[1]:obs_left_bottom_corner[1]+self.size_obs_height][:, obs_left_bottom_corner[0]:obs_left_bottom_corner[0]+self.size_obs_width]
self.map_array[obs_left_bottom_corner[1]:obs_left_bottom_corner[1]+self.size_obs_height][:, obs_left_bottom_corner[0]:obs_left_bottom_corner[0]+self.size_obs_width] \
= self.value_obs * np.ones(obs_mat.shape)
def generate_agents_and_targets(self, num_agents: int, num_targets: int):
"""
Randomly generate agents and targets which don't collide with obstacles.
"""
agents = list()
for _ in range(num_agents):
start = [randint(1, self.map_width-1), randint(1, self.map_height-1)]
while self.map_array[start[1]][start[0]] != self.value_non_obs:
start = [randint(1, self.map_width-1), randint(1, self.map_height-1)]
agents.extend(start)
targets = list()
for _ in range(num_targets):
goal = [randint(1, self.map_width-1), randint(1, self.map_height-1)]
while (self.map_array[goal[1]][goal[0]] != self.value_non_obs) or (self.check_target_collide_agents(goal, agents)):
goal = [randint(1, self.map_width-1), randint(1, self.map_height-1)]
targets.extend(goal)
return agents, targets
def check_target_collide_agents(self, target_position: list, agent_positions: list):
"""
Check if a target collides with all the agents.
Return True if a collision exists.
"""
collision_flag = False
for idx in range(0, len(agent_positions), 2):
collision_flag = collision_flag or (target_position[0] == agent_positions[idx]) and (target_position[1] == agent_positions[idx+1])
return collision_flag
def plot_single_path(self, *arguments):
"""
Simulator.visualize(path) # plot a path
Simulator.visualize(path_full, path_short) # plot two paths
path is a list for the trajectory. [x[0], y[0], x[1], y[1], ...]
"""
if len(arguments[0]) > 0:
fig_map, ax_map = plt.subplots(1, 1)
cmap = matplotlib.colors.ListedColormap(['white','black'])
ax_map.pcolormesh(self.map_array, cmap=cmap, edgecolors='none')
ax_map.scatter(arguments[0][0]+0.5, arguments[0][1]+0.5, label="start")
ax_map.scatter(arguments[0][-2]+0.5, arguments[0][-1]+0.5, label="goal")
ax_map.plot(list(map(lambda x:x+0.5, arguments[0][0::2])),
list(map(lambda x:x+0.5, arguments[0][1::2])), label="path")
if len(arguments) == 2:
ax_map.plot(list(map(lambda x:x+0.5, arguments[1][0::2])),
list(map(lambda x:x+0.5, arguments[1][1::2])), label="path")
ax_map.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
ax_map.set_xlabel("x")
ax_map.set_ylabel("y")
ax_map.set_aspect('equal')
ax_map.set_xlim([0, self.map_width])
ax_map.set_ylim([0, self.map_height])
plt.show(block=False)
else:
print("A Star didn't find a path!")
def plot_many_path(self, path_many: list, agent_position: list, targets_position: list):
"""
path_many is a list for the trajectory. [[x[0],y[0],x[1],y[1], ...], [x[0],y[0],x[1],y[1], ...], ...]
"""
fig_map, ax_map = plt.subplots(1, 1)
cmap = matplotlib.colors.ListedColormap(['white','black'])
ax_map.pcolormesh(self.map_array, cmap=cmap, edgecolors='none')
ax_map.scatter(agent_position[0]+0.5, agent_position[1]+0.5, label="start")
for idx_target in range(0, int(len(targets_position)/2)):
ax_map.scatter(targets_position[2*idx_target]+0.5, targets_position[2*idx_target+1]+0.5, label="goal")
for idx_path in range(0, len(path_many)):
ax_map.plot(list(map(lambda x:x+0.5, path_many[idx_path][0::2])),
list(map(lambda x:x+0.5, path_many[idx_path][1::2])))
ax_map.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
ax_map.set_xlabel("x")
ax_map.set_ylabel("y")
ax_map.set_aspect('equal')
ax_map.set_xlim([0, self.map_width])
ax_map.set_ylim([0, self.map_height])
plt.show(block=False)
def plot_multi_agent_path(self, path_many: list, agent_position: list, targets_position: list):
fig_map, ax_map = plt.subplots(1, 1)
cmap = matplotlib.colors.ListedColormap(['white','black'])
ax_map.pcolormesh(self.map_array, cmap=cmap, edgecolors='none')
ax_map.plot(self.map_width*self.map_height, self.map_width*self.map_height, 'ks', label="Obstacle")
ax_map.scatter(agent_position[0]+0.5, agent_position[1]+0.5, color = 'b',marker="*", label="start")
if len(agent_position) > 1:
for idx_agent in range(1, int(len(agent_position)/2)):
ax_map.scatter(agent_position[idx_agent*2]+0.5, agent_position[idx_agent*2+1]+0.5, color = 'b',marker="*")
ax_map.scatter(targets_position[0]+0.5, targets_position[1]+0.5, color = 'r',label="target")
if len(targets_position) > 1:
for idx_target in range(1, int(len(targets_position)/2)):
ax_map.scatter(targets_position[idx_target*2]+0.5, targets_position[idx_target*2+1]+0.5, color = 'r')
for idx_path in range(0, len(path_many)):
ax_map.plot(list(map(lambda x:x+0.5, path_many[idx_path][0::2])),
list(map(lambda x:x+0.5, path_many[idx_path][1::2])))
ax_map.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
ax_map.set_xlabel("x")
ax_map.set_ylabel("y")
ax_map.set_aspect('equal')
ax_map.set_xlim([0, self.map_width])
ax_map.set_ylim([0, self.map_height])
plt.show(block=False)