-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmotion_planning_composite_filed_ros.py
More file actions
2299 lines (1857 loc) · 97.5 KB
/
Copy pathmotion_planning_composite_filed_ros.py
File metadata and controls
2299 lines (1857 loc) · 97.5 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
#!/usr/bin/env python3
import numpy as np
import math
import matplotlib.pyplot as plt
import utils
import transformation as tsf
from iros2025_code import main_opt_static as mos
from scipy.optimize import minimize, differential_evolution
from scipy.interpolate import CubicSpline
from scipy.spatial import KDTree
import sys
import subprocess
# Get ROS workspace path
workspace_path = '/home/clover/catkin_ws'
last_relative_pose_wrists = None
last_object_pose = None
global ind
ind = 1
def launch_roslaunch():
launch_file = "~/catkin_ws/src/curi_whole_body_interface/launch/python_curi_dual_arm_ic_qbhand.launch"
command = f"roslaunch {launch_file}"
return subprocess.Popen(command, shell=True)
def vrpn_launch_roslaunch():
launch_file = "~/catkin_ws/src/vrpn_client_ros/launch/sample.launch"
command = f"roslaunch {launch_file} server:=192.168.10.7"
return subprocess.Popen(command, shell=True)
def signal_handler(sig, frame):
print('Python shutdown signal received...')
if 'roslaunch_process' in locals():
print('Shutdown roslaunch process.')
roslaunch_process.terminate()
roslaunch_process.wait()
print('Python shutdown.')
sys.exit(0)
def compress_bounds(joint_angle_bounds, q, compression_factor=0.5):
new_bounds = []
joint_center = q
for i, (lower, upper) in enumerate(joint_angle_bounds):
range_half = (upper - lower) * compression_factor / 2
center = joint_center[i]
new_lower = center - range_half
new_upper = center + range_half
new_bounds.append((new_lower, new_upper))
return new_bounds
def trans_shoulder2global(joint_pos, shoulder_pos, arm='right'):
if arm == 'left':
joint_pos[[0, 1]] = -joint_pos[[1, 0]]
joint_pos[1] = -joint_pos[1]
joint_pos = joint_pos + shoulder_pos
if arm == 'right':
joint_pos[[0, 1]] = -joint_pos[[1, 0]]
joint_pos = joint_pos + shoulder_pos
return joint_pos
def trans_global2shoulder(shoulder, elbow, wrist, arm='left'):
if arm == 'left':
elbow_new = elbow - shoulder
elbow_new = np.array([elbow_new[1], -elbow_new[0], elbow_new[2]])
wrist_new = wrist - shoulder
wrist_new = np.array([wrist_new[1], -wrist_new[0], wrist_new[2]])
if arm == 'right':
elbow_new = elbow - shoulder
elbow_new = np.array([-elbow_new[1], -elbow_new[0], elbow_new[2]])
wrist_new = wrist - shoulder
wrist_new = np.array([-wrist_new[1], -wrist_new[0], wrist_new[2]])
return elbow_new, wrist_new
def smooth_trajectory(waypoints, smoothing_factor=0.8, iterations=3):
"""
Smooth trajectory waypoints
waypoints: original trajectory points [N, 3]
smoothing_factor: smoothing factor (0-1), larger value means stronger smoothing
iterations: number of smoothing iterations
"""
if len(waypoints) <= 2:
return waypoints
smoothed = np.array(waypoints, copy=True)
for _ in range(iterations):
original_start = smoothed[0].copy()
original_end = smoothed[-1].copy()
for i in range(1, len(smoothed) - 1):
smoothed[i] = smoothed[i] * (1 - smoothing_factor) + \
(smoothed[i - 1] + smoothed[i + 1]) * 0.5 * smoothing_factor
smoothed[0] = original_start
smoothed[-1] = original_end
return smoothed
def generate_smooth_trajectory(waypoints, speed_limit, t_total, t_sample):
"""
Generate smooth trajectory based on given waypoints (fixed version)
waypoints: path points [N, 3]
speed_limit: maximum velocity limit
t_total: total time
t_sample: sampling time interval
"""
num_waypoints = len(waypoints)
if num_waypoints < 2:
raise ValueError("Need at least two waypoints to generate trajectory")
# Path length estimation
path_lengths = [0]
total_length = 0
for i in range(1, num_waypoints):
segment_length = np.linalg.norm(waypoints[i] - waypoints[i - 1])
total_length += segment_length
path_lengths.append(total_length)
# Time allocation based on path length
t_waypoints = np.zeros(num_waypoints)
for i in range(1, num_waypoints):
if total_length > 0:
t_waypoints[i] = t_total * path_lengths[i] / total_length
else:
t_waypoints[i] = t_total * i / (num_waypoints - 1)
# Ensure time is strictly increasing (fix duplicate time issue)
min_time_diff = 1e-6
for i in range(1, len(t_waypoints)):
if t_waypoints[i] <= t_waypoints[i - 1]:
t_waypoints[i] = t_waypoints[i - 1] + min_time_diff
print(f"Time waypoints: {t_waypoints}")
# Use cubic spline interpolation
splines = []
for dim in range(waypoints.shape[1]):
spline = CubicSpline(t_waypoints, waypoints[:, dim])
splines.append(spline)
# Generate trajectory sampling points
t_samples = np.arange(0, t_total, t_sample)
# Ensure last sampling point doesn't exceed t_total
if t_samples[-1] > t_total:
t_samples = t_samples[t_samples <= t_total]
positions = np.zeros((len(t_samples), waypoints.shape[1]))
velocities = np.zeros((len(t_samples), waypoints.shape[1]))
accelerations = np.zeros((len(t_samples), waypoints.shape[1]))
for dim, spline in enumerate(splines):
positions[:, dim] = spline(t_samples)
velocities[:, dim] = spline.derivative(1)(t_samples)
accelerations[:, dim] = spline.derivative(2)(t_samples)
# Velocity limiting
speeds = np.linalg.norm(velocities, axis=1)
max_speed = np.max(speeds) if len(speeds) > 0 else 0
if max_speed > speed_limit and max_speed > 0:
scale_factor = max_speed / speed_limit
t_total_adjusted = t_total * scale_factor
t_samples_adjusted = np.arange(0, t_total_adjusted, t_sample)
positions = np.zeros((len(t_samples_adjusted), waypoints.shape[1]))
velocities = np.zeros((len(t_samples_adjusted), waypoints.shape[1]))
accelerations = np.zeros((len(t_samples_adjusted), waypoints.shape[1]))
# Re-adjust time points
t_waypoints_adjusted = t_waypoints * scale_factor
for dim in range(waypoints.shape[1]):
adjusted_spline = CubicSpline(t_waypoints_adjusted, waypoints[:, dim])
positions[:, dim] = adjusted_spline(t_samples_adjusted)
velocities[:, dim] = adjusted_spline.derivative(1)(t_samples_adjusted) / scale_factor
accelerations[:, dim] = adjusted_spline.derivative(2)(t_samples_adjusted) / (scale_factor ** 2)
return positions
def find_optimal_ik_solution(task_goal_global, shoulder, d_uar, d_lar, joint_angle_bounds, method='global'):
"""
Find joint configuration that reaches task goal with minimal ergonomic score through optimization
Parameters:
- task_goal_global: task space goal point (global frame)
- shoulder: shoulder position (global frame)
- d_uar, d_lar: upper arm and lower arm length
- joint_angle_bounds: joint angle limits [(lower1, upper1), ...]
- method: 'global' (global search) or 'local' (local optimization)
Returns:
- target_q: optimal joint configuration
- target_hand: corresponding wrist position
- target_score: corresponding ergonomic score
- position_error: position error
"""
print("\n" + "=" * 70)
print("Starting optimization to find optimal IK configuration...")
print("=" * 70)
# Convert target point to shoulder frame
task_goal_relative = task_goal_global - shoulder
task_goal_shoulder = np.array([
-task_goal_relative[1],
-task_goal_relative[0],
task_goal_relative[2]
])
print(f"Task goal (global): {task_goal_global}")
print(f"Task goal (shoulder frame): {task_goal_shoulder}")
# Define optimization objective function with tighter constraint
def objective_function(q):
"""
Combined objective function: minimize (ergonomic_score + position_error_penalty)
"""
# 1. Calculate ergonomic score
ergo_score = utils.calculate_upper_limb_score_with_joint_angles(q)
# 2. Calculate position error
_, hand_shoulder = mos.forward_kinematics(q, d_uar, d_lar)
hand_global = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
position_error = np.linalg.norm(hand_global - task_goal_global)
# 3. TIGHTER position error penalty (increased from 1000.0 to 10000.0)
position_penalty_weight = 10000.0
position_penalty = position_penalty_weight * (position_error ** 2)
# 4. Combined objective
total_cost = ergo_score + position_penalty
return total_cost
# Tighter constraint function
def position_constraint(q):
"""Position constraint: wrist position should be very close to target"""
_, hand_shoulder = mos.forward_kinematics(q, d_uar, d_lar)
hand_global = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
error = np.linalg.norm(hand_global - task_goal_global)
return 0.005 - error # Constraint: error <= 5mm (tightened from 20mm)
if method == 'global':
print("Using global optimization algorithm (Differential Evolution)...")
# Use differential evolution for global search
result = differential_evolution(
objective_function,
bounds=joint_angle_bounds,
strategy='best1bin',
maxiter=2000, # Increased from 1000
popsize=20, # Increased from 15
tol=1e-9, # Tighter tolerance (from 1e-7)
mutation=(0.5, 1.0),
recombination=0.7,
seed=None,
disp=True,
polish=True,
init='latinhypercube',
atol=1e-6, # Added absolute tolerance
updating='immediate',
workers=1
)
if result.success:
target_q = result.x
print("Global optimization succeeded")
else:
print("Global optimization did not fully converge, using current best solution")
target_q = result.x
elif method == 'local':
print("Using local optimization algorithm (SLSQP)...")
# Initial guess: use middle configuration
q0 = np.array([
(joint_angle_bounds[i][0] + joint_angle_bounds[i][1]) / 2
for i in range(len(joint_angle_bounds))
])
# Define constraints
constraints = {
'type': 'ineq',
'fun': position_constraint
}
# Use SLSQP for constrained optimization
result = minimize(
objective_function,
q0,
method='SLSQP',
bounds=joint_angle_bounds,
constraints=constraints,
options={'maxiter': 1000, 'disp': True, 'ftol': 1e-12} # Tighter tolerance
)
if result.success:
target_q = result.x
print("Local optimization succeeded")
else:
print("Local optimization did not converge")
target_q = result.x
else:
raise ValueError(f"Unknown optimization method: {method}")
# Verify result
_, hand_shoulder = mos.forward_kinematics(target_q, d_uar, d_lar)
target_hand = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
target_score = utils.calculate_upper_limb_score_with_joint_angles(target_q)
position_error = np.linalg.norm(target_hand - task_goal_global)
print(f"\nOptimization result:")
print(f" Joint angles (radians): {target_q}")
print(f" Joint angles (degrees): {np.rad2deg(target_q)}")
print(f" Ergonomic score: {target_score:.4f}")
print(f" Position error: {position_error * 1000:.2f} mm")
print(f" Wrist position (global): {target_hand}")
print(f" Target position (global): {task_goal_global}")
# Check if position constraint is satisfied (tighter threshold)
if position_error > 0.01: # Changed from 0.05 to 0.01 (10mm)
print(f"Warning: Position error is large ({position_error * 1000:.2f} mm)")
print(" Possible reasons: target point outside workspace or joint limits too strict")
else:
print("Position constraint satisfied")
print("=" * 70 + "\n")
return target_q, target_hand, target_score, position_error
def find_optimal_ik_solution_hybrid(task_goal_global, shoulder, d_uar, d_lar, joint_angle_bounds):
"""
Hybrid optimization strategy with tighter constraints: global search for rough solution first, then local refinement
This is the recommended method, combining robustness of global search and precision of local optimization
"""
print("\n" + "=" * 70)
print("Using hybrid optimization strategy to find optimal IK configuration...")
print("=" * 70)
# Convert target point to shoulder frame
task_goal_relative = task_goal_global - shoulder
task_goal_shoulder = np.array([
-task_goal_relative[1],
-task_goal_relative[0],
task_goal_relative[2]
])
print(f"Task goal (global): {task_goal_global}")
print(f"Task goal (shoulder frame): {task_goal_shoulder}")
# Phase 1: Global search with very tight position constraint
print("\nPhase 1: Global search for feasible solution...")
def phase1_objective(q):
"""Phase 1: primarily optimize position error with heavy penalty"""
_, hand_shoulder = mos.forward_kinematics(q, d_uar, d_lar)
hand_global = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
position_error = np.linalg.norm(hand_global - task_goal_global)
ergo_score = utils.calculate_upper_limb_score_with_joint_angles(q)
# Phase 1 weights: MUCH stronger position error weight
return 1000.0 * position_error + 0.01 * ergo_score # Increased from 100.0 to 1000.0
result1 = differential_evolution(
phase1_objective,
bounds=joint_angle_bounds,
strategy='best1bin',
maxiter=500, # Increased from 300
popsize=15, # Increased from 10
tol=1e-8, # Tighter tolerance
seed=None,
disp=False,
polish=True, # Changed to True
workers=1
)
q_phase1 = result1.x
_, hand_phase1_shoulder = mos.forward_kinematics(q_phase1, d_uar, d_lar)
hand_phase1 = trans_shoulder2global(hand_phase1_shoulder, shoulder, arm='right')
error_phase1 = np.linalg.norm(hand_phase1 - task_goal_global)
score_phase1 = utils.calculate_upper_limb_score_with_joint_angles(q_phase1)
print(f"Phase 1 result: Position error = {error_phase1 * 1000:.2f} mm, Score = {score_phase1:.4f}")
# Phase 2: Local optimization with very tight position penalty
print("\nPhase 2: Local optimization for ergonomics...")
def phase2_objective(q):
"""Phase 2: optimize ergonomics while maintaining very tight position constraint"""
_, hand_shoulder = mos.forward_kinematics(q, d_uar, d_lar)
hand_global = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
position_error = np.linalg.norm(hand_global - task_goal_global)
ergo_score = utils.calculate_upper_limb_score_with_joint_angles(q)
# Phase 2 weights: maintain strong position constraint
if position_error < 0.005: # If error < 5mm
return ergo_score + 1000.0 * (position_error ** 2) # Increased from 50.0
else:
return ergo_score + 10000.0 * (position_error ** 2) # Increased from 500.0
result2 = minimize(
phase2_objective,
q_phase1,
method='SLSQP',
bounds=joint_angle_bounds,
options={'maxiter': 500, 'disp': False, 'ftol': 1e-12} # Increased iterations and tighter tolerance
)
target_q = result2.x
# Final verification
_, hand_shoulder = mos.forward_kinematics(target_q, d_uar, d_lar)
target_hand = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
target_score = utils.calculate_upper_limb_score_with_joint_angles(target_q)
position_error = np.linalg.norm(target_hand - task_goal_global)
print(f"\nFinal optimization result:")
print(f" Joint angles (radians): {target_q}")
print(f" Joint angles (degrees): {np.rad2deg(target_q)}")
print(f" Ergonomic score: {target_score:.4f}")
print(f" Position error: {position_error * 1000:.2f} mm")
print(f" Improvement: Score {score_phase1:.4f} -> {target_score:.4f}")
if position_error > 0.01: # Tightened from 0.05 to 0.01 (10mm)
print(f"Warning: Position error {position_error * 1000:.2f} mm exceeds threshold")
else:
print("Position constraint satisfied")
print("=" * 70 + "\n")
return target_q, target_hand, target_score, position_error
# ==================== NEW SDF-BASED METHODS ====================
class TrajectorySDFField:
"""
Signed Distance Field constructed from reference trajectory
"""
def __init__(self, reference_trajectory, sigma=0.05):
"""
Initialize SDF field
Parameters:
- reference_trajectory: reference trajectory points [N, 3]
- sigma: field smoothness parameter
"""
self.reference_trajectory = np.array(reference_trajectory)
self.sigma = sigma
self.kdtree = KDTree(self.reference_trajectory)
print(f"\n{'=' * 60}")
print("Initializing Trajectory SDF Field")
print(f"Reference trajectory points: {len(self.reference_trajectory)}")
print(f"Smoothness parameter (sigma): {self.sigma}")
print(f"{'=' * 60}\n")
def compute_sdf(self, point):
"""
Compute signed distance from point to trajectory
Parameters:
- point: query point [3,]
Returns:
- distance: signed distance value
- closest_point: closest point on trajectory
- closest_idx: index of closest point
"""
distance, closest_idx = self.kdtree.query(point)
closest_point = self.reference_trajectory[closest_idx]
return distance, closest_point, closest_idx
def compute_gradient(self, point, delta=1e-4):
"""
Compute SDF gradient at point using finite differences
Parameters:
- point: query point [3,]
- delta: finite difference step
Returns:
- gradient: SDF gradient [3,]
"""
gradient = np.zeros(3)
sdf_center, _, _ = self.compute_sdf(point)
for i in range(3):
point_plus = point.copy()
point_plus[i] += delta
sdf_plus, _, _ = self.compute_sdf(point_plus)
gradient[i] = (sdf_plus - sdf_center) / delta
return gradient
def compute_tangent_direction(self, point):
"""
Compute tangent direction of trajectory at closest point
Parameters:
- point: query point [3,]
Returns:
- tangent: tangent direction (normalized) [3,]
"""
_, _, closest_idx = self.compute_sdf(point)
# Get tangent direction from trajectory
if closest_idx == 0:
# At start, use forward difference
tangent = self.reference_trajectory[1] - self.reference_trajectory[0]
elif closest_idx == len(self.reference_trajectory) - 1:
# At end, use backward difference
tangent = self.reference_trajectory[-1] - self.reference_trajectory[-2]
else:
# In middle, use central difference
tangent = self.reference_trajectory[closest_idx + 1] - self.reference_trajectory[closest_idx - 1]
# Normalize
tangent_norm = np.linalg.norm(tangent)
if tangent_norm > 1e-6:
tangent = tangent / tangent_norm
else:
tangent = np.zeros(3)
return tangent
def generate_reference_trajectory(start_pos, goal_pos, num_points=50, trajectory_type='straight'):
"""
Generate reference trajectory
Parameters:
- start_pos: start position [3,]
- goal_pos: goal position [3,]
- num_points: number of trajectory points
- trajectory_type: 'straight' or 'curved'
Returns:
- trajectory: reference trajectory [N, 3]
"""
if trajectory_type == 'straight':
# Linear interpolation
trajectory = np.linspace(start_pos, goal_pos, num_points)
elif trajectory_type == 'curved':
# Parabolic curve (arc upward or downward)
t = np.linspace(0, 1, num_points)
# Compute middle control point (offset perpendicular to line)
direction = goal_pos - start_pos
midpoint = (start_pos + goal_pos) / 2
# Add vertical offset
offset = np.array([0, 0, np.linalg.norm(direction) * 0.2])
control_point = midpoint + offset
# Quadratic Bezier curve
trajectory = np.outer((1 - t) ** 2, start_pos) + \
np.outer(2 * (1 - t) * t, control_point) + \
np.outer(t ** 2, goal_pos)
else:
raise ValueError(f"Unknown trajectory type: {trajectory_type}")
return trajectory
def run_iterations_with_sdf_guidance(num_iterations, task_goal_global, reference_trajectory):
"""
SDF-guided trajectory planning with Adaptive Weighting Strategy
Key Innovation:
- Large SDF distance → Follow gradient (pull toward trajectory)
- Small SDF distance → Follow tangent (smooth flow along trajectory)
"""
global current_q, global_positions, shoulder, d_uar, d_lar, joint_angle_bounds
print("\n" + "=" * 70)
print("Starting SDF-guided trajectory planning with Adaptive Weights")
print("=" * 70)
# Initialize SDF field
sdf_field = TrajectorySDFField(reference_trajectory, sigma=0.05)
# ========== ADAPTIVE WEIGHT PARAMETERS ==========
# Define SDF distance thresholds for adaptive behavior
sdf_near_threshold = 0.01 # 3cm - considered "near" the trajectory
sdf_far_threshold = 0.03 # 10cm - considered "far" from trajectory
# Weight ranges for adaptive interpolation
# When FAR (large SDF): prioritize gradient to pull back to trajectory
alpha_far = 0.85 # Strong gradient following
beta_far = 0.1 # Weak tangent following
gamma_far = 0.05 # Weak goal attraction
# When NEAR (small SDF): prioritize tangent for smooth flow
alpha_near = 0.1 # Weak gradient following
beta_near = 0.8 # Strong tangent following
gamma_near = 0.1 # Weak goal attraction
# Step size parameters
step_size_base = 0.05 # Base step size
step_size_near = 0.04 # Smaller steps when near trajectory
step_size_far = 0.06 # Larger steps when far from trajectory
# Smoothness parameters
joint_velocity_weight = 0.3
joint_acceleration_weight = 0.2
use_moving_average = True
moving_avg_window = 3
# Convergence threshold
goal_threshold = 0.01 # 10mm
# Storage
trajectory = []
trajectory_hand_sdf = []
trajectory_elbow_sdf = []
score_history_sdf = []
joint_history_sdf = []
sdf_values = []
adaptive_weights_history = [] # Track weight evolution
joint_velocities = []
joint_accelerations = []
q_current = current_q.copy()
trajectory.append(q_current.copy())
# Initial state
_, hand_current_shoulder = mos.forward_kinematics(q_current, d_uar, d_lar)
hand_current_global = trans_shoulder2global(hand_current_shoulder, shoulder, arm='right')
trajectory_hand_sdf.append(hand_current_global.copy())
print(f"Initial position: {hand_current_global}")
print(f"Target position: {task_goal_global}")
print(f"Initial distance: {np.linalg.norm(task_goal_global - hand_current_global):.4f} m")
print(f"\nAdaptive Weight Strategy:")
print(
f" Near threshold (<{sdf_near_threshold * 1000:.0f}mm): α={alpha_near:.1f}, β={beta_near:.1f}, γ={gamma_near:.1f}")
print(
f" Far threshold (>{sdf_far_threshold * 1000:.0f}mm): α={alpha_far:.1f}, β={beta_far:.1f}, γ={gamma_far:.1f}")
print(f" Transition zone: smooth interpolation\n")
for step in range(num_iterations):
# 1. Compute current state
elbow_current_shoulder, hand_current_shoulder = mos.forward_kinematics(q_current, d_uar, d_lar)
hand_current_global = trans_shoulder2global(hand_current_shoulder, shoulder, arm='right')
elbow_current_global = trans_shoulder2global(elbow_current_shoulder, shoulder, arm='right')
current_score = utils.calculate_upper_limb_score_with_joint_angles(q_current)
# Record history
score_history_sdf.append(current_score)
joint_history_sdf.append(q_current.copy())
# 2. Compute SDF-related quantities
sdf_distance, closest_point, _ = sdf_field.compute_sdf(hand_current_global)
sdf_gradient = sdf_field.compute_gradient(hand_current_global, delta=1e-5)
tangent_direction = sdf_field.compute_tangent_direction(hand_current_global)
sdf_values.append(sdf_distance)
# 3. Compute goal direction
goal_direction = task_goal_global - hand_current_global
goal_distance = np.linalg.norm(goal_direction)
# Check if reached goal
if goal_distance < goal_threshold:
print(f"Reached target at iteration {step}")
break
# ========== ADAPTIVE WEIGHT COMPUTATION ==========
# Compute interpolation factor based on SDF distance
if sdf_distance <= sdf_near_threshold:
# NEAR: Use near weights
blend_factor = 0.0
elif sdf_distance >= sdf_far_threshold:
# FAR: Use far weights
blend_factor = 1.0
else:
# TRANSITION: Smooth interpolation
blend_factor = (sdf_distance - sdf_near_threshold) / (sdf_far_threshold - sdf_near_threshold)
# Interpolate weights smoothly
alpha_sdf = alpha_near + blend_factor * (alpha_far - alpha_near)
beta_tangent = beta_near + blend_factor * (beta_far - beta_near)
gamma_goal = gamma_near + blend_factor * (gamma_far - gamma_near)
# Adaptive step size based on SDF distance
step_size = step_size_near + blend_factor * (step_size_far - step_size_near)
# Store weights for analysis
adaptive_weights_history.append({
'sdf_distance': sdf_distance,
'alpha': alpha_sdf,
'beta': beta_tangent,
'gamma': gamma_goal,
'blend_factor': blend_factor,
'step_size': step_size
})
# Normalize directions
if np.linalg.norm(sdf_gradient) > 1e-6:
sdf_gradient_normalized = -sdf_gradient / np.linalg.norm(sdf_gradient)
else:
sdf_gradient_normalized = np.zeros(3)
if np.linalg.norm(tangent_direction) > 1e-6:
tangent_normalized = tangent_direction / np.linalg.norm(tangent_direction)
else:
tangent_normalized = np.zeros(3)
if goal_distance > 1e-6:
goal_direction_normalized = goal_direction / goal_distance
else:
goal_direction_normalized = np.zeros(3)
# 4. Combine directions with adaptive weights
combined_direction_task = (alpha_sdf * sdf_gradient_normalized +
beta_tangent * tangent_normalized +
gamma_goal * goal_direction_normalized)
combined_norm = np.linalg.norm(combined_direction_task)
if combined_norm > 1e-6:
combined_direction_task_normalized = combined_direction_task / combined_norm
else:
combined_direction_task_normalized = goal_direction_normalized
# 5. Adaptive step size with goal proximity consideration
progress_ratio = 1.0 - (goal_distance / np.linalg.norm(task_goal_global - trajectory_hand_sdf[0]))
adaptive_step = step_size * (1.0 - 0.4 * progress_ratio)
adaptive_step = min(adaptive_step, goal_distance * 0.35)
# 6. Task space displacement
delta_hand_global = adaptive_step * combined_direction_task_normalized
hand_target_global = hand_current_global + delta_hand_global
# 7. Convert to shoulder frame for IK
hand_target_relative = hand_target_global - shoulder
hand_target_shoulder = np.array([
-hand_target_relative[1],
-hand_target_relative[0],
hand_target_relative[2]
])
# 8. Solve IK with smoothness constraints
def ik_objective(q):
_, hand_shoulder = mos.forward_kinematics(q, d_uar, d_lar)
position_error = np.linalg.norm(hand_shoulder - hand_target_shoulder)
if len(trajectory) > 0:
q_prev = trajectory[-1]
joint_velocity = q - q_prev
velocity_penalty = joint_velocity_weight * np.sum(joint_velocity ** 2)
if len(trajectory) > 1:
q_prev_prev = trajectory[-2]
prev_velocity = q_prev - q_prev_prev
acceleration = joint_velocity - prev_velocity
acceleration_penalty = joint_acceleration_weight * np.sum(acceleration ** 2)
else:
acceleration_penalty = 0.0
return position_error + velocity_penalty + acceleration_penalty
return position_error
result = minimize(
ik_objective,
q_current,
method='SLSQP',
bounds=joint_angle_bounds,
options={'maxiter': 150, 'ftol': 1e-9}
)
q_next = result.x
# 9. Apply moving average filter
if use_moving_average and len(trajectory) >= moving_avg_window:
recent_qs = np.array(trajectory[-(moving_avg_window - 1):] + [q_next])
q_smoothed = np.mean(recent_qs, axis=0)
_, hand_check_shoulder = mos.forward_kinematics(q_smoothed, d_uar, d_lar)
check_error = np.linalg.norm(hand_check_shoulder - hand_target_shoulder)
if check_error < 0.02:
q_next = q_smoothed
# 10. Update trajectory
trajectory.append(q_next.copy())
new_elbow_shoulder, new_hand_shoulder = mos.forward_kinematics(q_next, d_uar, d_lar)
new_hand_global = trans_shoulder2global(new_hand_shoulder, shoulder, arm='right')
new_elbow_global = trans_shoulder2global(new_elbow_shoulder, shoulder, arm='right')
trajectory_hand_sdf.append(new_hand_global.copy())
trajectory_elbow_sdf.append(new_elbow_global.copy())
# Track velocities and accelerations
if len(trajectory) > 1:
velocity = q_next - trajectory[-2]
joint_velocities.append(np.linalg.norm(velocity))
if len(trajectory) > 2:
prev_velocity = trajectory[-2] - trajectory[-3]
acceleration = velocity - prev_velocity
joint_accelerations.append(np.linalg.norm(acceleration))
# 11. Print progress with adaptive weights
if step % 5 == 0 or step == num_iterations - 1:
avg_velocity = np.mean(joint_velocities[-5:]) if joint_velocities else 0
print(f"Iter {step:3d}: Score={current_score:.4f}, "
f"SDF={sdf_distance * 1000:.1f}mm, "
f"Goal={goal_distance * 1000:.1f}mm, "
f"α={alpha_sdf:.2f}, β={beta_tangent:.2f}, "
f"Step={adaptive_step:.3f}")
# 12. Update current state
q_current = q_next.copy()
# ========== POST-PROCESSING: MULTI-STAGE SMOOTHING ==========
print("\nApplying multi-stage trajectory smoothing...")
# Stage 1: Joint space smoothing
trajectory_array = np.array(trajectory)
if len(trajectory_array) > 5:
print(" Stage 1: Joint space smoothing...")
trajectory_smoothed = smooth_trajectory(
trajectory_array,
smoothing_factor=0.4,
iterations=3
)
trajectory = trajectory_smoothed.tolist()
# Recompute task space from smoothed joint space
trajectory_hand_sdf = []
for q in trajectory_smoothed:
_, hand_shoulder = mos.forward_kinematics(q, d_uar, d_lar)
hand_global = trans_shoulder2global(hand_shoulder, shoulder, arm='right')
trajectory_hand_sdf.append(hand_global)
# Stage 2: Light task space smoothing
trajectory_hand_sdf_array = np.array(trajectory_hand_sdf)
if len(trajectory_hand_sdf_array) > 5:
print(" Stage 2: Task space smoothing...")
trajectory_hand_sdf_smoothed = smooth_trajectory(
trajectory_hand_sdf_array,
smoothing_factor=0.3,
iterations=2
)
trajectory_hand_sdf = trajectory_hand_sdf_smoothed
# Final verification
q_final = trajectory[-1] if isinstance(trajectory[-1], np.ndarray) else np.array(trajectory[-1])
_, final_hand_shoulder = mos.forward_kinematics(q_final, d_uar, d_lar)
final_hand_global = trans_shoulder2global(final_hand_shoulder, shoulder, arm='right')
final_score = utils.calculate_upper_limb_score_with_joint_angles(q_final)
final_error = np.linalg.norm(final_hand_global - task_goal_global)
# Compute smoothness metrics
avg_velocity = np.mean(joint_velocities) if joint_velocities else 0
avg_acceleration = np.mean(joint_accelerations) if joint_accelerations else 0
# Analyze adaptive weight behavior
sdf_distances = [w['sdf_distance'] for w in adaptive_weights_history]
alphas = [w['alpha'] for w in adaptive_weights_history]
betas = [w['beta'] for w in adaptive_weights_history]
print(f"\nSDF-guided planning result (Adaptive Weights):")
print(f" Final joint angles (degrees): {np.rad2deg(q_final)}")
print(f" Final Score: {final_score:.4f}")
print(f" Final task error: {final_error * 1000:.2f} mm")
print(f" Trajectory points: {len(trajectory)}")
print(f" Average SDF distance: {np.mean(sdf_values) * 1000:.2f} mm")
print(f" Min/Max SDF distance: {np.min(sdf_values) * 1000:.2f} / {np.max(sdf_values) * 1000:.2f} mm")
print(f" Average joint velocity: {avg_velocity:.4f} rad/iter")
print(f" Average joint acceleration: {avg_acceleration:.4f} rad/iter²")
print(f"\nAdaptive Weight Statistics:")
print(f" α (gradient) range: [{np.min(alphas):.2f}, {np.max(alphas):.2f}]")
print(f" β (tangent) range: [{np.min(betas):.2f}, {np.max(betas):.2f}]")
print(f" Average α: {np.mean(alphas):.2f}, Average β: {np.mean(betas):.2f}")
print("=" * 70 + "\n")
return trajectory, np.array(trajectory_hand_sdf), score_history_sdf, joint_history_sdf, sdf_values
def run_iterations_with_optimized_ik(num_iterations, task_goal_global, optimization_method='hybrid'):
"""
Use optimization algorithm to solve IK, then plan trajectory in joint space
Parameters:
- num_iterations: number of iterations
- task_goal_global: task space goal point
- optimization_method: 'global', 'local', or 'hybrid' (recommended)
"""
global current_q, global_positions, trajectory_hand, trajectory_elbow, score_history, joint_history
print("\n" + "=" * 70)
print("Starting trajectory planning based on optimized IK")
print("=" * 70)
# Step 1: Optimize to solve target joint configuration
if optimization_method == 'hybrid':
target_q, target_hand_global, target_score, position_error = \
find_optimal_ik_solution_hybrid(task_goal_global, shoulder, d_uar, d_lar, joint_angle_bounds)
else:
target_q, target_hand_global, target_score, position_error = \
find_optimal_ik_solution(task_goal_global, shoulder, d_uar, d_lar, joint_angle_bounds,
method=optimization_method)
# Verify current state
_, hand_current_shoulder = mos.forward_kinematics(current_q, d_uar, d_lar)
hand_current_global = trans_shoulder2global(hand_current_shoulder, shoulder, arm='right')
current_score = utils.calculate_upper_limb_score_with_joint_angles(current_q)
print(f"Current state:")
print(f" Joint angles (degrees): {np.rad2deg(current_q)}")
print(f" Ergonomic score: {current_score:.4f}")
print(f" Wrist position: {hand_current_global}")
initial_distance = np.linalg.norm(target_hand_global - hand_current_global)
print(f"\nPlanning parameters:")
print(f" Initial distance: {initial_distance:.4f} m")
print(f" Score improvement: {current_score:.4f} -> {target_score:.4f}")
print(f" Joint space distance: {np.linalg.norm(target_q - current_q):.4f} rad")
# Step 2: CSEF-guided trajectory planning in joint space
print("\nStarting joint space trajectory planning...")
trajectory_result = run_iterations_in_joint_space(num_iterations, target_q, task_goal_global)
return trajectory_result, target_q, target_hand_global
def run_iterations_in_joint_space(num_iterations, target_q, task_goal_global=None):
"""
CSEF-guided trajectory planning in joint space with tighter convergence criteria
Parameters:
- num_iterations: number of iterations
- target_q: target joint configuration
- task_goal_global: task space goal (for visualization only)
"""
global current_q, global_positions, trajectory_hand, trajectory_elbow, score_history, joint_history
# CSEF field parameters
q_opt = np.array(optimal_q)
weights = np.array([1.0, 1.0, 1.0, 2.0])
comfort_threshold = 0.1
# Weight parameters - adjusted for tighter tracking
alpha = 0.8 # Increased goal direction weight (from 0.7)
beta = 0.2 # Decreased ergonomic gradient weight (from 0.3)
step_size = 0.08
# Helper functions to calculate SEF value and gradient
def calculate_sef(q):
ergo_score = utils.calculate_upper_limb_score_with_joint_angles(q)
return ergo_score - comfort_threshold
def calculate_sef_gradient(q, delta=1e-5):
grad = np.zeros_like(q)
sef_q = calculate_sef(q)
for i in range(len(q)):
q_plus = q.copy()
q_plus[i] += delta
sef_plus = calculate_sef(q_plus)
grad[i] = (sef_plus - sef_q) / delta
return grad
def enforce_joint_limits(q, bounds):
q_limited = np.copy(q)
for i in range(len(q)):
q_limited[i] = np.clip(q[i], bounds[i][0], bounds[i][1])
return q_limited