Repository navigation
Expand file tree
/
Copy pathsim_freeswing.py
More file actions
78 lines (56 loc) · 1.95 KB
/
Copy pathsim_freeswing.py
File metadata and controls
78 lines (56 loc) · 1.95 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
"""Free-swing simulation: KUKA held at neutral with PD control, pendulum swings under gravity."""
import time
import numpy as np
from pinocchio.visualize import MeshcatVisualizer
import meshcat
from dynamics import build_augmented_model, step_numpy
DT = 0.001
SIM_DURATION = 15.0
# PD gains to hold the KUKA joints at neutral
KP = 1000.0
KD = 40.0
def main():
model, visual_model, collision_model = build_augmented_model()
nq = model.nq
nu = nq - 1 # actuated KUKA joints
pend_idx = nq - 1 # last q entry is pendulum angle
torque_max = model.effortLimit[:nu]
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()}")
x = np.zeros(2 * nq)
x[pend_idx] = 0.3 # start pendulum horizontal (90 degrees from upright)
x[3] = -np.pi/4
x[1] = np.pi/4
viz.display(x[:nq])
q_target = x[:nu].copy()
input("Press Enter to start the free-swing simulation...")
n_steps = int(SIM_DURATION / DT)
t_sim = 0.0
t_wall_start = time.perf_counter()
viz_interval = max(1, int(1.0 / (60.0 * DT)))
for step in range(n_steps):
q = x[:nq]
v = x[nq:]
error = q_target - q[:nu]
u = KP * error - KD * v[:nu]
u = np.clip(u, -torque_max, torque_max)
x = step_numpy(model, x, u, DT, method="rk4")
t_sim += DT
if step % viz_interval == 0:
viz.display(x[:nq])
elapsed = time.perf_counter() - t_wall_start
ahead = t_sim - elapsed
if ahead > 0:
time.sleep(ahead)
if step % 1000 == 0:
print(
f"t={t_sim:5.2f}s | "
f"theta={x[pend_idx]:+8.4f} rad | "
f"omega={x[nq + pend_idx]:+8.4f} rad/s"
)
print(f"\nDone. Final pendulum angle: {x[pend_idx]:.4f} rad")
if __name__ == "__main__":
main()