-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmpc.rs
More file actions
8151 lines (7329 loc) · 298 KB
/
Copy pathmpc.rs
File metadata and controls
8151 lines (7329 loc) · 298 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
#![allow(dead_code)]
//! Model Predictive Control (MPC) for path tracking
//!
//! author: Atsushi Sakai (@Atsushi_twi)
//! Ryohei Sasaki (@rsasaki0109)
//! Rust port
//!
//! This version follows the PythonRobotics structure more closely:
//! - speed profile generation
//! - yaw smoothing
//! - iterative linear MPC around an operational point
use nalgebra::{Matrix2, Matrix4, Matrix4x2, Vector2, Vector4};
use std::f64::consts::PI;
// Vehicle parameters
const WB: f64 = 2.5; // wheelbase [m]
const MAX_STEER: f64 = 45.0 * PI / 180.0; // max steering angle [rad]
const MAX_DSTEER: f64 = 30.0 * PI / 180.0; // max steering rate [rad/s]
const MAX_SPEED: f64 = 55.0 / 3.6; // max speed [m/s]
const MIN_SPEED: f64 = -20.0 / 3.6; // min speed (reverse) [m/s]
const MAX_ACCEL: f64 = 1.0; // max acceleration [m/ss]
// MPC parameters, aligned with PythonRobotics
const T: usize = 5; // prediction horizon
const DT: f64 = 0.2; // time step [s]
const TARGET_SPEED: f64 = 10.0 / 3.6; // [m/s]
const GOAL_DIS: f64 = 1.5; // goal distance threshold
const STOP_SPEED: f64 = 0.5 / 3.6; // stop speed threshold
const MAX_ITER: usize = 3; // iterative linear MPC outer iterations
const DU_TH: f64 = 0.1; // outer-loop convergence threshold
const N_IND_SEARCH: usize = 10; // nearest-index search window
const PATH_RESOLUTION: f64 = 0.5; // [m]
const UPSTREAM_SWITCH_BACK_TICK: f64 = 1.0; // [m]
const MAX_SIM_STEPS: usize = 2000;
// Inner projected-gradient solver settings
const QP_MAX_ITERS: usize = 200;
const LINE_SEARCH_ITERS: usize = 16;
const LINE_SEARCH_INITIAL_STEP: f64 = 0.25;
const GRAD_TOL: f64 = 1.0e-5;
const COST_TOL: f64 = 1.0e-7;
// Cost weights
const Q: [f64; 4] = [1.0, 1.0, 0.5, 0.5];
const QF: [f64; 4] = Q;
const R: [f64; 2] = [0.01, 0.01];
const RD: [f64; 2] = [0.01, 1.0];
/// Vehicle state
#[derive(Clone, Copy, Debug)]
pub struct State {
pub x: f64,
pub y: f64,
pub v: f64,
pub yaw: f64,
}
impl State {
pub fn new(x: f64, y: f64, v: f64, yaw: f64) -> Self {
Self { x, y, v, yaw }
}
pub fn to_vector(self) -> Vector4<f64> {
Vector4::new(self.x, self.y, self.v, self.yaw)
}
pub fn update(&mut self, accel: f64, steer: f64) {
let steer = steer.clamp(-MAX_STEER, MAX_STEER);
self.x += self.v * self.yaw.cos() * DT;
self.y += self.v * self.yaw.sin() * DT;
self.yaw += self.v / WB * steer.tan() * DT;
self.yaw = normalize_angle(self.yaw);
self.v += accel * DT;
self.v = self.v.clamp(MIN_SPEED, MAX_SPEED);
}
}
#[derive(Debug)]
pub struct MpcResult {
pub controls: Vec<Vector2<f64>>,
pub predicted: Vec<Vector4<f64>>,
}
#[derive(Debug)]
pub struct SimulationResult {
pub cx: Vec<f64>,
pub cy: Vec<f64>,
pub hist_x: Vec<f64>,
pub hist_y: Vec<f64>,
pub predicted_x: Vec<f64>,
pub predicted_y: Vec<f64>,
pub goal: (f64, f64),
pub reached_goal: bool,
pub target_index: usize,
pub final_index: usize,
pub final_state: State,
}
pub fn normalize_angle(angle: f64) -> f64 {
let mut value = angle % (2.0 * PI);
if value > PI {
value -= 2.0 * PI;
} else if value < -PI {
value += 2.0 * PI;
}
value
}
fn angle_diff(a: f64, b: f64) -> f64 {
normalize_angle(a - b)
}
fn state_error(state: Vector4<f64>, reference: Vector4<f64>) -> Vector4<f64> {
let mut error = state - reference;
error[3] = angle_diff(state[3], reference[3]);
error
}
fn control_cost_weight() -> Matrix2<f64> {
Matrix2::from_diagonal(&Vector2::new(R[0], R[1]))
}
fn control_rate_weight() -> Matrix2<f64> {
Matrix2::from_diagonal(&Vector2::new(RD[0], RD[1]))
}
fn state_cost_weight() -> Matrix4<f64> {
Matrix4::from_diagonal(&Vector4::new(Q[0], Q[1], Q[2], Q[3]))
}
fn terminal_cost_weight() -> Matrix4<f64> {
Matrix4::from_diagonal(&Vector4::new(QF[0], QF[1], QF[2], QF[3]))
}
fn get_linear_model_matrix(
v: f64,
yaw: f64,
steer: f64,
) -> (Matrix4<f64>, Matrix4x2<f64>, Vector4<f64>) {
let a = Matrix4::new(
1.0,
0.0,
DT * yaw.cos(),
-DT * v * yaw.sin(),
0.0,
1.0,
DT * yaw.sin(),
DT * v * yaw.cos(),
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
DT * steer.tan() / WB,
1.0,
);
let b = Matrix4x2::new(
0.0,
0.0,
0.0,
0.0,
DT,
0.0,
0.0,
DT * v / (WB * steer.cos().powi(2)),
);
let c = Vector4::new(
DT * v * yaw.sin() * yaw,
-DT * v * yaw.cos() * yaw,
0.0,
-DT * v * steer / (WB * steer.cos().powi(2)),
);
(a, b, c)
}
/// Cubic spline for reference path
struct CubicSpline1D {
x: Vec<f64>,
a: Vec<f64>,
b: Vec<f64>,
c: Vec<f64>,
d: Vec<f64>,
}
impl CubicSpline1D {
fn new(x: &[f64], y: &[f64]) -> Self {
let n = x.len();
let a = y.to_vec();
let mut b = vec![0.0; n];
let mut c = vec![0.0; n];
let mut d = vec![0.0; n];
let h: Vec<f64> = (0..n - 1).map(|i| x[i + 1] - x[i]).collect();
let mut alpha = vec![0.0; n];
for i in 1..n - 1 {
alpha[i] = 3.0 / h[i] * (a[i + 1] - a[i]) - 3.0 / h[i - 1] * (a[i] - a[i - 1]);
}
let mut l = vec![1.0; n];
let mut mu = vec![0.0; n];
let mut z = vec![0.0; n];
for i in 1..n - 1 {
l[i] = 2.0 * (x[i + 1] - x[i - 1]) - h[i - 1] * mu[i - 1];
mu[i] = h[i] / l[i];
z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
}
for j in (0..n - 1).rev() {
c[j] = z[j] - mu[j] * c[j + 1];
b[j] = (a[j + 1] - a[j]) / h[j] - h[j] * (c[j + 1] + 2.0 * c[j]) / 3.0;
d[j] = (c[j + 1] - c[j]) / (3.0 * h[j]);
}
Self {
x: x.to_vec(),
a,
b,
c,
d,
}
}
fn calc(&self, t: f64) -> f64 {
let i = self.search_index(t);
let dx = t - self.x[i];
self.a[i] + self.b[i] * dx + self.c[i] * dx.powi(2) + self.d[i] * dx.powi(3)
}
fn calc_d(&self, t: f64) -> f64 {
let i = self.search_index(t);
let dx = t - self.x[i];
self.b[i] + 2.0 * self.c[i] * dx + 3.0 * self.d[i] * dx.powi(2)
}
fn search_index(&self, t: f64) -> usize {
for i in 0..self.x.len() - 1 {
if self.x[i] <= t && t < self.x[i + 1] {
return i;
}
}
self.x.len() - 2
}
}
/// 2D Cubic spline path
struct CubicSpline2D {
s: Vec<f64>,
sx: CubicSpline1D,
sy: CubicSpline1D,
}
impl CubicSpline2D {
fn new(x: &[f64], y: &[f64]) -> Self {
let mut s = vec![0.0];
for i in 1..x.len() {
let ds = ((x[i] - x[i - 1]).powi(2) + (y[i] - y[i - 1]).powi(2)).sqrt();
s.push(s[i - 1] + ds);
}
let sx = CubicSpline1D::new(&s, x);
let sy = CubicSpline1D::new(&s, y);
Self { s, sx, sy }
}
fn calc_position(&self, s: f64) -> (f64, f64) {
(self.sx.calc(s), self.sy.calc(s))
}
fn calc_yaw(&self, s: f64) -> f64 {
let dx = self.sx.calc_d(s);
let dy = self.sy.calc_d(s);
dy.atan2(dx)
}
}
fn smooth_yaw(yaw: &mut [f64]) {
for i in 0..yaw.len().saturating_sub(1) {
let mut dyaw = yaw[i + 1] - yaw[i];
while dyaw >= PI / 2.0 {
yaw[i + 1] -= 2.0 * PI;
dyaw = yaw[i + 1] - yaw[i];
}
while dyaw <= -PI / 2.0 {
yaw[i + 1] += 2.0 * PI;
dyaw = yaw[i + 1] - yaw[i];
}
}
}
pub fn calc_speed_profile(cx: &[f64], cy: &[f64], cyaw: &[f64], target_speed: f64) -> Vec<f64> {
let mut speed_profile = vec![target_speed; cx.len()];
let mut direction = 1.0;
for i in 0..cx.len().saturating_sub(1) {
let dx = cx[i + 1] - cx[i];
let dy = cy[i + 1] - cy[i];
let move_direction = dy.atan2(dx);
if dx.abs() > f64::EPSILON && dy.abs() > f64::EPSILON {
let dangle = angle_diff(move_direction, cyaw[i]).abs();
direction = if dangle >= PI / 4.0 { -1.0 } else { 1.0 };
}
speed_profile[i] = direction * target_speed;
}
if let Some(last) = speed_profile.last_mut() {
*last = 0.0;
}
speed_profile
}
fn calc_nearest_index(
state: &State,
cx: &[f64],
cy: &[f64],
cyaw: &[f64],
pind: usize,
) -> (usize, f64) {
let start = pind.min(cx.len().saturating_sub(1));
let end = (start + N_IND_SEARCH).min(cx.len());
let mut best_index = start;
let mut best_distance_sq = f64::INFINITY;
for i in start..end {
let dx = state.x - cx[i];
let dy = state.y - cy[i];
let distance_sq = dx * dx + dy * dy;
if distance_sq < best_distance_sq {
best_distance_sq = distance_sq;
best_index = i;
}
}
let mut best_distance = best_distance_sq.sqrt();
let dxl = cx[best_index] - state.x;
let dyl = cy[best_index] - state.y;
let angle = angle_diff(cyaw[best_index], dyl.atan2(dxl));
if angle < 0.0 {
best_distance *= -1.0;
}
(best_index, best_distance)
}
fn calc_ref_trajectory(
state: &State,
cx: &[f64],
cy: &[f64],
cyaw: &[f64],
speed_profile: &[f64],
course_tick: f64,
pind: usize,
) -> (Vec<Vector4<f64>>, usize) {
let ncourse = cx.len();
let (mut ind, _) = calc_nearest_index(state, cx, cy, cyaw, pind);
if pind >= ind {
ind = pind;
}
let mut xref = vec![Vector4::zeros(); T + 1];
xref[0] = Vector4::new(cx[ind], cy[ind], speed_profile[ind], cyaw[ind]);
let mut travel = 0.0;
for point in xref.iter_mut().take(T + 1).skip(1) {
travel += state.v.abs() * DT;
let dind = (travel / course_tick).round() as usize;
let index = (ind + dind).min(ncourse - 1);
*point = Vector4::new(cx[index], cy[index], speed_profile[index], cyaw[index]);
}
(xref, ind)
}
fn predict_motion(state: State, controls: &[Vector2<f64>]) -> Vec<Vector4<f64>> {
let mut predicted = vec![Vector4::zeros(); T + 1];
predicted[0] = state.to_vector();
let mut current = state;
for (i, control) in controls.iter().enumerate().take(T) {
current.update(control[0], control[1]);
predicted[i + 1] = current.to_vector();
}
predicted
}
fn apply_control_constraints(controls: &mut [Vector2<f64>]) {
for i in 0..controls.len() {
controls[i][0] = controls[i][0].clamp(-MAX_ACCEL, MAX_ACCEL);
controls[i][1] = controls[i][1].clamp(-MAX_STEER, MAX_STEER);
if i > 0 {
let delta = controls[i][1] - controls[i - 1][1];
let max_delta = MAX_DSTEER * DT;
if delta.abs() > max_delta {
controls[i][1] = controls[i - 1][1] + max_delta * delta.signum();
}
}
}
}
type LinearizedRollout = (
Vec<Vector4<f64>>,
Vec<Matrix4<f64>>,
Vec<Matrix4x2<f64>>,
Vec<Vector4<f64>>,
);
fn linearized_rollout(
x0: &State,
xbar: &[Vector4<f64>],
controls: &[Vector2<f64>],
) -> LinearizedRollout {
let mut x = vec![Vector4::zeros(); T + 1];
let mut a_seq = Vec::with_capacity(T);
let mut b_seq = Vec::with_capacity(T);
let mut c_seq = Vec::with_capacity(T);
x[0] = x0.to_vector();
for t in 0..T {
let (a, b, c) = get_linear_model_matrix(xbar[t][2], xbar[t][3], 0.0);
let mut next = a * x[t] + b * controls[t] + c;
next[3] = normalize_angle(next[3]);
a_seq.push(a);
b_seq.push(b);
c_seq.push(c);
x[t + 1] = next;
}
(x, a_seq, b_seq, c_seq)
}
fn compute_cost(x: &[Vector4<f64>], xref: &[Vector4<f64>], controls: &[Vector2<f64>]) -> f64 {
let q = state_cost_weight();
let qf = terminal_cost_weight();
let r = control_cost_weight();
let rd = control_rate_weight();
let mut cost = 0.0;
for t in 0..T {
cost += controls[t].dot(&(r * controls[t]));
if t != 0 {
let err = state_error(x[t], xref[t]);
cost += err.dot(&(q * err));
}
if t < T - 1 {
let du = controls[t + 1] - controls[t];
cost += du.dot(&(rd * du));
}
}
let terminal_error = state_error(x[T], xref[T]);
cost + terminal_error.dot(&(qf * terminal_error))
}
#[allow(clippy::needless_range_loop)]
fn solve_qp_clarabel(
xref: &[Vector4<f64>],
xbar: &[Vector4<f64>],
state: &State,
) -> Option<Vec<Vector2<f64>>> {
use clarabel::algebra::*;
use clarabel::solver::*;
let nu = 2;
let nx = 4;
let n_u = nu * T;
let n_x = nx * (T + 1);
let n = n_u + n_x;
let u_idx = |t: usize, k: usize| -> usize { t * nu + k };
let x_idx = |t: usize, k: usize| -> usize { n_u + t * nx + k };
// --- Build P (cost Hessian, upper triangular) ---
let mut p_rows = Vec::new();
let mut p_cols = Vec::new();
let mut p_vals = Vec::new();
for t in 0..T {
for k in 0..nu {
let idx = u_idx(t, k);
let mut val = R[k];
if t > 0 {
val += RD[k];
}
if t < T - 1 {
val += RD[k];
}
p_rows.push(idx);
p_cols.push(idx);
p_vals.push(val * 2.0);
}
if t < T - 1 {
for k in 0..nu {
let i = u_idx(t, k);
let j = u_idx(t + 1, k);
p_rows.push(i);
p_cols.push(j);
p_vals.push(-RD[k] * 2.0);
}
}
}
for t in 1..=T {
let w = if t == T { QF } else { Q };
for k in 0..nx {
let idx = x_idx(t, k);
p_rows.push(idx);
p_cols.push(idx);
p_vals.push(w[k] * 2.0);
}
}
let p = CscMatrix::new_from_triplets(n, n, p_rows, p_cols, p_vals);
// --- Build q (linear cost) ---
let mut q_vec = vec![0.0; n];
for t in 1..=T {
let w = if t == T { QF } else { Q };
for k in 0..nx {
q_vec[x_idx(t, k)] = -w[k] * 2.0 * xref[t][k];
}
}
// --- Build constraints ---
let n_eq = nx * (T + 1);
let n_steer_rate = T - 1;
let n_u_box = 2 * nu * T;
let n_steer_rate_box = 2 * n_steer_rate;
let n_v_box = 2 * (T + 1);
let n_ineq = n_u_box + n_steer_rate_box + n_v_box;
let mut a_rows = Vec::new();
let mut a_cols = Vec::new();
let mut a_vals = Vec::new();
let mut b_vec = vec![0.0; n_eq + n_ineq];
let x0 = state.to_vector();
for k in 0..nx {
a_rows.push(k);
a_cols.push(x_idx(0, k));
a_vals.push(1.0);
b_vec[k] = x0[k];
}
for t in 0..T {
let (a_mat, b_mat, c_vec) = get_linear_model_matrix(xbar[t][2], xbar[t][3], 0.0);
let base_row = nx * (t + 1);
for i in 0..nx {
let row = base_row + i;
a_rows.push(row);
a_cols.push(x_idx(t + 1, i));
a_vals.push(-1.0);
for j in 0..nx {
let val = a_mat[(i, j)];
if val.abs() > 1e-15 {
a_rows.push(row);
a_cols.push(x_idx(t, j));
a_vals.push(val);
}
}
for j in 0..nu {
let val = b_mat[(i, j)];
if val.abs() > 1e-15 {
a_rows.push(row);
a_cols.push(u_idx(t, j));
a_vals.push(val);
}
}
b_vec[row] = -c_vec[i];
}
}
let ineq_offset = n_eq;
let mut ineq_row = 0;
let u_bounds = [MAX_ACCEL, MAX_STEER];
for t in 0..T {
for (k, &bound) in u_bounds.iter().enumerate() {
let row = ineq_offset + ineq_row;
a_rows.push(row);
a_cols.push(u_idx(t, k));
a_vals.push(1.0);
b_vec[row] = bound;
ineq_row += 1;
let row = ineq_offset + ineq_row;
a_rows.push(row);
a_cols.push(u_idx(t, k));
a_vals.push(-1.0);
b_vec[row] = bound;
ineq_row += 1;
}
}
let max_steer_delta = MAX_DSTEER * DT;
for t in 0..(T - 1) {
let row = ineq_offset + ineq_row;
a_rows.push(row);
a_cols.push(u_idx(t + 1, 1));
a_vals.push(1.0);
a_rows.push(row);
a_cols.push(u_idx(t, 1));
a_vals.push(-1.0);
b_vec[row] = max_steer_delta;
ineq_row += 1;
let row = ineq_offset + ineq_row;
a_rows.push(row);
a_cols.push(u_idx(t + 1, 1));
a_vals.push(-1.0);
a_rows.push(row);
a_cols.push(u_idx(t, 1));
a_vals.push(1.0);
b_vec[row] = max_steer_delta;
ineq_row += 1;
}
for t in 0..=T {
let row = ineq_offset + ineq_row;
a_rows.push(row);
a_cols.push(x_idx(t, 2));
a_vals.push(1.0);
b_vec[row] = MAX_SPEED;
ineq_row += 1;
let row = ineq_offset + ineq_row;
a_rows.push(row);
a_cols.push(x_idx(t, 2));
a_vals.push(-1.0);
b_vec[row] = -MIN_SPEED;
ineq_row += 1;
}
let m = n_eq + n_ineq;
let a_csc = CscMatrix::new_from_triplets(m, n, a_rows, a_cols, a_vals);
let cones = vec![
SupportedConeT::ZeroConeT(n_eq),
SupportedConeT::NonnegativeConeT(n_ineq),
];
let settings = DefaultSettingsBuilder::default()
.verbose(false)
.build()
// Default settings builder always succeeds
.expect("DefaultSettingsBuilder with defaults should not fail");
let mut solver = DefaultSolver::new(&p, &q_vec, &a_csc, &b_vec, &cones, settings).ok()?;
solver.solve();
if solver.solution.status != SolverStatus::Solved {
return None;
}
let z = &solver.solution.x;
let controls: Vec<Vector2<f64>> = (0..T)
.map(|t| Vector2::new(z[u_idx(t, 0)], z[u_idx(t, 1)]))
.collect();
Some(controls)
}
fn optimize_linearized_controls(
xref: &[Vector4<f64>],
xbar: &[Vector4<f64>],
state: &State,
initial_controls: &[Vector2<f64>],
) -> Vec<Vector2<f64>> {
let pg_controls = optimize_linearized_controls_pg(xref, xbar, state, initial_controls);
// Adaptive solver selection: only invoke QP solver during reverse maneuvers
// where the projected-gradient solver struggles with the nonlinear coupling.
// During forward driving, PG alone is sufficient and faster.
let is_reverse = state.v < -0.1 || xref.iter().any(|x| x[2] < -0.1);
if is_reverse {
if let Some(qp_controls) = solve_qp_clarabel(xref, xbar, state) {
let (qp_x, _, _, _) = linearized_rollout(state, xbar, &qp_controls);
let qp_cost = compute_cost(&qp_x, xref, &qp_controls);
let (pg_x, _, _, _) = linearized_rollout(state, xbar, &pg_controls);
let pg_cost = compute_cost(&pg_x, xref, &pg_controls);
if qp_cost <= pg_cost {
return qp_controls;
}
}
}
pg_controls
}
fn optimize_linearized_controls_pg(
xref: &[Vector4<f64>],
xbar: &[Vector4<f64>],
state: &State,
initial_controls: &[Vector2<f64>],
) -> Vec<Vector2<f64>> {
let q = state_cost_weight();
let qf = terminal_cost_weight();
let r = control_cost_weight();
let rd = control_rate_weight();
let mut controls = initial_controls.to_vec();
controls.resize(T, Vector2::zeros());
apply_control_constraints(&mut controls);
let mut previous_cost = f64::INFINITY;
for _ in 0..QP_MAX_ITERS {
let (x, a_seq, b_seq, _) = linearized_rollout(state, xbar, &controls);
let current_cost = compute_cost(&x, xref, &controls);
let mut gradients = [Vector2::zeros(); T];
let mut lambda = (qf * state_error(x[T], xref[T])) * 2.0;
for t in (0..T).rev() {
let mut grad = (r * controls[t]) * 2.0 + b_seq[t].transpose() * lambda;
if t > 0 {
grad += (rd * (controls[t] - controls[t - 1])) * 2.0;
}
if t < T - 1 {
grad -= (rd * (controls[t + 1] - controls[t])) * 2.0;
}
gradients[t] = grad;
let lx = if t == 0 {
Vector4::zeros()
} else {
(q * state_error(x[t], xref[t])) * 2.0
};
lambda = lx + a_seq[t].transpose() * lambda;
}
let gradient_norm = gradients
.iter()
.map(Vector2::norm_squared)
.sum::<f64>()
.sqrt();
if gradient_norm <= GRAD_TOL || (previous_cost - current_cost).abs() <= COST_TOL {
break;
}
previous_cost = current_cost;
let current_controls = controls.clone();
let mut best_candidate_controls = None;
let mut best_candidate_cost = current_cost;
let mut step = LINE_SEARCH_INITIAL_STEP;
for &large_step in &[1.0, 0.5] {
let mut candidate = current_controls.clone();
for t in 0..T {
candidate[t] -= gradients[t] * large_step;
}
apply_control_constraints(&mut candidate);
let (candidate_x, _, _, _) = linearized_rollout(state, xbar, &candidate);
let candidate_cost = compute_cost(&candidate_x, xref, &candidate);
if candidate_cost < best_candidate_cost {
best_candidate_cost = candidate_cost;
best_candidate_controls = Some(candidate);
}
}
for _ in 0..LINE_SEARCH_ITERS {
let mut candidate = current_controls.clone();
for t in 0..T {
candidate[t] -= gradients[t] * step;
}
apply_control_constraints(&mut candidate);
let (candidate_x, _, _, _) = linearized_rollout(state, xbar, &candidate);
let candidate_cost = compute_cost(&candidate_x, xref, &candidate);
if candidate_cost < best_candidate_cost {
best_candidate_cost = candidate_cost;
best_candidate_controls = Some(candidate);
}
step *= 0.5;
}
if let Some(candidate) = best_candidate_controls {
controls = candidate;
} else {
break;
}
}
controls
}
pub fn iterative_linear_mpc_control(
xref: &[Vector4<f64>],
state: &State,
warm_start: &[Vector2<f64>],
) -> MpcResult {
let mut controls = warm_start.to_vec();
controls.resize(T, Vector2::zeros());
apply_control_constraints(&mut controls);
let mut predicted = predict_motion(*state, &controls);
for _ in 0..MAX_ITER {
let previous_controls = controls.clone();
controls = optimize_linearized_controls(xref, &predicted, state, &controls);
predicted = predict_motion(*state, &controls);
let du = controls
.iter()
.zip(previous_controls.iter())
.map(|(current, previous)| {
(current[0] - previous[0]).abs() + (current[1] - previous[1]).abs()
})
.sum::<f64>();
if du <= DU_TH {
break;
}
}
MpcResult {
controls,
predicted,
}
}
fn next_warm_start(controls: &[Vector2<f64>]) -> Vec<Vector2<f64>> {
let mut warm_start = controls[1..].to_vec();
warm_start.push(controls.last().copied().unwrap_or(Vector2::zeros()));
warm_start
}
pub fn check_goal(
state: &State,
goal: (f64, f64),
target_index: usize,
final_index: usize,
) -> bool {
let dx = state.x - goal.0;
let dy = state.y - goal.1;
let distance = (dx * dx + dy * dy).sqrt();
let near_goal = distance <= GOAL_DIS;
let near_end = final_index.abs_diff(target_index) < 5;
let stopped = state.v.abs() <= STOP_SPEED;
near_goal && near_end && stopped
}
fn sample_reference_course(
ax: &[f64],
ay: &[f64],
course_tick: f64,
) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
let csp = CubicSpline2D::new(ax, ay);
let s_max = *csp.s.last().unwrap_or(&0.0);
let mut cx = Vec::new();
let mut cy = Vec::new();
let mut cyaw = Vec::new();
let mut s = 0.0;
while s <= s_max {
let (x, y) = csp.calc_position(s);
cx.push(x);
cy.push(y);
cyaw.push(csp.calc_yaw(s));
s += course_tick;
}
if cx.is_empty() || cy.is_empty() || cyaw.is_empty() {
cx.push(ax[0]);
cy.push(ay[0]);
cyaw.push(0.0);
}
(cx, cy, cyaw)
}
pub fn generate_reference_course(ax: &[f64], ay: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
let (cx, cy, mut cyaw) = sample_reference_course(ax, ay, PATH_RESOLUTION);
smooth_yaw(&mut cyaw);
(cx, cy, cyaw)
}
fn generate_switch_back_course() -> (Vec<f64>, Vec<f64>, Vec<f64>) {
let (mut cx, mut cy, mut cyaw) = sample_reference_course(
&[0.0, 30.0, 6.0, 20.0, 35.0],
&[0.0, 0.0, 20.0, 35.0, 20.0],
UPSTREAM_SWITCH_BACK_TICK,
);
let (cx2, cy2, mut cyaw2) = sample_reference_course(
&[35.0, 10.0, 0.0, 0.0],
&[20.0, 30.0, 5.0, 0.0],
UPSTREAM_SWITCH_BACK_TICK,
);
for yaw in &mut cyaw2 {
*yaw -= PI;
}
cx.extend(cx2);
cy.extend(cy2);
cyaw.extend(cyaw2);
smooth_yaw(&mut cyaw);
(cx, cy, cyaw)
}
pub fn run_mpc_simulation() -> SimulationResult {
let (cx, cy, cyaw) = generate_switch_back_course();
run_mpc_simulation_with_reference(cx, cy, cyaw, UPSTREAM_SWITCH_BACK_TICK, MAX_SIM_STEPS)
}
fn run_mpc_simulation_with_course(
ax: &[f64],
ay: &[f64],
max_sim_steps: usize,
) -> SimulationResult {
let (cx, cy, cyaw) = generate_reference_course(ax, ay);
run_mpc_simulation_with_reference(cx, cy, cyaw, PATH_RESOLUTION, max_sim_steps)
}
fn run_mpc_simulation_with_reference(
cx: Vec<f64>,
cy: Vec<f64>,
cyaw: Vec<f64>,
course_tick: f64,
max_sim_steps: usize,
) -> SimulationResult {
let speed_profile = calc_speed_profile(&cx, &cy, &cyaw, TARGET_SPEED);
let mut state = State::new(cx[0], cy[0], 0.0, cyaw[0]);
if state.yaw - cyaw[0] >= PI {
state.yaw -= 2.0 * PI;
} else if state.yaw - cyaw[0] <= -PI {
state.yaw += 2.0 * PI;
}
let mut target_index = 0;
let final_index = cx.len() - 1;
let goal = (cx[final_index], cy[final_index]);
let mut warm_start = vec![Vector2::zeros(); T];
let mut hist_x = vec![state.x];
let mut hist_y = vec![state.y];
let mut predicted = vec![state.to_vector()];
let mut reached_goal = false;
for _ in 0..max_sim_steps {
let (xref, new_index) = calc_ref_trajectory(
&state,
&cx,
&cy,
&cyaw,
&speed_profile,
course_tick,
target_index,
);
target_index = new_index;
let mpc_result = iterative_linear_mpc_control(&xref, &state, &warm_start);
let accel = mpc_result.controls[0][0];
let steer = mpc_result.controls[0][1];
state.update(accel, steer);
hist_x.push(state.x);
hist_y.push(state.y);
predicted = mpc_result.predicted;
warm_start = next_warm_start(&mpc_result.controls);
if check_goal(&state, goal, target_index, final_index) {
reached_goal = true;
break;
}
}
SimulationResult {
cx,
cy,