Repository navigation
Expand file tree
/
Copy pathMpc_controller.py
More file actions
808 lines (689 loc) · 25.8 KB
/
Copy pathMpc_controller.py
File metadata and controls
808 lines (689 loc) · 25.8 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
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, Sequence
import numpy as np
import osqp
import scipy.sparse as sp
import pybullet as p
import time
from sim2d.world import BoxObstacle, World2D
from obstacles import update_cone_positions
@dataclass(frozen=True, slots=True)
class MPCParams:
dt: float = 0.2
horizon: int = 40
robot_radius: float = 0.25
# Input bounds for holonomic robot (u = [vx, vy]).
u_min: float = -1.0
u_max: float = 1.0
# Tracking weights
w_pos: float = 10.0
w_terminal: float = 50.0
w_u: float = 0.2
# Only activate obstacle half-space constraints when the reference trajectory
# comes within this distance (meters) of the (inflated) obstacle.
obstacle_activation_distance: float = 1.0
# Soft constraint weight for moving obstacle avoidance slack variables.
w_moving_obstacle_slack: float = 10_000.0
# Only activate moving-obstacle constraints when the reference is within this distance.
moving_obstacle_activation_distance: float = 3.0
@dataclass(frozen=True, slots=True)
class MovingCircleObstacle:
"""
Moving circular obstacle with constant velocity.
center(t) = center0 + v * t
"""
center0: np.ndarray # (2,)
velocity: np.ndarray # (2,)
radius: float
def center(self, t: float) -> np.ndarray:
return np.asarray(self.center0, dtype=float).reshape(2) + float(t) * np.asarray(
self.velocity, dtype=float
).reshape(2)
def _polyline_arclength(points: np.ndarray) -> np.ndarray:
"""Cumulative arc-length parameter s for a polyline."""
if points.shape[0] <= 1:
return np.array([0.0], dtype=float)
seg = points[1:] - points[:-1]
seg_len = np.linalg.norm(seg, axis=1)
return np.concatenate(([0.0], np.cumsum(seg_len))).astype(float)
def _sample_polyline(points: np.ndarray, s_query: np.ndarray) -> np.ndarray:
"""
Samples polyline positions at arc-length values s_query.
points: (M,2)
s_query: (n,)
output: (n,2)
"""
if points.shape[0] == 1:
return np.repeat(points, s_query.size, axis=0)
s = _polyline_arclength(points)
total = float(s[-1])
if total == 0.0:
return np.repeat(points[:1], s_query.size, axis=0)
t = np.clip(s_query, 0.0, total)
x = np.interp(t, s, points[:, 0])
y = np.interp(t, s, points[:, 1])
return np.column_stack([x, y]).astype(float)
def _choose_box_halfspace(aabb, p_ref: np.ndarray, r: float) -> tuple[str, float]:
"""
Chooses one linear half-space constraint that keeps p outside the inflated box.
Returns (kind, rhs) with constraint always in form:
- kind == "x_le": x <= rhs
- kind == "x_ge": x >= rhs
- kind == "y_le": y <= rhs
- kind == "y_ge": y >= rhs
"""
xmin = aabb.xmin - r
xmax = aabb.xmax + r
ymin = aabb.ymin - r
ymax = aabb.ymax + r
x_ref, y_ref = float(p_ref[0]), float(p_ref[1])
# Positive margins mean the reference is already outside on that side.
m_left = xmin - x_ref
m_right = x_ref - xmax
m_below = ymin - y_ref
m_above = y_ref - ymax
margins = np.array([m_left, m_right, m_below, m_above], dtype=float)
side = int(np.argmax(margins))
if side == 0:
return "x_le", float(xmin)
if side == 1:
return "x_ge", float(xmax)
if side == 2:
return "y_le", float(ymin)
return "y_ge", float(ymax)
def _unit(v: np.ndarray, eps: float = 1e-9) -> np.ndarray:
n = float(np.linalg.norm(v))
if n < eps:
return np.array([1.0, 0.0], dtype=float)
return v / n
def _linearized_circle_avoidance(
p_ref: np.ndarray,
c: np.ndarray,
required_dist: float,
) -> tuple[np.ndarray, float]:
"""
Linearizes ||p - c|| >= required_dist around p_ref.
Returns (n, rhs) such that:
n^T p >= rhs
is the first-order approximation of the constraint at p_ref.
"""
p_ref = np.asarray(p_ref, dtype=float).reshape(2)
c = np.asarray(c, dtype=float).reshape(2)
d = p_ref - c
dist = float(np.linalg.norm(d))
n = _unit(d)
# If dist is ~0, the linearization direction is arbitrary; _unit picks [1,0].
# First-order: dist + n^T(p - p_ref) >= required_dist => n^T p >= required_dist - dist + n^T p_ref
rhs = float(required_dist - dist + float(np.dot(n, p_ref)))
return n, rhs
class HolonomicMPC:
"""
Linear MPC for a holonomic point robot with state [x,y] and input [vx,vy].
Decision vector:
z = [x0,y0, x1,y1, ... xN,yN, vx0,vy0, vx1,vy1, ... vx{N-1},vy{N-1}]
Solver: OSQP (QP with linear constraints l <= A z <= u).
"""
def __init__(self, params: MPCParams = MPCParams()) -> None:
self.p = params
def _idx_x(self, k: int) -> int:
return 2 * k
def _idx_y(self, k: int) -> int:
return 2 * k + 1
def _idx_u0(self) -> int:
return 2 * (self.p.horizon + 1)
def _idx_ux(self, k: int) -> int:
return self._idx_u0() + 2 * k
def _idx_uy(self, k: int) -> int:
return self._idx_u0() + 2 * k + 1
def build_reference(
self, x0: np.ndarray, waypoints: Iterable[np.ndarray]
) -> np.ndarray:
"""
Builds a (N+1,2) reference trajectory from x0 through waypoints.
"""
pts = [np.asarray(x0, dtype=float).reshape(2)]
for w in waypoints:
pts.append(np.asarray(w, dtype=float).reshape(2))
poly = np.vstack(pts)
# IMPORTANT: sample reference with a feasible step length, otherwise the
# reference might demand reaching far-away waypoints within the horizon,
# which makes hard obstacle constraints infeasible.
vmax = float(max(abs(self.p.u_min), abs(self.p.u_max)))
vref = 0.9 * np.sqrt(2.0) * vmax
s_query = np.arange(self.p.horizon + 1, dtype=float) * float(self.p.dt) * vref
return _sample_polyline(poly, s_query)
def build_qp(
self,
x0: np.ndarray,
reference: np.ndarray,
world: World2D | None = None,
moving_obstacles: Sequence[MovingCircleObstacle] | None = None,
t0: float = 0.0,
) -> tuple[sp.csc_matrix, np.ndarray, sp.csc_matrix, np.ndarray, np.ndarray]:
"""
Builds OSQP matrices (P,q,A,l,u).
"""
N = int(self.p.horizon)
dt = float(self.p.dt)
rr = float(self.p.robot_radius)
nx, nu = 2, 2
n_moving = 0 if moving_obstacles is None else int(len(moving_obstacles))
n_slack = n_moving * N # one slack per moving obstacle per step k=1..N
n_vars = (N + 1) * nx + N * nu + n_slack
slack0 = (N + 1) * nx + N * nu
def idx_slack(i_obs: int, k: int) -> int:
# k is 1..N
return slack0 + i_obs * N + (k - 1)
# Quadratic cost: sum_k ||x_k - xref_k||_Q^2 + ||u_k||_R^2 + terminal.
Q = np.diag([self.p.w_pos, self.p.w_pos])
QN = np.diag([self.p.w_terminal, self.p.w_terminal])
R = np.diag([self.p.w_u, self.p.w_u])
P = sp.lil_matrix((n_vars, n_vars), dtype=float)
q = np.zeros(n_vars, dtype=float)
for k in range(N + 1):
Qk = QN if k == N else Q
ix = self._idx_x(k)
iy = self._idx_y(k)
P[ix, ix] += 2.0 * Qk[0, 0]
P[iy, iy] += 2.0 * Qk[1, 1]
q[ix] += -2.0 * Qk[0, 0] * float(reference[k, 0])
q[iy] += -2.0 * Qk[1, 1] * float(reference[k, 1])
for k in range(N):
iux = self._idx_ux(k)
iuy = self._idx_uy(k)
P[iux, iux] += 2.0 * R[0, 0]
P[iuy, iuy] += 2.0 * R[1, 1]
# Moving obstacle slack penalty
if n_slack:
w = float(self.p.w_moving_obstacle_slack)
for j in range(n_slack):
P[slack0 + j, slack0 + j] += 2.0 * w
# Constraints
boxes = []
if world is not None:
boxes = [obs for obs in world.obstacles if isinstance(obs, BoxObstacle)]
# Rows count
n_init = 2
n_dyn = 2 * N
n_state_bounds = 2 * (N + 1)
n_input_bounds = 2 * N
n_obs = len(boxes) * N # k=1..N; 1 constraint per box per step
n_moving_avoid = n_moving * N # one inequality per moving obstacle per step
n_slack_bounds = n_slack # s >= 0
n_cons = (
n_init
+ n_dyn
+ n_state_bounds
+ n_input_bounds
+ n_obs
+ n_moving_avoid
+ n_slack_bounds
)
A = sp.lil_matrix((n_cons, n_vars), dtype=float)
l = np.full(n_cons, -np.inf, dtype=float)
u = np.full(n_cons, np.inf, dtype=float)
row = 0
# Initial state equality: x0 == given
x0 = np.asarray(x0, dtype=float).reshape(2)
A[row, self._idx_x(0)] = 1.0
l[row] = u[row] = float(x0[0])
row += 1
A[row, self._idx_y(0)] = 1.0
l[row] = u[row] = float(x0[1])
row += 1
# Dynamics: x_{k+1} - x_k - dt*u_k = 0
for k in range(N):
# x
A[row, self._idx_x(k + 1)] = 1.0
A[row, self._idx_x(k)] = -1.0
A[row, self._idx_ux(k)] = -dt
l[row] = u[row] = 0.0
row += 1
# y
A[row, self._idx_y(k + 1)] = 1.0
A[row, self._idx_y(k)] = -1.0
A[row, self._idx_uy(k)] = -dt
l[row] = u[row] = 0.0
row += 1
# State bounds (world bounds)
if world is None:
xmin, xmax, ymin, ymax = -np.inf, np.inf, -np.inf, np.inf
else:
xmin = world.bounds.xmin + rr
xmax = world.bounds.xmax - rr
ymin = world.bounds.ymin + rr
ymax = world.bounds.ymax - rr
for k in range(N + 1):
A[row, self._idx_x(k)] = 1.0
l[row] = float(xmin)
u[row] = float(xmax)
row += 1
A[row, self._idx_y(k)] = 1.0
l[row] = float(ymin)
u[row] = float(ymax)
row += 1
# Input bounds
for k in range(N):
A[row, self._idx_ux(k)] = 1.0
l[row] = float(self.p.u_min)
u[row] = float(self.p.u_max)
row += 1
A[row, self._idx_uy(k)] = 1.0
l[row] = float(self.p.u_min)
u[row] = float(self.p.u_max)
row += 1
# Obstacle half-space constraints (Option 1)
if boxes:
# Decide ONE side per obstacle, based on the closest reference point.
# This prevents "side switching" mid-horizon, which can easily make the
# QP infeasible under input limits.
side_for_box: list[tuple[str, float]] = []
for obs in boxes:
d = np.array(
[
obs.signed_distance(reference[k], inflate=rr)
for k in range(N + 1)
],
dtype=float,
)
k_star = int(np.argmin(d))
side_for_box.append(
_choose_box_halfspace(obs.aabb, reference[k_star], rr)
)
for k in range(1, N + 1):
pref = reference[k]
for obs, (kind, rhs) in zip(boxes, side_for_box, strict=True):
# Activate only near obstacles; otherwise keep this constraint row disabled.
if obs.signed_distance(pref, inflate=rr) <= float(
self.p.obstacle_activation_distance
):
if kind == "x_le":
A[row, self._idx_x(k)] = 1.0
u[row] = rhs
elif kind == "x_ge":
A[row, self._idx_x(k)] = -1.0
u[row] = -rhs
elif kind == "y_le":
A[row, self._idx_y(k)] = 1.0
u[row] = rhs
else: # y_ge
A[row, self._idx_y(k)] = -1.0
u[row] = -rhs
# l[row] stays -inf (inequality); if inactive, A row is all-zeros and u=inf.
row += 1
# Moving obstacle avoidance constraints (soft via slack variables).
if moving_obstacles is not None and len(moving_obstacles) > 0:
act = float(self.p.moving_obstacle_activation_distance)
for k in range(1, N + 1):
pref = reference[k]
tk = float(t0) + k * dt
for i_obs, obs in enumerate(moving_obstacles):
c = obs.center(tk)
required = rr + float(obs.radius)
# Only activate when the reference comes close (keeps constraints sparse/benign).
dist_ref = float(np.linalg.norm(pref - c)) - required
if dist_ref <= act:
n, rhs = _linearized_circle_avoidance(pref, c, required)
# n^T p_k + s >= rhs <=> -n^T p_k - s <= -rhs
A[row, self._idx_x(k)] = -float(n[0])
A[row, self._idx_y(k)] = -float(n[1])
A[row, idx_slack(i_obs, k)] = -1.0
u[row] = -float(rhs)
row += 1
# Slack bounds: s >= 0
if n_slack:
for i_obs in range(n_moving):
for k in range(1, N + 1):
A[row, idx_slack(i_obs, k)] = 1.0
l[row] = 0.0
u[row] = np.inf
row += 1
assert row == n_cons
return P.tocsc(), q, A.tocsc(), l, u
def solve(
self,
x0: np.ndarray,
waypoints: Iterable[np.ndarray],
world: World2D | None = None,
moving_obstacles: Sequence[MovingCircleObstacle] | None = None,
t0: float = 0.0,
) -> dict:
"""
Solves MPC once and returns the optimal first control and predicted states.
"""
reference = self.build_reference(x0, waypoints)
P, q, A, l, u = self.build_qp(
x0=x0,
reference=reference,
world=world,
moving_obstacles=moving_obstacles,
t0=t0,
)
solver = osqp.OSQP()
solver.setup(P=P, q=q, A=A, l=l, u=u, verbose=False)
res = solver.solve()
if res.info.status_val not in (1, 2): # solved / solved inaccurate
raise RuntimeError(f"OSQP failed: {res.info.status}")
z = res.x
N = int(self.p.horizon)
xs = np.column_stack([z[self._idx_x(k)] for k in range(N + 1)]).T
ys = np.column_stack([z[self._idx_y(k)] for k in range(N + 1)]).T
traj = np.hstack([xs, ys])
u0 = np.array([z[self._idx_ux(0)], z[self._idx_uy(0)]], dtype=float)
return {"u0": u0, "traj": traj, "reference": reference, "osqp_result": res}
def run_closed_loop(
*,
n_steps: int = 200,
goal_tol: float = 0.25,
moving: bool = False,
) -> tuple[object, np.ndarray, list[np.ndarray], float | None]:
"""
Simple closed-loop simulation for quick debugging.
Returns (scenario, robot_traj, obstacle_centers_over_time).
"""
from sim2d.scenarios import mpc_blocks_with_waypoints
s = mpc_blocks_with_waypoints()
params = MPCParams(
dt=0.2,
horizon=45,
u_min=-1.0,
u_max=1.0,
obstacle_activation_distance=1.2,
moving_obstacle_activation_distance=3.0,
w_moving_obstacle_slack=10_000.0,
)
mpc = HolonomicMPC(params)
moving_obs: list[MovingCircleObstacle] = []
if moving:
# Circle crossing the robot corridor around x=-4, y≈0.5.
# Center starts left of the map and moves right at constant velocity.
moving_obs = [
MovingCircleObstacle(
center0=np.array([-5.0, -0.5], dtype=float),
velocity=np.array([0.25, 0.0], dtype=float), # crosses x=-4 at t≈4s
radius=0.45,
)
]
x = s.start.copy()
wps = [*s.waypoints, s.goal]
wp_idx = 0
traj = [x.copy()]
obs_centers: list[np.ndarray] = []
for step in range(int(n_steps)):
t = float(step) * float(mpc.p.dt)
if moving_obs:
obs_centers.append(moving_obs[0].center(t))
while wp_idx < len(wps) - 1 and np.linalg.norm(x - wps[wp_idx]) < 0.4:
wp_idx += 1
out = mpc.solve(
x0=x,
waypoints=wps[wp_idx:],
world=s.world,
moving_obstacles=moving_obs if moving_obs else None,
t0=t,
)
u = out["u0"]
x = x + mpc.p.dt * u
traj.append(x.copy())
if s.world.is_collision(x, robot_radius=s.robot_radius):
print(f"Collision with static world at step {step}, x={x}")
break
if np.linalg.norm(x - s.goal) < goal_tol:
print(f"Reached goal at step {step}, x={x}")
break
moving_radius = float(moving_obs[0].radius) if moving_obs else None
return s, np.array(traj), obs_centers, moving_radius
def _save_plot(
*,
scenario: object,
traj: np.ndarray,
obs_centers: list[np.ndarray],
obs_radius: float | None,
out_path: str,
) -> None:
try:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
except ImportError:
print("matplotlib not installed; skipping plot.")
return
# Scenario has world/start/goal attributes (from sim2d.scenarios.Scenario2D).
world = getattr(scenario, "world")
goal = getattr(scenario, "goal")
robot_radius = getattr(scenario, "robot_radius")
fig, ax = plt.subplots(figsize=(6, 6))
world.plot(ax, robot_radius=robot_radius)
ax.plot(traj[:, 0], traj[:, 1], "b-", label="closed-loop traj")
ax.scatter([traj[0, 0]], [traj[0, 1]], c="tab:blue", label="start")
ax.scatter([goal[0]], [goal[1]], c="tab:green", label="goal")
if obs_centers:
obs_centers_arr = np.asarray(obs_centers, dtype=float)
ax.plot(
obs_centers_arr[:, 0],
obs_centers_arr[:, 1],
"r--",
linewidth=1.5,
label="moving obstacle path",
)
ax.scatter(
[obs_centers_arr[0, 0]],
[obs_centers_arr[0, 1]],
c="red",
s=35,
label="moving obstacle start",
)
# draw a few snapshot circles
for idx in np.linspace(
0, len(obs_centers) - 1, num=min(6, len(obs_centers)), dtype=int
):
if obs_radius is not None:
ax.add_patch(
Circle(
obs_centers[idx],
float(obs_radius),
fill=False,
edgecolor="red",
linewidth=1.0,
alpha=0.7,
)
)
# Expand plot limits to include obstacle path even if it starts outside world bounds.
pad = 0.75
xmin = min(
world.bounds.xmin - 0.5,
float(traj[:, 0].min()) - pad,
float(obs_centers_arr[:, 0].min()) - pad,
)
xmax = max(
world.bounds.xmax + 0.5,
float(traj[:, 0].max()) + pad,
float(obs_centers_arr[:, 0].max()) + pad,
)
ymin = min(
world.bounds.ymin - 0.5,
float(traj[:, 1].min()) - pad,
float(obs_centers_arr[:, 1].min()) - pad,
)
ymax = max(
world.bounds.ymax + 0.5,
float(traj[:, 1].max()) + pad,
float(obs_centers_arr[:, 1].max()) + pad,
)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.legend()
fig.savefig(out_path, dpi=150, bbox_inches="tight")
print(f"Saved {out_path}")
def update_camera_follow(robot_id, distance=8.0, yaw=45, pitch=-45):
"""
Update camera to follow the robot.
Args:
robot_id: PyBullet robot ID
distance: Camera distance from target
yaw: Camera yaw angle (rotation around vertical axis)
pitch: Camera pitch angle (angle from horizontal, negative = looking down)
"""
# Get robot base position
robot_x = p.getJointState(robot_id, 0)[0]
robot_y = p.getJointState(robot_id, 1)[0]
target_pos = [robot_x, robot_y, 0.5] # Slightly above ground
p.resetDebugVisualizerCamera(
cameraDistance=distance,
cameraYaw=yaw,
cameraPitch=pitch,
cameraTargetPosition=target_pos,
)
def execute_mpc_path(
env,
robot_id,
mpc,
world2d,
base_path_2d,
moving_obstacles,
cone_ids,
arrival_threshold=0.25,
t0=0.0,
recorder=None,
robot_radius=0.25,
follow_camera=False,
max_steps=5000,
):
"""
Moves the robot along a 2D path using MPC while avoiding moving obstacles.
Args:
env: Simulation environment
robot_id: PyBullet robot ID
mpc: MPC controller
world2d: 2D world for obstacle avoidance
base_path_2d: List of 2D waypoints
moving_obstacles: List of moving obstacles
cone_ids: PyBullet IDs for cone visualization
arrival_threshold: Distance to goal to consider arrived
t0: Initial simulation time for moving obstacles
recorder: Optional BenchmarkRecorder for recording metrics
robot_radius: Robot radius for collision checking
follow_camera: If True, camera follows the robot
max_steps: Maximum number of simulation steps (default 5000 ~= 80s at 60Hz)
"""
x = np.array(
[
p.getJointState(robot_id, 0)[0],
p.getJointState(robot_id, 1)[0],
],
dtype=float,
)
prev_x = x.copy()
# Store initial arm joint positions to keep them fixed during MPC
# Joints 0,1,2 are base (x, y, theta), joints 3+ are arm
arm_joint_indices = list(range(3, p.getNumJoints(robot_id)))
arm_joint_positions = {}
for j in arm_joint_indices:
joint_info = p.getJointInfo(robot_id, j)
joint_type = joint_info[2]
# Only store movable joints (not fixed)
if joint_type != p.JOINT_FIXED:
arm_joint_positions[j] = p.getJointState(robot_id, j)[0]
base_goal_2d = base_path_2d[-1]
arrived = False
wp_idx = 0
step_idx = 0
dt = env.dt
action = np.zeros(env.n())
while not arrived:
start_loop_time = time.time()
# 1. Update dynamic obstacles
update_cone_positions(cone_ids, moving_obstacles, t0)
# 2. Advance waypoint if we are close enough to the current one
while (
wp_idx < len(base_path_2d) - 1
and np.linalg.norm(x - base_path_2d[wp_idx]) < 0.2
):
wp_idx += 1
# 3. Solve MPC
mpc_start = time.time()
output = mpc.solve(
x,
base_path_2d[wp_idx:],
world2d,
moving_obstacles,
t0,
)
mpc_latency = time.time() - mpc_start
# 4. Apply Action
action[:] = 0.0
action[0] = output["u0"][0]
action[1] = output["u0"][1]
env.step(action)
# 4b. Hold arm joints fixed to prevent collisions
for j, pos in arm_joint_positions.items():
p.resetJointState(robot_id, j, pos)
# 5. Update state and check completion
x = np.array([p.getJointState(robot_id, 0)[0], p.getJointState(robot_id, 1)[0]])
# 6. Record state for benchmarking
if recorder is not None:
# Calculate velocity
velocity = (x - prev_x) / dt if dt > 0 else np.zeros(2)
# Calculate minimum distance to static obstacles
static_dist = world2d.signed_distance(x, robot_radius=robot_radius)
# Also check distance to moving obstacles
moving_dist = float("inf")
for obs in moving_obstacles:
obs_center = obs.center(t0)
dist = np.linalg.norm(x - obs_center) - obs.radius - robot_radius
moving_dist = min(moving_dist, dist)
min_obstacle_dist = min(static_dist, moving_dist)
# Record state
recorder.record_state(
position=x,
velocity=velocity,
min_obstacle_distance=min_obstacle_dist,
mpc_latency=mpc_latency,
)
# Check for collision
if min_obstacle_dist < 0:
recorder.record_collision(x)
prev_x = x.copy()
# 7. Update camera to follow robot
if follow_camera:
update_camera_follow(robot_id, distance=10.0, yaw=0, pitch=-60)
if np.linalg.norm(x - base_goal_2d) < arrival_threshold:
arrived = True
# Check max steps to prevent infinite loops
if step_idx >= max_steps:
dist = np.linalg.norm(x - base_goal_2d)
print(f"MPC max steps reached ({max_steps}). Distance to goal: {dist:.3f}m")
break
# 8. Timing control
t0 += dt
loop_duration = time.time() - start_loop_time
time.sleep(max(0, dt - loop_duration))
if step_idx % 50 == 0:
u0 = output["u0"]
dist = np.linalg.norm(x - base_goal_2d)
print(
f"Base at: {x[0]:.2f}, {x[1]:.2f} | Goal: {base_goal_2d} | u0: [{u0[0]:.3f}, {u0[1]:.3f}] | dist: {dist:.3f}"
)
step_idx += 1
return t0
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--moving",
action="store_true",
help="Enable moving circular obstacle crossing the path.",
)
parser.add_argument("--steps", type=int, default=200)
args = parser.parse_args()
s, traj, obs, obs_radius = run_closed_loop(n_steps=args.steps, moving=args.moving)
print("Final:", traj[-1])
_save_plot(
scenario=s,
traj=traj,
obs_centers=obs,
obs_radius=obs_radius,
out_path=(
"mpc_closed_loop_moving.png" if args.moving else "mpc_closed_loop.png"
),
)