Repository navigation
Expand file tree
/
Copy pathdls_lambda_analysis.py
More file actions
187 lines (158 loc) · 7.22 KB
/
Copy pathdls_lambda_analysis.py
File metadata and controls
187 lines (158 loc) · 7.22 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
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import time
# Fixed Parameters
L1, L2 = 210.0, 210.0
theta_init = np.radians([10.0, 10.0])
goal = np.array([-100.0, 10.0])
beta = 0.1
v_desired = 100.0
max_iter = 50000
tol = 0.1
LAMBDAS = [10, 20, 30, 40, 60, 100, 250, 500, 1000]
#FK
def fk(t):
return np.array([
L1*np.cos(t[0]) + L2*np.cos(t[0]+t[1]),
L1*np.sin(t[0]) + L2*np.sin(t[0]+t[1])
])
#Jacobian
def jacobian(t):
return np.matrix([
[-L1*np.sin(t[0]) - L2*np.sin(t[0]+t[1]), -L2*np.sin(t[0]+t[1])],
[ L1*np.cos(t[0]) + L2*np.cos(t[0]+t[1]), L2*np.cos(t[0]+t[1])]
])
# Run DLS for one lambda
def run_dls(lam):
theta = theta_init.copy()
path = [fk(theta)]
act_vels = []
goal_errs = []
total_time = 0.0
I2 = np.matrix(np.eye(2))
t_cpu = time.perf_counter()
for _ in range(max_iter):
pos = fk(theta)
err_vec = goal - pos
dist = np.linalg.norm(err_vec)
if dist < tol:
break
direction = err_vec / dist
dt_step = beta * dist / v_desired
v_cmd = np.matrix(v_desired * direction).T
J = jacobian(theta)
theta_dot = J.T * (J * J.T + lam**2 * I2).I * v_cmd
theta = theta + np.array(theta_dot).flatten() * dt_step
new_pos = fk(theta)
total_time += dt_step
act_vels.append(np.linalg.norm(new_pos - pos) / dt_step)
goal_errs.append(dist)
path.append(new_pos)
cpu_ms = (time.perf_counter() - t_cpu) * 1000
path = np.array(path)
n = len(path)
ideal = np.linspace(path[0], goal, n)
tr_err = np.linalg.norm(path - ideal, axis=1)
return {
'path' : path,
'ideal' : ideal,
'tr_err' : tr_err,
'act_vels' : np.array(act_vels),
'goal_errs' : np.array(goal_errs),
'n_iter' : n - 1,
'sim_time_ms': total_time * 1000,
'cpu_ms' : cpu_ms,
'residual' : np.linalg.norm(path[-1] - goal),
'max_vel' : np.max(act_vels) if len(act_vels) else 0,
'max_tr_err' : np.max(tr_err),
'converged' : np.linalg.norm(path[-1] - goal) < tol
}
# Run all lambdas
print(f"\n{'λ':>6} | {'Iters':>7} | {'Sim Time (ms)':>14} | {'CPU (ms)':>10} | "
f"{'Max Vel (mm/s)':>15} | {'Max Tr Err (mm)':>16} | {'Residual (mm)':>14} | {'Converged':>10}")
print("─" * 105)
results = {}
for lam in LAMBDAS:
r = run_dls(lam)
results[lam] = r
conv_str = "YES" if r['converged'] else "NO"
print(f"{lam:>6} | {r['n_iter']:>7} | {r['sim_time_ms']:>14.4f} | {r['cpu_ms']:>10.3f} | "
f"{r['max_vel']:>15.4f} | {r['max_tr_err']:>16.4f} | {r['residual']:>14.6f} | {conv_str:>10}")
# Color map for 9 lambdas
colors = plt.cm.plasma(np.linspace(0.08, 0.92, len(LAMBDAS)))
# Plot Layout
# Row 0 : path comparison — full width
# Row 1 : tracking error curves — left | velocity curves — right
# Row 2 : 5 scalar metrics vs lambda — full width
fig = plt.figure(figsize=(18, 14), layout='constrained')
fig.suptitle(
f"DLS IK — Lambda Comparison | β={beta} | v_desired={v_desired} mm/s "
f"| 2-Link Arm (L₁=L₂=210 mm) | Goal: (−100, 10) mm",
fontsize=12, fontweight='bold'
)
gs = gridspec.GridSpec(3, 5, figure=fig, height_ratios=[1.1, 1.0, 1.0], hspace=0.42, wspace=0.38)
ax_path = fig.add_subplot(gs[0, :]) # row 0 — full width
ax_trerr = fig.add_subplot(gs[1, :3]) # row 1 left — tracking error curves
ax_vel = fig.add_subplot(gs[1, 3:]) # row 1 right — velocity curves
ax_ni = fig.add_subplot(gs[2, 0]) # row 2 — n_iter
ax_st = fig.add_subplot(gs[2, 1]) # row 2 — sim time
ax_mv = fig.add_subplot(gs[2, 2]) # row 2 — max velocity
ax_me = fig.add_subplot(gs[2, 3]) # row 2 — max track error
ax_re = fig.add_subplot(gs[2, 4]) # row 2 — residual error
lam_arr = np.array(LAMBDAS)
n_iters = np.array([results[l]['n_iter'] for l in LAMBDAS])
sim_times= np.array([results[l]['sim_time_ms']for l in LAMBDAS])
max_vels = np.array([results[l]['max_vel'] for l in LAMBDAS])
max_errs = np.array([results[l]['max_tr_err'] for l in LAMBDAS])
residuals= np.array([results[l]['residual'] for l in LAMBDAS])
# 1.Path Comparison
for i, lam in enumerate(LAMBDAS):
p = results[lam]['path']
ax_path.plot(p[:, 0], p[:, 1], color=colors[i], lw=1.8, label=f'λ={lam}')
ideal_ref = results[LAMBDAS[0]]['ideal']
ax_path.plot(ideal_ref[:, 0], ideal_ref[:, 1], 'k--', lw=1.8, label='Ideal Path', zorder=10)
ax_path.plot(*results[LAMBDAS[0]]['path'][0], 'ko', ms=9, zorder=11, label='Start')
ax_path.plot(*goal, 'r*', ms=14, zorder=11, label='Goal')
ax_path.set_xlabel('X (mm)', fontsize=10); ax_path.set_ylabel('Y (mm)', fontsize=10)
ax_path.set_title('End-Effector Path — All λ Values', fontweight='bold')
ax_path.legend(fontsize=8, loc='upper right', ncol=5)
ax_path.grid(True, linestyle='--', alpha=0.5)
# 2.Tracking Error Curves
for i, lam in enumerate(LAMBDAS):
te = results[lam]['tr_err']
ax_trerr.plot(np.arange(len(te)), te, color=colors[i], lw=1.8, label=f'λ={lam}')
ax_trerr.axhline(tol, color='black', linestyle=':', lw=1.3, label=f'Tol={tol}mm')
ax_trerr.set_xlabel('Iteration', fontsize=10); ax_trerr.set_ylabel('Tracking Error (mm)', fontsize=10)
ax_trerr.set_title('Tracking Error vs Iteration', fontweight='bold')
ax_trerr.legend(fontsize=8, ncol=2); ax_trerr.grid(True, linestyle='--', alpha=0.5)
# 3.Velocity Curves
for i, lam in enumerate(LAMBDAS):
v = results[lam]['act_vels']
ax_vel.plot(np.arange(1, len(v)+1), v, color=colors[i], lw=1.8, label=f'λ={lam}')
ax_vel.axhline(v_desired, color='black', linestyle=':', lw=1.3, label=f'v_desired={v_desired}')
ax_vel.set_xlabel('Iteration', fontsize=10); ax_vel.set_ylabel('Velocity (mm/s)', fontsize=10)
ax_vel.set_title('Velocity vs Iteration', fontweight='bold')
ax_vel.legend(fontsize=8, ncol=2); ax_vel.grid(True, linestyle='--', alpha=0.5)
# Scalar Metrics vs Lambda
marker = 'o-'
lam_labels = [str(l) for l in LAMBDAS]
def style_ax(ax, title, ylabel, color):
ax.set_title(title, fontweight='bold', fontsize=9)
ax.set_xlabel('λ', fontsize=10); ax.set_ylabel(ylabel, fontsize=9)
ax.set_xscale('log'); ax.grid(True, linestyle='--', alpha=0.5)
ax.tick_params(axis='x', labelsize=8)
ax_ni.plot(lam_arr, n_iters, marker, color='royalblue', lw=2, ms=7)
style_ax(ax_ni, 'Iterations to Converge', 'Iterations', 'royalblue')
ax_st.plot(lam_arr, sim_times, marker, color='darkorange', lw=2, ms=7)
style_ax(ax_st, 'Total Sim Time', 'Time (ms)', 'darkorange')
ax_mv.plot(lam_arr, max_vels, marker, color='green', lw=2, ms=7)
ax_mv.axhline(v_desired, color='gray', linestyle=':', lw=1.3)
style_ax(ax_mv, 'Peak EE Velocity', 'Velocity (mm/s)', 'green')
ax_me.plot(lam_arr, max_errs, marker, color='crimson', lw=2, ms=7)
style_ax(ax_me, 'Max Tracking Error', 'Error (mm)', 'crimson')
ax_re.plot(lam_arr, residuals, marker, color='purple', lw=2, ms=7)
ax_re.axhline(tol, color='gray', linestyle=':', lw=1.3, label=f'Tol={tol}')
style_ax(ax_re, 'Residual Error at Goal', 'Residual (mm)', 'purple')
ax_re.legend(fontsize=8)
plt.show()