Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
86 lines (66 loc) · 2.77 KB
/
Copy pathmain.py
File metadata and controls
86 lines (66 loc) · 2.77 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
import time
import numpy as np
from pinocchio.visualize import MeshcatVisualizer
import meshcat
from dynamics import build_augmented_model, _build_symbolic_forward_dynamics, step_numpy, build_fk_rotation
from mpc_acados import AcadosMPCController
DT = 0.02
N_HORIZON = 30
SIM_DURATION = 30.0
def main():
print("Building augmented KUKA + pendulum model...")
model, visual_model, collision_model = build_augmented_model()
nq = model.nq
print("Building CasADi dynamics...")
# Acados handles integration internally, but we use this to get the symbolic expressions
f_dynamics = _build_symbolic_forward_dynamics(model)
f_fk = build_fk_rotation(model)
print("Setting up Acados MPC controller...")
# Note: Initial compilation may take a few seconds
mpc = AcadosMPCController(model, f_dynamics, f_fk, N=N_HORIZON, dt=DT)
viz_server = meshcat.Visualizer()
viz = MeshcatVisualizer(model, collision_model, visual_model)
viz.initViewer(viewer=viz_server)
viz.loadViewerModel()
print(f"MeshCat URL: {viz_server.url()}")
pend_idx = nq - 1
x = np.zeros(2 * nq)
x[3] = -np.pi/2
viz.display(x[:nq])
print("-" * 80)
print("Starting simulation with Acados...")
input("Press Enter to start the simulation...")
time.sleep(2)
n_steps = int(SIM_DURATION / DT)
t_sim = 0.0
for step in range(n_steps):
dynamic_z = 1
t_wall_start = time.perf_counter()
u_opt, info = mpc.solve(x, target_z_val=dynamic_z)
if info['status'] != 0:
print(f"MPC FAILED: Status {info['status']}") # This usually explains the violation
break
if t_sim > 0 and abs(t_sim % 5.0) < DT:
print(">>> 💥 APPLYING KICK!")
# nq is the start of the velocity vector, pend_idx is the last joint
x[nq + pend_idx] += 1.0 # Add 8 rad/s sudden velocity
# Simulation step
x = step_numpy(model, x, u_opt, DT)
viz.display(x[:nq])
t_wall = (time.perf_counter() - t_wall_start) * 1000.0
t_sim += DT
nu = nq - 1
if np.any(x[:nu] < model.lowerPositionLimit[:nu]) or np.any(x[:nu] > model.upperPositionLimit[:nu]):
print(">>> KUKA POSITION LIMITS VIOLATED!")
if np.any(x[nq:nq+nu] < -model.velocityLimit[:nu]) or np.any(x[nq:nq+nu] > model.velocityLimit[:nu]):
max_v = np.max(np.abs(x[nq:nq+nu]))
print(f">>> KUKA VELOCITY LIMITS VIOLATED! (Peak velocity: {max_v:.2f} rad/s)")
if step % 10 == 0:
print(
f"t={t_sim:5.2f}s | "
f"theta={info['pendulum_angle']:+8.4f} | "
f"solve={info['solve_time_ms']:6.2f}ms | "
f"wall={t_wall:6.2f}ms"
)
if __name__ == "__main__":
main()