Repository navigation
Expand file tree
/
Copy pathdouble_lane_change.py
More file actions
329 lines (252 loc) · 10.9 KB
/
Copy pathdouble_lane_change.py
File metadata and controls
329 lines (252 loc) · 10.9 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import numpy as np
import logging
from datetime import datetime
class SharedControl_DLC:
def __init__(self, log=False):
self.L = 2.6 # Wheelbase (m)
self.Lf = 0.9 # Distance from CoG to front axle (m)
self.Lr = 1.7 # Distance from CoG to rear axle (m)
self.m = 1600 # Vehicle mass (kg)
self.v_init = 15 # ehicle velocity (m/s)
self.QA_max = np.diag([0, 5, 10, 0]) # max ADAS state weights [x, y, theta, v]
self.QD_max = np.diag([0, 10, 10, 0]) # max driver state weights [x, y, theta, v]
self.RA = np.diag([1.0, 0.1]) # ADAS control weights [delta, accel]
self.RD = np.diag([2.0, 0.1]) # Driver control weights [delta, accel]
self.T = 0.5 # Preview horizon (s)
self.dt = 0.01 # Time step (s)
self.log = log
if log: self.setup_logger()
def kinematic_model(self, x, delta, accel):
x_dot = np.zeros(4)
theta = x[2]
v = x[3]
x_dot[0] = v * np.cos(theta) # x_dot
x_dot[1] = v * np.sin(theta) # y_dot
x_dot[2] = v * np.tan(delta) / self.L # theta_dot
x_dot[3] = accel # v_dot
return x_dot
def discretize_model(self, x, delta, accel):
k1 = self.kinematic_model(x, delta, accel)
k2 = self.kinematic_model(x + self.dt/2 * k1, delta, accel)
k3 = self.kinematic_model(x + self.dt/2 * k2, delta, accel)
k4 = self.kinematic_model(x + self.dt * k3, delta, accel)
x_next = x + self.dt/6 * (k1 + 2*k2 + 2*k3 + k4)
return x_next
def jacobian_state(self, x, delta):
theta = x[2]
v = x[3]
A = np.zeros((4, 4))
A[0, 2] = -v * np.sin(theta)
A[0, 3] = np.cos(theta)
A[1, 2] = v * np.cos(theta)
A[1, 3] = np.sin(theta)
A[2, 3] = np.tan(delta) / self.L
A[0, 0] = 1
A[1, 1] = 1
A[2, 2] = 1
A[3, 3] = 1
return A
def jacobian_input(self, x, delta):
v = x[3]
B = np.zeros((4, 2))
B[2, 0] = v / (self.L * np.cos(delta)**2)
B[3, 1] = 1
return B
def solve_riccati(self, A, BD, BA, QD, QA, RD, RA):
n = A.shape[0]
PD = np.zeros((n, n))
PA = np.zeros((n, n))
SD = BD @ np.linalg.inv(RD) @ BD.T
SA = BA @ np.linalg.inv(RA) @ BA.T
steps = int(self.T/self.dt)
for _ in range(steps):
PD_dot = (A - SA @ PA).T @ PD + PD @ (A - SA @ PA) - PD @ SD @ PD + QD
PD += PD_dot * self.dt
PA_dot = (A - SD @ PD).T @ PA + PA @ (A - SD @ PD) - PA @ SA @ PA + QA
PA += PA_dot * self.dt
return PD, PA
def compute_control(self, x, t, alpha_D, alpha_A, path_ref):
x_ref, y_ref, theta_ref, v_ref = self.get_reference_at_position(x, path_ref)
# Create reference state vector
state_ref = np.array([x_ref, y_ref, theta_ref, v_ref])
# State error
x_tilde = x - state_ref
# Current steering
current_delta = 0
# Linearization of the model around current state
A = self.jacobian_state(x, current_delta)
B = self.jacobian_input(x, current_delta)
# Scale input matrices for driver and ADAS
BD = B
BA = B
# Scale weight matrices by authority levels
# QD = alpha_D * self.QD_max
# QA = alpha_A * self.QA_max
QD = self.QD_max
QA = self.QA_max
RD = self.RD
RA = self.RA
# Solve Riccati equations
PD, PA = self.solve_riccati(A, BD, BA, QD, QA, RD, RA)
# Compute control inputs
uD = -np.linalg.inv(RD) @ BD.T @ PD @ x_tilde
uA = -np.linalg.inv(RA) @ BA.T @ PA @ x_tilde
# shared control
uD = alpha_D * uD
uA = alpha_A * uA
return uD, uA
def get_reference_at_position(self, x, path_ref):
current_x, current_y = x[0], x[1]
x_path = path_ref[:, 0]
y_path = path_ref[:, 1]
theta_path = path_ref[:, 2]
v_path = path_ref[:, 3]
# Find closest point on reference path
distances = np.sqrt((x_path - current_x)**2 + (y_path - current_y)**2)
idx = np.argmin(distances)
# Look ahead a few points for smoother control
look_ahead = 5 # Look ahead by 5 points
idx_ahead = min(idx + look_ahead, len(x_path) - 1)
return x_path[idx_ahead], y_path[idx_ahead], theta_path[idx_ahead], v_path[idx_ahead]
def smooth_step(self, x):
x = np.clip(x, 0, 1)
return x * x * (3 - 2 * x)
def generate_trajectory(self, sim_length):
"""
Generate a reference trajectory for a double lane change maneuver
"""
t = np.arange(0, sim_length, self.dt)
x_ref = self.v_init * t
r1 = 30
r2 = 21.95
d1 = 3.5
d2 = 3.5
y_ref = (d1/2) * (1 + np.tanh((3/r1)*(x_ref-70)-1.2)) - (d2/2) * (1 + np.tanh((3/r2)*(x_ref-125)-1.5))
theta_ref = np.arctan((1.2*d1)/(r1*np.cosh((3/r1)*(x_ref-70)-1.2))) - np.arctan((1.0*d2)/(r2*np.cosh((3/r2)*(x_ref-125)-1.5)))
v_ref = np.ones_like(x_ref) * self.v_init
path_ref = np.column_stack((x_ref, y_ref, theta_ref, v_ref))
return path_ref, y_ref, theta_ref
def transition_functions(self, t, ts, te, type='linear', x=None, path_ref=None):
if t < ts:
return 0.0, 1.0 # Full ADAS control
elif t > te:
return 1.0, 0.0 # Full driver control
if type == 'step':
alpha_A = 0.0
elif type == 'linear':
alpha_A = -(1/(te - ts)) * (t - ts) + 1
elif type == 'cooperative':
alpha_A = 0.5
elif type == 'sigmoid':
alpha_A = 1 - 1 / (1 + np.exp(-10 * (t - (ts + te) / 2) / (te - ts)))
elif type == 'exponential':
normalized_t = (t - ts) / (te - ts)
alpha_A = np.exp(-5 * normalized_t)
elif type == 'blend':
normalized_t = (t - ts) / (te - ts)
linear_A = 1 - normalized_t
sigmoid_A = 1 - 1 / (1 + np.exp(-10 * (normalized_t - 0.5)))
alpha_A = 0.5 * linear_A + 0.5 * sigmoid_A
elif type == 'lagged':
if t <= ts + 2:
alpha_A = 1.0
else:
alpha_A = 0.5
elif type == 'adaptive':
if x is None or path_ref is None:
alpha_A = 0.5
else:
x_ref, y_ref, theta_ref, v_ref = self.get_reference_at_position(x, path_ref)
lateral_error = abs(x[1] - y_ref)
heading_error = abs(x[2] - theta_ref)
max_lateral_error = 0.3
max_heading_error = 0.2
norm_lateral_error = min(lateral_error / max_lateral_error, 1.0)
norm_heading_error = min(heading_error / max_heading_error, 1.0)
total_error = 0.7 * norm_lateral_error + 0.3 * norm_heading_error
base_alpha_A = 0.5
error_factor = total_error * 0.14
alpha_A = min(max(base_alpha_A + error_factor, 0.0), 1.0)
else:
raise ValueError("Unknown transition type")
alpha_D = 1.0 - alpha_A
return alpha_D, alpha_A
def setup_logger(self):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
logging.basicConfig(
filename=f'logs/shared_control_log_{timestamp}.txt',
level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logging.getLogger().addHandler(console_handler)
def log_control_state(self, t, alpha_D, alpha_A, x):
phase = self.determine_control_phase(t)
log_msg = (
f"Time: {t:.2f}s | "
f"Phase: {phase} | "
f"Authority - Driver: {alpha_D:.2f}, AV: {alpha_A:.2f} | "
f"Position: ({x[0]:.2f}, {x[1]:.2f}) | "
f"Heading: {np.degrees(x[2]):.2f}° | "
f"Velocity: {x[3]:.2f} m/s"
)
logging.info(log_msg)
def determine_control_phase(self, t):
if t < 3.0:
return "AV Full Control"
elif t > 8.0:
return "Driver Full Control"
else:
return "Transition Phase"
def simulate_double_lane_change(self, transition_type='linear'):
# Simulation time
sim_length = 15.0
t_sim = np.arange(0, sim_length, self.dt)
ts = 3.0 # Start of transition
te = 10.0 # End of transition
path_ref, y_ref, psi_ref = self.generate_trajectory(sim_length)
x = np.array([0.0, 0.0, 0.0, self.v_init]) # [x, y, theta, v]
states = [x.copy()]
controls_D = []
controls_A = []
alphas_D = []
alphas_A = []
deltas = []
accels = []
for i, t in enumerate(t_sim[:-1]):
alpha_D, alpha_A = self.transition_functions(t, ts, te, transition_type, x, path_ref)
alphas_D.append(alpha_D)
alphas_A.append(alpha_A)
uD, uA = self.compute_control(x, t, alpha_D, alpha_A, path_ref)
controls_D.append(uD)
controls_A.append(uA)
delta = alpha_D * uD[0] + alpha_A * uA[0]
accel = alpha_D * uD[1] + alpha_A * uA[1]
deltas.append(delta)
accels.append(accel)
x = self.discretize_model(x, delta, accel)
states.append(x.copy())
if self.log:
self.log_control_state(t, alpha_D, alpha_A, x)
states = np.array(states)
controls_D = np.array(controls_D)
controls_A = np.array(controls_A)
deltas = np.array(deltas)
accels = np.array(accels)
return (states, controls_D, controls_A,
np.array(alphas_D), np.array(alphas_A),
t_sim, y_ref, psi_ref, deltas, accels)
def do_double_lane_change(self, transition_types):
results = {}
for trans_type in transition_types:
result = self.simulate_double_lane_change(trans_type)
results[trans_type] = result
print(f"Completed {trans_type} transition!")
print("-"*50)
return results
if __name__ == "__main__":
controller = SharedControl_DLC()
transition_types = ['step', 'linear', 'cooperative', 'sigmoid', 'blend', 'lagged', 'adaptive']
results = controller.do_double_lane_change(transition_types)