-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetaheuristic_intersection.py
More file actions
1787 lines (1456 loc) · 68.4 KB
/
Copy pathmetaheuristic_intersection.py
File metadata and controls
1787 lines (1456 loc) · 68.4 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import matplotlib.pyplot as plt
from typing import Tuple, Dict, List
from dataclasses import dataclass
# ============================================================================
# PROBLEM PARAMETERS (Based on Literature 2018-2025)
# ============================================================================
@dataclass
class ProblemParameters:
"""
Parameters for CAV intersection optimization
"""
# Number of vehicles
N: int = 4 # Total vehicles
N_EW: int = 1 # East to West
N_WE: int = 1 # West to East
N_NS: int = 1 # North to South
N_SN: int = 1 # South to North
# Time discretization - EXTENDED to remove artificial time constraint
dt: float = 0.5 # Time step (seconds) - [0.1-0.5 typical]
K: int = 100 # Maximum time steps (safety limit)
T_max: float = 50.0 # Maximum time horizon (seconds, safety limit)
# NOTE: T_max is now an upper bound for simulation, not a hard constraint.
# The objective function measures actual crossing time, which can be much less.
# Time minimization in objective naturally pushes for fast crossings (~10-20s).
# Extended horizon ensures solution space completeness without artificial limits.
# Acceleration limits (m/s²)
u_min: float = -4.0 # Max deceleration (AASHTO standard)
u_max: float = 3.0 # Max acceleration (typical vehicle)
# Velocity limits (m/s)
v_min: float = 1.0 # Min velocity in intersection (no stopping)
v_max: float = 20.0 # Max velocity
v_min_approach: float = 0.0 # Min velocity before intersection
# Intersection geometry (meters)
L: float = 150.0 # Control zone length (approach distance)
S: float = 12.0 # Merging/conflict zone size
delta: float = 5.0 # Minimum separation distance (point mass)
# Safety parameters
dt_safe: float = 2.0 # Minimum time separation (seconds)
M: float = 500.0 # Big-M constant for MILP formulation
# Objective function weights
alpha: float = 0.5 # Time weight (0 to 1)
# Note: Energy weight is (1 - alpha)
def __post_init__(self):
"""Validate parameters after initialization"""
# Check vehicle count consistency
if self.N_EW + self.N_WE + self.N_NS + self.N_SN != self.N:
raise ValueError(
f"N_EW ({self.N_EW}) + N_WE ({self.N_WE}) + N_NS ({self.N_NS}) + N_SN ({self.N_SN}) must equal N ({self.N})"
)
# Check time discretization consistency
if abs(self.dt * self.K - self.T_max) > 1e-6:
print(f"Warning: dt×K ({self.dt * self.K:.2f}s) ≠ T_max ({self.T_max}s)")
print(f" Using dt×K = {self.dt * self.K:.2f}s as effective time horizon")
# Check velocity limits are sensible
if self.v_min > self.v_max:
raise ValueError(
f"v_min ({self.v_min}) must be less than v_max ({self.v_max})"
)
if self.v_min_approach > self.v_min:
raise ValueError(
f"v_min_approach ({self.v_min_approach}) should not exceed v_min ({self.v_min})"
)
# Check acceleration limits
if self.u_min > self.u_max:
raise ValueError(
f"u_min ({self.u_min}) must be less than u_max ({self.u_max})"
)
# Check alpha weight is valid
if not (0 <= self.alpha <= 1):
raise ValueError(
f"alpha ({self.alpha}) must be between 0 and 1"
)
# Check geometric parameters
if self.S > self.L:
raise ValueError(
f"Merging zone size S ({self.S}) should not exceed control zone length L ({self.L})"
)
if self.delta <= 0:
raise ValueError(
f"Safety distance delta ({self.delta}) must be positive"
)
def get_conflict_matrix(self) -> np.ndarray:
"""
Conflict matrix for 4-direction intersection
Vehicle indices:
0: E→W, 1: W→E, 2: N→S, 3: S→N
Conflicts (perpendicular crossings):
- E→W (0) conflicts with N→S (2) and S→N (3)
- W→E (1) conflicts with N→S (2) and S→N (3)
- N→S (2) conflicts with E→W (0) and W→E (1)
- S→N (3) conflicts with E→W (0) and W→E (1)
"""
C = np.zeros((self.N, self.N), dtype=int)
# Horizontal vehicles (E→W, W→E) conflict with vertical (N→S, S→N)
horizontal_vehicles = list(range(self.N_EW + self.N_WE)) # [0, 1]
vertical_vehicles = list(range(self.N_EW + self.N_WE, self.N)) # [2, 3]
for h in horizontal_vehicles:
for v in vertical_vehicles:
C[h, v] = 1
C[v, h] = 1
return C
def get_vehicle_direction(self, vehicle_id: int) -> str:
"""
Get direction string for a vehicle
Returns: 'EW', 'WE', 'NS', or 'SN'
"""
if vehicle_id < self.N_EW:
return 'EW'
elif vehicle_id < self.N_EW + self.N_WE:
return 'WE'
elif vehicle_id < self.N_EW + self.N_WE + self.N_NS:
return 'NS'
else:
return 'SN'
def vehicles_in_same_lane(self, i: int, j: int) -> bool:
"""
Check if two vehicles are in the exact same lane (same direction)
Used for rear-end collision checking
"""
dir_i = self.get_vehicle_direction(i)
dir_j = self.get_vehicle_direction(j)
return dir_i == dir_j
# ============================================================================
# VEHICLE DYNAMICS SIMULATION
# ============================================================================
def simulate_vehicle_trajectory(u: np.ndarray, x0: float, v0: float,
dt: float, K: int) -> Tuple[np.ndarray, np.ndarray]:
"""
Simulate vehicle trajectory using discrete-time dynamics
Dynamics (Constraint 1):
x[k+1] = x[k] + v[k]·dt + 0.5·u[k]·dt²
v[k+1] = v[k] + u[k]·dt
Args:
u: Acceleration profile (K,) array
x0: Initial position (m)
v0: Initial velocity (m/s)
dt: Time step (s)
K: Number of time steps
Returns:
x: Position trajectory (K+1,) - positions at k=0,1,...,K
v: Velocity trajectory (K+1,) - velocities at k=0,1,...,K
"""
x = np.zeros(K + 1)
v = np.zeros(K + 1)
# Initial conditions (Constraint 2)
x[0] = x0
v[0] = v0
# Forward integration
for k in range(K):
v[k+1] = v[k] + u[k] * dt
x[k+1] = x[k] + v[k] * dt + 0.5 * u[k] * dt**2
return x, v
def simulate_until_completion(u_profile: np.ndarray,
x0: float,
v0: float,
dt: float,
L: float,
K_max: int = 200) -> Tuple[np.ndarray, np.ndarray, int]:
"""
Simulate vehicle trajectory until it exits control zone OR reaches K_max
Returns:
x: Position trajectory (variable length)
v: Velocity trajectory (variable length)
k_actual: Actual number of steps used
"""
x = [x0]
v = [v0]
for k in range(K_max):
# Get acceleration for this step (or 0 if beyond u_profile length)
u_k = u_profile[k] if k < len(u_profile) else 0.0
# Update velocity and position
v_next = v[-1] + u_k * dt
x_next = x[-1] + v[-1] * dt + 0.5 * u_k * dt**2
v.append(v_next)
x.append(x_next)
# Check if vehicle exited control zone
if x_next >= L:
return np.array(x), np.array(v), k + 1
# Reached K_max without exiting
return np.array(x), np.array(v), K_max
# ============================================================================
# OBJECTIVE FUNCTION
# ============================================================================
def objective_function(x_decision: np.ndarray,
x0: np.ndarray,
v0: np.ndarray,
t0: np.ndarray,
params: ProblemParameters) -> Tuple[float, float, float, Dict]:
"""
Compute objective function with ADAPTIVE time horizon
Each vehicle simulates until it exits (x >= L), not fixed K steps.
"""
N = params.N
dt = params.dt
alpha = params.alpha
L = params.L
# Extract acceleration profiles (use first K values, will be adaptively truncated)
K_nominal = params.K
u_profiles = x_decision[:N * K_nominal].reshape(N, K_nominal)
# Simulate each vehicle until completion
trajectories = []
completion_times = []
for i in range(N):
x_traj, v_traj, k_actual = simulate_until_completion(
u_profiles[i], x0[i], v0[i], dt, L, K_max=params.K
)
trajectories.append((x_traj, v_traj))
# Calculate completion time for this vehicle
t_completion = t0[i] + k_actual * dt
completion_times.append(t_completion)
# Check if all vehicles completed
all_completed = all(traj[0][-1] >= L for traj in trajectories)
if not all_completed:
# Penalize incomplete trajectories heavily
return 1e6, 1e6, 0.0, {
'all_completed': False,
'trajectories': trajectories,
'completion_times': completion_times
}
# Calculate time cost (sum of actual completion times)
f_time = sum(completion_times)
# Calculate energy cost (sum of squared accelerations up to actual completion)
f_energy = 0.0
for i in range(N):
x_traj, v_traj = trajectories[i]
k_actual = len(x_traj) - 1 # Actual steps used
# Only sum energy for steps actually used
u_actual = u_profiles[i, :k_actual]
f_energy += np.sum(u_actual ** 2) * dt
# Combined objective
f_total = alpha * f_time + (1 - alpha) * f_energy
info = {
'all_completed': True,
'trajectories': trajectories,
'completion_times': completion_times,
'f_time': f_time,
'f_energy': f_energy,
'f_total': f_total,
'travel_times': np.array(completion_times) - t0, # For compatibility
'energies': np.array([np.sum(u_profiles[i, :len(trajectories[i][0])-1]**2)*dt for i in range(N)]),
'actual_K_needed': max(len(traj[0])-1 for traj in trajectories),
'time_efficiency': max(len(traj[0])-1 for traj in trajectories) / K_nominal,
'avg_crossing_time': f_time / N,
'total_time': f_time,
'total_energy': f_energy
}
return f_total, f_time, f_energy, info
# ============================================================================
# CONSTRAINT CHECKERS
# ============================================================================
def check_constraint_1_dynamics(trajectories: List, u_profiles: np.ndarray,
x0: np.ndarray, v0: np.ndarray,
params: ProblemParameters) -> Dict:
"""
Constraint 1: Vehicle dynamics0
xᵢ[k+1] = xᵢ[k] + vᵢ[k]·Δt + 0.5·uᵢ[k]·Δt²
vᵢ[k+1] = vᵢ[k] + uᵢ[k]·Δt
This is enforced by construction in simulate_vehicle_trajectory()
"""
return {
'satisfied': True,
'type': 'dynamics',
'note': 'Enforced by trajectory simulation',
'violations': []
}
def check_constraint_2_initial_conditions(trajectories: List,
x0: np.ndarray, v0: np.ndarray,
params: ProblemParameters) -> Dict:
"""
Constraint 2: Initial conditions
xᵢ[0] = 0 (or xᵢ⁰)
vᵢ[0] = vᵢ⁰
"""
violations = []
tol = 1e-6
for i, (x_traj, v_traj) in enumerate(trajectories):
if abs(x_traj[0] - x0[i]) > tol:
violations.append({
'vehicle': i,
'type': 'position',
'expected': x0[i],
'actual': x_traj[0],
'error': abs(x_traj[0] - x0[i])
})
if abs(v_traj[0] - v0[i]) > tol:
violations.append({
'vehicle': i,
'type': 'velocity',
'expected': v0[i],
'actual': v_traj[0],
'error': abs(v_traj[0] - v0[i])
})
return {
'satisfied': len(violations) == 0,
'type': 'initial_conditions',
'violations': violations
}
def check_constraint_3_acceleration_limits(u_profiles: np.ndarray,
params: ProblemParameters) -> Dict:
"""
Constraint 3: Acceleration limits
u_min ≤ uᵢ[k] ≤ u_max ∀i ∈ N, k ∈ ET
"""
violations = []
for i in range(u_profiles.shape[0]):
# Check lower bound
below_min = u_profiles[i, :] < params.u_min
if np.any(below_min):
violations.append({
'vehicle': i,
'type': 'below_minimum',
'min_value': np.min(u_profiles[i, :]),
'limit': params.u_min,
'count': np.sum(below_min),
'timesteps': np.where(below_min)[0].tolist()
})
# Check upper bound
above_max = u_profiles[i, :] > params.u_max
if np.any(above_max):
violations.append({
'vehicle': i,
'type': 'above_maximum',
'max_value': np.max(u_profiles[i, :]),
'limit': params.u_max,
'count': np.sum(above_max),
'timesteps': np.where(above_max)[0].tolist()
})
return {
'satisfied': len(violations) == 0,
'type': 'acceleration_limits',
'violations': violations
}
def check_constraint_4_velocity_limits(trajectories: List, params: ProblemParameters) -> Dict:
"""
Constraint 4: Velocity constraints (no stopping in intersection)
Before merging zone: v_min_approach ≤ vᵢ[k] ≤ v_max
Inside merging zone: v_min ≤ vᵢ[k] ≤ v_max (no stopping)
"""
violations = []
for i, (x_traj, v_traj) in enumerate(trajectories):
# Find where vehicle enters merging zone (x >= L - S)
in_merge_zone = x_traj >= (params.L - params.S)
# Before merging zone
before_merge = ~in_merge_zone
v_before = v_traj[before_merge]
if len(v_before) > 0:
below_min = v_before < params.v_min_approach
if np.any(below_min):
violations.append({
'vehicle': i,
'zone': 'approach',
'type': 'below_minimum',
'min_velocity': np.min(v_before),
'limit': params.v_min_approach,
'count': np.sum(below_min)
})
# Inside merging zone (no stopping constraint)
v_inside = v_traj[in_merge_zone]
if len(v_inside) > 0:
below_min = v_inside < params.v_min
if np.any(below_min):
violations.append({
'vehicle': i,
'zone': 'merging',
'type': 'stopping_violation',
'min_velocity': np.min(v_inside),
'limit': params.v_min,
'count': np.sum(below_min)
})
# Check upper bound everywhere
above_max = v_traj > params.v_max
if np.any(above_max):
violations.append({
'vehicle': i,
'zone': 'all',
'type': 'above_maximum',
'max_velocity': np.max(v_traj),
'limit': params.v_max,
'count': np.sum(above_max)
})
return {
'satisfied': len(violations) == 0,
'type': 'velocity_limits',
'violations': violations
}
def check_constraint_5_reaching_zones(trajectories: List, params: ProblemParameters) -> Dict:
"""
Constraint 5: Vehicles must reach merging zone AND exit control zone
UPDATED: With extended time horizon (K=100), this constraint checks that vehicles
eventually reach the exit. The time minimization objective ensures they don't
dawdle - vehicles that take longer get worse objective values.
Checks for:
1. Vehicle reaches merging zone entry (x >= L - S)
2. Vehicle reaches control zone exit (x >= L)
3. No teleportation: position is monotonically increasing
4. Vehicle properly enters merge zone (not just touches it)
"""
violations = []
for i, (x_traj, v_traj) in enumerate(trajectories):
# Check 1: Reaches merging zone
reaches_merge = np.any(x_traj >= (params.L))
if not reaches_merge:
violations.append({
'vehicle': i,
'type': 'does_not_reach_merging_zone',
'max_position': np.max(x_traj),
'target': params.L,
'deficit': (params.L) - np.max(x_traj),
'note': f'Vehicle did not reach merge zone even with {params.T_max}s horizon'
})
# Check 2: Reaches exit
reaches_exit = np.any(x_traj >= params.L)
if not reaches_exit:
violations.append({
'vehicle': i,
'type': 'does_not_reach_exit',
'max_position': np.max(x_traj),
'target': params.L,
'deficit': (params.L) - np.max(x_traj),
'note': f'Vehicle did not complete crossing even with {params.T_max}s horizon'
})
# Check 3: No teleportation (monotonic increasing)
# Position should never decrease (vehicles only move forward)
position_decreases = np.diff(x_traj) < -1e-6 # Small tolerance for numerical error
if np.any(position_decreases):
violations.append({
'vehicle': i,
'type': 'position_not_monotonic',
'note': 'Vehicle position decreased (impossible for forward motion)',
'first_violation_index': np.where(position_decreases)[0][0]
})
# Check 4: Vehicle actually ENTERS merging zone (not just touches it)
# Must spend at least 2 time steps inside merging zone
in_merge_zone = (x_traj >= params.L - params.S) & (x_traj < params.L)
time_steps_in_merge = np.sum(in_merge_zone)
if reaches_merge and time_steps_in_merge < 2:
violations.append({
'vehicle': i,
'type': 'insufficient_time_in_merge_zone',
'time_steps': time_steps_in_merge,
'required': 2,
'note': 'Vehicle barely touches merge zone instead of properly entering'
})
return {
'satisfied': len(violations) == 0,
'type': 'reaching_zones',
'violations': violations
}
def check_constraint_6_rear_end_collision(trajectories: List,
t0: np.ndarray,
params: ProblemParameters) -> Dict:
"""
Constraint 6: Rear-end collision avoidance (SAME LANE only)
Only check vehicles traveling in the EXACT SAME DIRECTION:
- E→W vehicles only check against other E→W
- W→E vehicles only check against other W→E
- N→S vehicles only check against other N→S
- S→N vehicles only check against other S→N
Note: Same road but opposite direction = no rear-end collision possible
"""
violations = []
dt = params.dt
# Check all vehicle pairs
for i in range(params.N - 1):
for j in range(i + 1, params.N):
# Only check if in same lane (same direction)
if not params.vehicles_in_same_lane(i, j):
continue
x_i, v_i = trajectories[i]
x_j, v_j = trajectories[j]
# Create time arrays
t_i = t0[i] + np.arange(len(x_i)) * dt
t_j = t0[j] + np.arange(len(x_j)) * dt
# Find overlapping time range
t_start = max(t_i[0], t_j[0])
t_end = min(t_i[-1], t_j[-1])
if t_start >= t_end:
continue
# Sample common time points
common_times = np.arange(t_start, t_end, dt)
# Interpolate positions
x_i_common = np.interp(common_times, t_i, x_i)
x_j_common = np.interp(common_times, t_j, x_j)
# Check separation
separation = np.abs(x_i_common - x_j_common)
min_separation = np.min(separation)
min_sep_idx = np.argmin(separation)
min_sep_time = common_times[min_sep_idx]
if min_separation < params.delta:
violations.append({
'vehicle_pair': (i, j),
'direction': params.get_vehicle_direction(i),
'min_separation': min_separation,
'required': params.delta,
'deficit': params.delta - min_separation,
'time_of_min_separation': min_sep_time,
'position_i': x_i_common[min_sep_idx],
'position_j': x_j_common[min_sep_idx]
})
return {
'satisfied': len(violations) == 0,
'type': 'rear_end_collision',
'violations': violations
}
def check_constraint_6b_lateral_physical_collision(trajectories: List,
t0: np.ndarray,
params: ProblemParameters) -> Dict:
"""
Constraint 6B: Physical lateral collision (CONFLICT-POINT BASED)
NEW IMPLEMENTATION: Allows multiple vehicles in intersection simultaneously,
but checks if they reach the CONFLICT POINT (center of intersection) at
dangerously close times.
For perpendicular vehicles (EW/WE vs NS/SN):
- Compute when each reaches the conflict point (L - S/2)
- Check if arrival times differ by at least safety margin
- Safety margin = delta / v_min (time needed to clear conflict point)
"""
violations = []
dt = params.dt
conflict_matrix = params.get_conflict_matrix()
# Conflict point is at the CENTER of the merging zone
conflict_position = params.L - params.S / 2.0
# Minimum time separation at conflict point (seconds)
# Based on: time = distance / velocity
min_time_separation = params.delta / params.v_min
for i in range(params.N):
for j in range(i + 1, params.N):
if conflict_matrix[i, j] != 1:
continue # Not perpendicular, skip
x_i, v_i = trajectories[i]
x_j, v_j = trajectories[j]
t_i = t0[i] + np.arange(len(x_i)) * dt
t_j = t0[j] + np.arange(len(x_j)) * dt
# Find when each vehicle reaches conflict point
# Use linear interpolation for accuracy
# Vehicle i: find crossing time
if x_i[-1] < conflict_position:
# Doesn't reach conflict point
continue
idx_before_i = np.where(x_i < conflict_position)[0]
idx_after_i = np.where(x_i >= conflict_position)[0]
if len(idx_after_i) == 0:
continue
k_cross_i = idx_after_i[0]
if k_cross_i == 0:
t_cross_i = t_i[0]
v_cross_i = v_i[0]
else:
# Linear interpolation
x_before = x_i[k_cross_i - 1]
x_after = x_i[k_cross_i]
t_before = t_i[k_cross_i - 1]
t_after = t_i[k_cross_i]
alpha = (conflict_position - x_before) / (x_after - x_before)
t_cross_i = t_before + alpha * (t_after - t_before)
v_cross_i = v_i[k_cross_i - 1] + alpha * (v_i[k_cross_i] - v_i[k_cross_i - 1])
# Vehicle j: find crossing time
if x_j[-1] < conflict_position:
continue
idx_after_j = np.where(x_j >= conflict_position)[0]
if len(idx_after_j) == 0:
continue
k_cross_j = idx_after_j[0]
if k_cross_j == 0:
t_cross_j = t_j[0]
v_cross_j = v_j[0]
else:
x_before = x_j[k_cross_j - 1]
x_after = x_j[k_cross_j]
t_before = t_j[k_cross_j - 1]
t_after = t_j[k_cross_j]
alpha = (conflict_position - x_before) / (x_after - x_before)
t_cross_j = t_before + alpha * (t_after - t_before)
v_cross_j = v_j[k_cross_j - 1] + alpha * (v_j[k_cross_j] - v_j[k_cross_j - 1])
# Check time separation at conflict point
time_separation = abs(t_cross_i - t_cross_j)
# Required separation depends on speeds
# Use conservative estimate: slower vehicle needs more clearance
v_slower = min(abs(v_cross_i), abs(v_cross_j))
if v_slower < 0.1: # Near-zero velocity
v_slower = params.v_min
required_separation = params.delta / v_slower
if time_separation < required_separation:
violations.append({
'vehicle_pair': (i, j),
'direction_i': params.get_vehicle_direction(i),
'direction_j': params.get_vehicle_direction(j),
't_cross_i': t_cross_i,
't_cross_j': t_cross_j,
'time_separation': time_separation,
'required_separation': required_separation,
'deficit': required_separation - time_separation,
'conflict_position': conflict_position
})
return {
'satisfied': len(violations) == 0,
'type': 'lateral_physical_collision',
'note': 'Conflict-point based: checks arrival time at intersection center',
'violations': violations
}
def check_constraint_7_lateral_collision(trajectories: List,
Z_binary: np.ndarray,
t0: np.ndarray,
params: ProblemParameters) -> Dict:
"""
Constraint 7: Lateral collision avoidance (priority timing rules)
FIXED: Properly handles binary variables by ROUNDING to nearest integer
Z values from SA might be continuous (0.3, 0.7), but we interpret as binary:
- Z < 0.5 → treat as 0 (vehicle j has priority)
- Z >= 0.5 → treat as 1 (vehicle i has priority)
"""
violations = []
conflict_matrix = params.get_conflict_matrix()
z_index = 0
for i in range(params.N):
for j in range(i + 1, params.N):
if conflict_matrix[i, j] == 1:
# These vehicles conflict (perpendicular paths)
# Get Z_ij and ROUND to binary
if z_index < len(Z_binary):
z_ij_raw = Z_binary[z_index]
z_ij = 1.0 if z_ij_raw >= 0.5 else 0.0 # ROUND to binary
else:
z_ij = 0.5 # Unspecified
z_index += 1
# Find merging times
x_i, v_i = trajectories[i]
x_j, v_j = trajectories[j]
# Entry time to merging zone (x >= L - S)
idx_i = np.where(x_i >= params.L)[0]
t_m_i = t0[i] + (idx_i[0] * params.dt if len(idx_i) > 0 else np.inf)
idx_j = np.where(x_j >= params.L)[0]
t_m_j = t0[j] + (idx_j[0] * params.dt if len(idx_j) > 0 else np.inf)
# Exit time from merging zone (x >= L)
idx_exit_i = np.where(x_i >= params.L + params.S)[0]
t_f_i = t0[i] + (idx_exit_i[0] * params.dt if len(idx_exit_i) > 0 else np.inf)
idx_exit_j = np.where(x_j >= params.L + params.S)[0]
t_f_j = t0[j] + (idx_exit_j[0] * params.dt if len(idx_exit_j) > 0 else np.inf)
# Safety time buffer
crossing_time = params.dt_safe
# Check priority constraint based on ROUNDED Z value
if z_ij >= 0.5:
# Vehicle i has priority (should exit before j enters)
required = t_f_i + crossing_time <= t_f_j + crossing_time/2
gap = t_f_j + crossing_time/2 - (t_f_i + crossing_time)
if not required:
violations.append({
'vehicle_pair': (i, j),
'priority': f'Vehicle {i} should go first (Z={z_ij_raw:.2f}→{z_ij:.0f})',
'z_ij_raw': z_ij_raw,
'z_ij_rounded': z_ij,
't_m_i': t_m_i,
't_f_i': t_f_i,
't_m_j': t_m_j,
'time_gap': gap,
'required_gap': 0.0,
'type': 'insufficient_separation'
})
else:
# Vehicle j has priority (z_ij = 0, meaning z_ji = 1)
required = t_f_j + crossing_time <= t_m_i
gap = t_m_i - (t_f_j + crossing_time)
if not required:
violations.append({
'vehicle_pair': (i, j),
'priority': f'Vehicle {j} should go first (Z={z_ij_raw:.2f}→{z_ij:.0f})',
'z_ij_raw': z_ij_raw,
'z_ij_rounded': z_ij,
't_m_j': t_m_j,
't_f_j': t_f_j,
't_m_i': t_m_i,
'time_gap': gap,
'required_gap': 0.0,
'type': 'insufficient_separation'
})
return {
'satisfied': len(violations) == 0,
'type': 'lateral_collision',
'note': 'Binary variables rounded: Z<0.5→0, Z≥0.5→1',
'violations': violations
}
# ============================================================================
# MASTER FEASIBILITY CHECKER
# ============================================================================
def feasibility_check(x_decision: np.ndarray,
x0: np.ndarray,
v0: np.ndarray,
t0: np.ndarray,
params: ProblemParameters) -> Tuple[bool, Dict]:
"""
Master feasibility checker - evaluates all 7 constraints - now handles VARIABLE length trajectories
"""
# Simulate trajectories (adaptive horizon)
N = params.N
K_nominal = params.K
dt = params.dt
L = params.L
u_profiles = x_decision[:N * K_nominal].reshape(N, K_nominal)
Z_binary = x_decision[N*K_nominal:] # Binary variables
# Simulate each vehicle until completion
trajectories = []
for i in range(N):
x_traj, v_traj, k_actual = simulate_until_completion(
u_profiles[i], x0[i], v0[i], dt, L, K_max=params.K
)
trajectories.append((x_traj, v_traj))
# Check all constraints
all_violations = {}
all_violations['constraint_1_dynamics'] = check_constraint_1_dynamics(
trajectories, u_profiles, x0, v0, params)
all_violations['constraint_2_initial_conditions'] = check_constraint_2_initial_conditions(
trajectories, x0, v0, params)
all_violations['constraint_3_acceleration_limits'] = check_constraint_3_acceleration_limits(
u_profiles, params)
all_violations['constraint_4_velocity_limits'] = check_constraint_4_velocity_limits(
trajectories, params)
all_violations['constraint_5_reaching_zones'] = check_constraint_5_reaching_zones(
trajectories, params)
all_violations['constraint_6_rear_end_collision'] = check_constraint_6_rear_end_collision(
trajectories, t0, params)
all_violations['constraint_6b_lateral_physical'] = check_constraint_6b_lateral_physical_collision(
trajectories, t0, params)
all_violations['constraint_7_lateral_collision'] = check_constraint_7_lateral_collision(
trajectories, Z_binary, t0, params)
# Determine overall feasibility
is_feasible = all(
result['satisfied']
for result in all_violations.values()
)
return is_feasible, all_violations
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
def generate_random_solution(params: ProblemParameters, scale: float = 0.3) -> np.ndarray:
"""
Generate a random solution for testing
Args:
params: Problem parameters
scale: Fraction of acceleration bounds to use (0-1)
scale=0.3 for safe testing, scale=1.0 for full exploration
Returns:
x: Decision vector [u_profiles, Z_binary]
"""
N = params.N
K = params.K
# Generate random acceleration profiles
u_profiles = np.random.uniform(
params.u_min * scale,
params.u_max * scale,
size=(N, K)
)
# Generate random binary variables
n_conflicts = np.sum(params.get_conflict_matrix()) // 2
Z_binary = np.random.randint(0, 2, size=n_conflicts).astype(float)
# Concatenate
x = np.concatenate([u_profiles.flatten(), Z_binary])
return x
def print_constraint_summary(violations: Dict):
"""Simple constraint summary - robust to different violation payloads."""
import numpy as np
print("\n" + "="*70)
print("CONSTRAINT CHECKING SUMMARY")
print("="*70)
constraint_names = {
'constraint_1_dynamics': 'Constraint 1: Vehicle Dynamics',
'constraint_2_initial_conditions': 'Constraint 2: Initial Conditions',
'constraint_3_acceleration_limits': 'Constraint 3: Acceleration Limits',
'constraint_4_velocity_limits': 'Constraint 4: Velocity Limits',
'constraint_5_reaching_zones': 'Constraint 5: Reaching Zones',
'constraint_6_rear_end_collision': 'Constraint 6: Rear-End Physical Collision',
'constraint_6b_lateral_physical': 'Constraint 6B: Lateral Physical Collision',
'constraint_7_lateral_collision': 'Constraint 7: Priority Timing Rules'
}
for key, name in constraint_names.items():
result = violations[key]
status = "[PASS]" if result['satisfied'] else "[FAIL]"
print(f"{name}: {status}")
if result['satisfied']:
continue
for v in result['violations']:
# ---------- Constraint 5: several subtypes ----------
if key == 'constraint_5_reaching_zones':
vtype = v.get('type', '')
if vtype in ('does_not_reach_merging_zone', 'does_not_reach_exit'):
max_pos = v.get('max_position', float('nan'))
target = v.get('target', float('nan'))
print(f" V{v.get('vehicle','?')}: Reached {max_pos:.1f}m, needed {target:.1f}m")
elif vtype == 'position_not_monotonic':
idx = v.get('first_violation_index', '?')
print(f" V{v.get('vehicle','?')}: position decreased (first at k={idx})")
elif vtype == 'insufficient_time_in_merge_zone':
steps = v.get('time_steps', 0)
req = v.get('required', 2)
print(f" V{v.get('vehicle','?')}: spent {steps} steps in merge (min {req})")
else:
print(f" V{v.get('vehicle','?')}: {vtype} – details: {v}")
# ---------- Constraint 6: rear-end (same lane) ----------
elif key == 'constraint_6_rear_end_collision':
i, j = v['vehicle_pair']
print(f" V{i} & V{j}: {v['min_separation']:.2f}m apart (need {v['required']:.1f}m)")
# ---------- Constraint 6B: lateral physical (conflict point) ----------
elif key == 'constraint_6b_lateral_physical':
i, j = v['vehicle_pair']
sep = v.get('time_separation', float('nan'))
req = v.get('required_clearance', float('nan'))
print(f" V{i} ({v.get('direction_i','?')}) & V{j} ({v.get('direction_j','?')}): "
f"Δt={sep:.2f}s < req {req:.2f}s (PHYSICAL COLLISION)")
# ---------- Constraint 7: priority timing ----------
elif key == 'constraint_7_lateral_collision':
i, j = v['vehicle_pair']
gap = v.get('time_gap', float('nan'))
if isinstance(gap, (int, float)) and np.isfinite(gap):
print(f" V{i} & V{j}: time gap {gap:.1f}s (violates assigned priority)")
else:
print(f" V{i} & V{j}: time gap -inf (vehicle didn’t reach merge/exit)")
# ============================================================================
# VISUALIZATION FUNCTIONS
# ============================================================================
def plot_combined_visualization(x_decision: np.ndarray, x0: np.ndarray,
v0: np.ndarray, t0: np.ndarray,
params: ProblemParameters):
"""
Combined visualization: Animation + Stats + Timeline (NO position plot)
Layout: Top row = Animation + Stats, Bottom row = Timeline