Repository navigation
Expand file tree
/
Copy pathcontrolBarrierFunction.py
More file actions
284 lines (216 loc) · 11.5 KB
/
Copy pathcontrolBarrierFunction.py
File metadata and controls
284 lines (216 loc) · 11.5 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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env python3
from matplotlib.animation import FuncAnimation
from shapely.geometry import LineString
import matplotlib.pyplot as plt
import numpy as np
import random
def main():
approach = 'general'#, 'grid'
sim = Simulation(approach)
for t in range(sim.steps):
sim.run(t)
sim.plot()
# Force encoding : linear, no fp, and also compare horiwontal traje to ignore the deconfliction.
class Simulation:
def __init__(self, approach, tsim=20, dt=0.05, n_vehicles=10):
self.approach = approach
self.dt = dt # Time step (s)
self.tsim = tsim
self.steps = int(self.tsim/self.dt) # Wall simulation time (s)
self.n_vehicles = n_vehicles
self.epsilon = 1e-6
self.colors = ['b','g','r','c','m','y', 'b','g','r','c','m','y', 'b','g','r','c','m','y', 'b','g','r','c','m','y', 'b','g','r','c','m','y', 'b','g','r','c','m','y', 'b','g','r','c','m','y']
self.airspace = Airspace(self.n_vehicles, self.approach)
self.solver = ControlBarrier()
self.traffic = Traffic(self.steps, n_vehicles)
self.idx = 0
def run(self, t):
self.traffic.update(self.airspace.flight_plans, t)
self.v_new = np.zeros(self.n_vehicles)
#self.grid_approach(t)
if self.approach == 'grid':
self.step_grid(t)
else:
self.step(t)
self.traffic.priority += 1 - self.v_new
self.traffic.pos += self.v_new * self.dt
self.traffic.v_prev = self.v_new
def step(self, t):
for ownship_idx in range(self.n_vehicles):
pi = self.traffic.pos_hist[ownship_idx, t]
LB, UB = -np.inf, np.inf
for intruder_idx in range(self.n_vehicles):
if ownship_idx == intruder_idx or (self.traffic.passing_deadlock(ownship_idx, intruder_idx) and self.traffic.get_priority(ownship_idx, intruder_idx)):
continue
pj = self.traffic.pos_hist[intruder_idx, t]
diff = pi - pj
h_val = diff.dot(diff) - self.solver.lowc**2
grad_h = 2 * diff
dir_own = self.airspace.flight_plans['paths'][ownship_idx](self.traffic.pos[ownship_idx] + self.epsilon) - pi
dir_int = self.airspace.flight_plans['paths'][intruder_idx](self.traffic.pos[intruder_idx] + self.epsilon) - pj
# Normalize directions to avoid influence from path scale
dir_own /= np.linalg.norm(dir_own) + self.epsilon
dir_int /= np.linalg.norm(dir_int) + self.epsilon
Lf_h = -grad_h.dot(dir_int) * self.traffic.v_prev[intruder_idx]
a = grad_h.dot(dir_own)
b = -(Lf_h + self.solver.alpha * h_val)
if abs(a) < self.epsilon:
continue
if a > 0:
LB = max(LB, b / a)
else:
UB = min(UB, b / a)
v_i = max(self.traffic.spd_floor, np.clip(self.traffic.ini_spd[ownship_idx], LB, UB))
self.v_new[ownship_idx] = v_i
def step_grid(self, t):
for ownship_idx in range(self.n_vehicles):
LB, UB = -np.inf, np.inf
pi = self.traffic.pos_hist[ownship_idx, t]
for intruder_idx in range(self.n_vehicles):
if ownship_idx == intruder_idx:
continue
horizontal_own = (ownship_idx < int(self.n_vehicles/2))
horizontal_int = (intruder_idx < int(self.n_vehicles/2))
if horizontal_own == horizontal_int:
continue
if horizontal_own:
y_own = self.airspace.flight_plans['latitude'][ownship_idx]
x_int = self.airspace.flight_plans['longitude'][intruder_idx-int(self.n_vehicles/2)]
s_i_int = x_int + self.airspace.flight_plans['path length']/2
s_j_int = y_own + self.airspace.flight_plans['path length']/2
else:
x_own = self.airspace.flight_plans['longitude'][ownship_idx-int(self.n_vehicles/2)]; y_int = self.airspace.flight_plans['latitude'][intruder_idx]
s_i_int = y_int + self.airspace.flight_plans['path length']/2
s_j_int = x_own + self.airspace.flight_plans['path length']/2
t_i = (s_i_int - self.traffic.pos[ownship_idx]) / self.traffic.v_prev[ownship_idx] if self.traffic.v_prev[ownship_idx] > self.epsilon else np.inf
t_j = (s_j_int - self.traffic.pos[intruder_idx]) / self.traffic.v_prev[intruder_idx] if self.traffic.v_prev[intruder_idx] > self.epsilon else np.inf
if (t_i > t_j) or (abs(t_i - t_j) < self.epsilon and ownship_idx > intruder_idx):
pj = self.traffic.pos_hist[intruder_idx, t]
diff = pi - pj
h_val = diff.dot(diff) - self.solver.los**2
grad_h = 2 * diff
dir_own = np.array([1.0, 0.0]) if horizontal_own else np.array([0.0, 1.0])
dir_int = np.array([1.0, 0.0]) if horizontal_int else np.array([0.0, 1.0])
Lf_h = -grad_h.dot(dir_int) * self.traffic.v_prev[intruder_idx]
a = grad_h.dot(dir_own)
b = -(Lf_h + self.solver.alpha * h_val)
if abs(a) < self.epsilon:
continue
if a > 0:
LB = max(LB, b / a)
else:
UB = min(UB, b / a)
v_i = np.clip(self.traffic.ini_spd[ownship_idx], LB, UB)
self.v_new[ownship_idx] = max(0.0, v_i)
def plot(self):
fig, ax = plt.subplots(figsize=(6,6))
if self.approach == 'grid':
ax.set_xlim(-self.airspace.flight_plans['path length']/2 - 4, self.airspace.flight_plans['path length']/2 + 4)
ax.set_ylim(-self.airspace.flight_plans['path length']/2 - 4, self.airspace.flight_plans['path length']/2 + 4)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("CBF Conflict Resolution")
t_line = np.linspace(-self.airspace.flight_plans['path length']/2, self.airspace.flight_plans['path length']/2, 200)
for y in self.airspace.flight_plans['latitude']:
ax.plot(t_line, y*np.ones_like(t_line), 'k--', alpha=0.5)
for x in self.airspace.flight_plans['longitude']:
ax.plot(x*np.ones_like(t_line), t_line, 'k--', alpha=0.5)
dots = []
for i in range(self.n_vehicles):
dot, = ax.plot([], [], f'{self.colors[i]}o', label=f'Vehicle {i+1}')
dots.append(dot)
ax.legend(loc='upper right')
def update(frame):
for i, dot in enumerate(dots):
dot.set_data([self.traffic.pos_hist[i, frame, 0]], [self.traffic.pos_hist[i, frame, 1]])
return dots
ani = FuncAnimation(fig, update, frames=self.steps, interval=50, blit=True)
plt.show(block=False)
plt.pause(self.tsim + 1)
plt.close(fig)
else:
ax.set_xlim(self.airspace.xmin, self.airspace.xmax)
ax.set_ylim(self.airspace.ymin, self.airspace.ymax)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("CBF Conflict Resolution")
for i in range(self.n_vehicles):
path_fn = self.airspace.flight_plans['paths'][i]
s_vals = np.linspace(0, self.traffic.ini_spd[i] * self.tsim, 100)
traj = np.array([path_fn(s) for s in s_vals])
ax.plot(traj[:, 0], traj[:, 1], 'k--', alpha=0.3)
dots = []
for i in range(self.n_vehicles):
dot, = ax.plot([], [], f'{self.colors[i]}o', label=f'Vehicle {i + 1}')
dots.append(dot)
ax.legend(loc='upper right')
def update(frame):
for i, dot in enumerate(dots):
dot.set_data([self.traffic.pos_hist[i, frame, 0]], [self.traffic.pos_hist[i, frame, 1]])
return dots
ani = FuncAnimation(fig, update, frames=self.steps, interval=50, blit=True)
plt.show(block=False)
plt.pause(self.tsim + 1)
plt.close(fig)
class ControlBarrier:
def __init__(self, lowc= 1.0, nmac= 0.5, alpha= 1.0):
self.lowc = lowc
self.nmac = nmac
self.alpha = alpha # CBF gain
class Traffic:
def __init__(self, steps, n_vehicles):
self.steps = steps
self.n_vehicles = n_vehicles
self.priority = np.zeros(self.n_vehicles)
self.ini_spd = np.random.uniform(1, 5, size=(self.n_vehicles))
self.pos = np.zeros(self.n_vehicles) # path parameters
self.v_prev = self.ini_spd
self.spd_floor = 0.05
self.pos_hist = np.zeros((self.n_vehicles, self.steps, 2)) # record positions
def update(self, flight_plans, time):
for ac in range(self.n_vehicles):
self.pos_hist[ac, time] = flight_plans['paths'][ac](self.pos[ac])
def passing_deadlock(self, ownship_idx, intruder_idx):
return self.v_prev[ownship_idx] == self.spd_floor and self.v_prev[intruder_idx] == self.spd_floor
def get_priority(self, ownship_idx, intruder_idx):
return self.priority[ownship_idx] >= self.priority[intruder_idx]
class Airspace:
def __init__(self, n_vehicles, approach, corridor_sep = 3.0, box=15):
self.n_vehicles = n_vehicles
self.corridor_sep = corridor_sep
self.box = box
self.path_length = corridor_sep * (int(self.n_vehicles/2)+1)
if approach == 'grid':
self.generate_grid_flight_plans
else:
self.generate_random_flight_plans
@property
def generate_random_flight_plans(self):
origins = np.random.uniform(0, self.box, size=(self.n_vehicles, 2))
heading = np.random.uniform(0, 2*np.pi, size=(self.n_vehicles, 1))
distances = np.random.uniform(8, 12, size=(self.n_vehicles,1))
directions = np.concatenate((np.cos(heading), np.sin(heading)), axis=1)
destinations = origins + directions * distances
def make_path_fn(origin, direction):
return lambda s: origin + s * direction
paths = [make_path_fn(o, d) for o, d in zip(origins, directions)]
all_points = np.vstack([origins, destinations])
self.xmin, self.ymin = np.min(all_points, axis=0) - 0.2
self.xmax, self.ymax = np.max(all_points, axis=0) + 0.2
self.flight_plans = {'origins': origins,
'destinations': destinations,
'heading': heading,
'distance': distances,
'paths': paths}
@property
def generate_grid_flight_plans(self):
coordinates = np.array([idx*self.corridor_sep for idx in range(int(self.n_vehicles/2))])
self.flight_plans = {'latitude': coordinates - coordinates[-1]/2,
'longitude': coordinates - coordinates[-1]/2,
'path length': self.path_length}
self.flight_plans.update({'paths': self.generate_paths})
@property
def generate_paths(self):
return [lambda s, y=y: np.array([s - self.flight_plans['path length']/2, y]) for y in self.flight_plans['latitude']] + [lambda s, x=x: np.array([x, s - self.flight_plans['path length']/2]) for x in self.flight_plans['longitude']]
if __name__ == "__main__":
main()