-
Notifications
You must be signed in to change notification settings - Fork 0
/
norm_flocking.py
246 lines (212 loc) · 8.67 KB
/
norm_flocking.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
# Copyright (c) 2022-2023.
# ProrokLab (https://www.proroklab.org/)
# All rights reserved.
from typing import Callable, Dict
import torch
from torch import Tensor
from vmas import render_interactively
from vmas.simulator.core import Agent, Landmark, Sphere, World, Entity
from vmas.simulator.heuristic_policy import BaseHeuristicPolicy
from vmas.simulator.scenario import BaseScenario
from vmas.simulator.sensors import Lidar
from vmas.simulator.utils import Color, X, Y, ScenarioUtils
class Scenario(BaseScenario):
def make_world(self, batch_dim: int, device: torch.device, **kwargs):
n_agents = kwargs.get("n_agents", 4)
n_obstacles = kwargs.get("n_obstacles", 5)
self._min_dist_between_entities = kwargs.get("min_dist_between_entities", 0.15)
self.collision_reward = kwargs.get("collision_reward", -0.1)
self.dist_shaping_factor = kwargs.get("dist_shaping_factor", 1)
self.plot_grid = True
self.desired_distance = 0.1
self.min_collision_distance = 0.005
self.x_dim = 1
self.y_dim = 1
# Make world
world = World(batch_dim, device, collision_force=400, substeps=5)
# Add agents
self._target = Agent(
name="target",
collide=True,
color=Color.GREEN,
render_action=True,
action_script=self.action_script_creator(),
)
world.add_agent(self._target)
goal_entity_filter: Callable[[Entity], bool] = lambda e: not isinstance(
e, Agent
)
for i in range(n_agents):
agent = Agent(
name=f"agent_{i}",
collide=True,
sensors=[
Lidar(
world,
n_rays=12,
max_range=0.35,
entity_filter=goal_entity_filter,
)
],
render_action=True,
)
agent.collision_rew = torch.zeros(batch_dim, device=device)
agent.dist_rew = agent.collision_rew.clone()
world.add_agent(agent)
# Add landmarks
self.obstacles = []
for i in range(n_obstacles):
obstacle = Landmark(
name=f"obstacle_{i}",
collide=True,
movable=False,
shape=Sphere(radius=0.1),
color=Color.RED,
)
world.add_landmark(obstacle)
self.obstacles.append(obstacle)
return world
def action_script_creator(self):
def action_script(agent, world):
t = self.t / 30
agent.action.u = torch.stack([torch.cos(t), torch.sin(t)], dim=1)
return action_script
def reset_world_at(self, env_index: int = None):
target_pos = torch.zeros(
(1, self.world.dim_p)
if env_index is not None
else (self.world.batch_dim, self.world.dim_p),
device=self.world.device,
dtype=torch.float32,
)
target_pos[:, Y] = -self.y_dim
self._target.set_pos(target_pos, batch_index=env_index)
ScenarioUtils.spawn_entities_randomly(
self.obstacles + self.world.policy_agents,
self.world,
env_index,
self._min_dist_between_entities,
x_bounds=(-self.x_dim, self.x_dim),
y_bounds=(-self.y_dim, self.y_dim),
)
for agent in self.world.policy_agents:
if env_index is None:
agent.distance_shaping = (
torch.stack(
[
torch.linalg.vector_norm(
agent.state.pos - a.state.pos, dim=-1
)
for a in self.world.agents
if a != agent
],
dim=1,
)
- self.desired_distance
).pow(2).mean(-1) * self.dist_shaping_factor
else:
agent.distance_shaping[env_index] = (
torch.stack(
[
torch.linalg.vector_norm(
agent.state.pos[env_index] - a.state.pos[env_index]
)
for a in self.world.agents
if a != agent
],
dim=0,
)
- self.desired_distance
).pow(2).mean(-1) * self.dist_shaping_factor
if env_index is None:
self.t = torch.zeros(self.world.batch_dim, device=self.world.device)
else:
self.t[env_index] = 0
def reward(self, agent: Agent):
is_first = self.world.policy_agents.index(agent) == 0
if is_first:
self.t += 1
# Avoid collisions with each other
if self.collision_reward != 0:
for a in self.world.policy_agents:
a.collision_rew[:] = 0
for i, a in enumerate(self.world.agents):
for j, b in enumerate(self.world.agents):
if j <= i:
continue
collision = (
self.world.get_distance(a, b) <= self.min_collision_distance
)
if a.action_script is None:
a.collision_rew[collision] += self.collision_reward
if b.action_script is None:
b.collision_rew[collision] += self.collision_reward
# stay close together (separation)
agents_dist_shaping = (
torch.stack(
[
torch.linalg.vector_norm(agent.state.pos - a.state.pos, dim=-1)
for a in self.world.agents
if a != agent
],
dim=1,
)
- self.desired_distance
).pow(2).mean(-1) * self.dist_shaping_factor
agent.dist_rew = agent.distance_shaping - agents_dist_shaping
agent.distance_shaping = agents_dist_shaping
return agent.collision_rew + agent.dist_rew
def observation(self, agent: Agent):
return torch.cat(
[
agent.state.pos,
agent.state.vel,
agent.state.pos - self._target.state.pos,
agent.sensors[0].measure(),
],
dim=-1,
)
def info(self, agent: Agent) -> Dict[str, Tensor]:
info = {
"agent_collision_rew": agent.collision_rew,
"agent_distance_rew": agent.dist_rew,
}
return info
class HeuristicPolicy(BaseHeuristicPolicy):
def compute_action(self, observation: torch.Tensor, u_range: float) -> torch.Tensor:
assert self.continuous_actions
# First calculate the closest point to a circle of radius circle_radius given the current position
circle_origin = torch.zeros(1, 2)
circle_radius = 0.3
current_pos = observation[:, :2]
v = current_pos - circle_origin
closest_point_on_circ = (
circle_origin + v / torch.linalg.norm(v, dim=1).unsqueeze(1) * circle_radius
)
# calculate the normal vector of the vector from the origin of the circle to that closest point
# on the circle. Adding this scaled normal vector to the other vector gives us a target point we
# try to reach, thus resulting in a circular motion.
closest_point_on_circ_normal = torch.stack(
[closest_point_on_circ[:, Y], -closest_point_on_circ[:, X]], dim=1
)
closest_point_on_circ_normal /= torch.linalg.norm(
closest_point_on_circ_normal, dim=1
).unsqueeze(1)
closest_point_on_circ_normal *= 0.1
des_pos = closest_point_on_circ + closest_point_on_circ_normal
# Move away from other agents and obstcles within visibility range
lidar = observation[:, 6:18]
object_visible = torch.any(lidar < 0.1, dim=1)
_, object_dir_index = torch.min(lidar, dim=1)
object_dir = object_dir_index / lidar.shape[1] * 2 * torch.pi
object_vec = torch.stack([torch.cos(object_dir), torch.sin(object_dir)], dim=1)
des_pos_object = current_pos - object_vec * 0.1
des_pos[object_visible] = des_pos_object[object_visible]
action = torch.clamp(
(des_pos - current_pos) * 10,
min=-u_range,
max=u_range,
)
return action
if __name__ == "__main__":
render_interactively(__file__, control_two_agents=True)