-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrw_planner.py
1636 lines (1238 loc) · 56.8 KB
/
rw_planner.py
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
import timeit
import subprocess
import IPython
import time
import rospy
import numpy as np
import math as m
import matplotlib.pyplot as plt
from pyquaternion import Quaternion
from shapely.geometry import MultiPoint, Polygon, Point, LineString
from dm_control import suite
from dm_control import viewer
from scipy.spatial import ConvexHull
from matplotlib.path import Path
from PIL import Image
from std_msgs.msg import String
from std_msgs.msg import Float32MultiArray
from resources import *
def plan_grasp_callback(data):
return data.data
def initialize_physics_env(p_object_states, p_object_names):
global env
global physics
global N_QPOS
global obj_names
global num_objs
global obj_colors
global plot_width
obj_names = p_object_names
num_objs = len(p_object_states)
# Compose new object xml
obj_names_str = ""
count_objs = 0
for obj_n in obj_names:
obj_names_str = obj_names_str+obj_n
if count_objs < len(obj_names)-1:
obj_names_str = obj_names_str+','
count_objs += 1
subprocess.call(['python3', 'compose_obj_xml.py', '--obj_list', obj_names_str])
# Copy full system xml
pusher_xml_path = suite.__path__[0]+"/pusher_clutter.xml"
subprocess.call(["cp", "./mog_xmls/target.xml", pusher_xml_path])
env = suite.load(domain_name="pusher", task_name="easy")
physics = env.physics
# Set physics simulation parameters
physics.model.opt.timestep = SIM_TIMESTEP
physics.model.opt.integrator = SIM_INTEGRATOR
init_state = env.physics.get_state()
N_QPOS = physics.data.qpos[:].shape[0]
physics.set_start_state(init_state[0:N_QPOS])
def set_state(x_0):
# Reset physics and set initial state
global env
with env.physics.reset_context():
env.physics.set_state(x_0)
env.physics.step()
return None
def visualize_grasp(x_0, cand_grasp):
reset_viewer_policy_params(x_0, cand_grasp)
viewer.launch(env, policy=policy)
def policy(timestep):
global env
return np.array([-1., 1.])
def reset_viewer_policy_params(x_0, grasp_cand):
global env
global init_robot_pos
global final_robot_pos
global count_single_action
env.physics.model.opt.timestep = SIM_TIMESTEP
env.physics.model.opt.integrator = SIM_INTEGRATOR
env.physics.start_state = x_0[0:N_QPOS].copy()
def prepare_rw_state(plan_mj_state, plan_mj_obj_name):
full_obj_state = []
for obj_ind in range(len(plan_mj_state)):
obj_theta = plan_mj_state[obj_ind][-1]
obj_quat = Quaternion(axis=[0,0,1], angle=obj_theta).elements
obj_pos = plan_mj_state[obj_ind][0:2].copy()
full_obj_state.append([obj_pos, list(obj_quat)])
# Update object states
with env.physics.reset_context():
for obj_ind in range(len(plan_mj_state)):
obj_name = plan_mj_obj_name[obj_ind]+"_joint"
obj_state = full_obj_state[obj_ind].copy()
env.physics.named.data.qpos[obj_name][0:2] = obj_state[0].copy()
env.physics.named.data.qpos[obj_name][3:7] = obj_state[1].copy()
env.physics.step()
init_state = env.physics.get_state()
return init_state, full_obj_state
def rw_grasp_planner(init_state, full_obj_state):
init_state, full_obj_state = prepare_rw_state()
set_state(init_state)
min_stable_distance, _ = compute_min_stable_distance()
print ('Generating candidate grasps ....')
cand_grasp_params, obj_state = gen_cand_grasps(init_state, plot_all_grasps=False, plot_path=sim_scene_path)
cand_grasps = cand_grasp_params[0]
std_indices = np.linspace(start=0, stop=len(cand_grasps), num=len(cand_grasps), endpoint=False)
gp_params = [obj_state, std_indices]
gp_start_time = timeit.default_timer()
gp_grasp, gp_results, sorted_indices = grasp_planner(cand_grasp_params, gp_params, full_obj_state, min_stable_distance, method="Area")
gp_time = timeit.default_timer() - gp_start_time
return None
def compute_min_stable_distance():
obj_pts, obj_lines, obj_edge_lines = get_props()
# For each object, compute stability type and corresponding distance
all_min_dists = []
for obj_ind in range(num_objs):
_, dists = compute_stable_configs_and_dists(obj_pts[obj_ind], obj_lines[obj_ind], obj_edge_lines[obj_ind])
min_dist = np.min(dists)
all_min_dists.append(min_dist)
min_mog_dist = np.sum(np.array(all_min_dists))
indiv_min = np.min(all_min_dists)
return min_mog_dist, indiv_min
def compute_stable_configs_and_dists(obj_pts, obj_lines, obj_edge_lines):
stable_configs = []
stable_dists = []
# Two parallel lines belonging to the object.
num_lines = len(obj_lines)
for line_a_ind in range(num_lines):
for line_b_ind in range(line_a_ind+1, num_lines):
line_a = obj_lines[line_a_ind]
line_b = obj_lines[line_b_ind]
parallel_lines = check_parallel_lines(line_a, line_b)
if parallel_lines:
stable_config_type = 'l_l'
stable_config_dist = LineString(line_a).distance(LineString(line_b))
stable_configs.append(stable_config_type)
stable_dists.append(stable_config_dist)
num_edge_points = len(obj_pts)
# Edge point and corresponding pependicular line.
for edge_pt_ind in range(num_edge_points):
for line_ind in range(num_lines):
# Use the full line instead of the intersection line only.
line = obj_lines[line_ind]
edge_pt = obj_pts[edge_pt_ind]
edge_lines = obj_edge_lines[edge_pt_ind]
line_edge_point = check_line_edge_point_pepend(line, edge_pt, edge_lines)
if line_edge_point:
stable_config_type = 'l_p'
stable_config_dist = LineString(line).distance(Point(edge_pt))
stable_configs.append(stable_config_type)
stable_dists.append(stable_config_dist)
# Two edge points that are pependicularly connected.
for edge_pt_ind_1 in range(num_edge_points):
for edge_pt_ind_2 in range(edge_pt_ind_1+1, num_edge_points):
edge_pt_1 = obj_pts[edge_pt_ind_1]
edge_pt_2 = obj_pts[edge_pt_ind_2]
edge_pt_1_lines = obj_edge_lines[edge_pt_ind_1]
edge_pt_2_lines = obj_edge_lines[edge_pt_ind_2]
pts = [edge_pt_1, edge_pt_2]
lines = [edge_pt_1_lines, edge_pt_2_lines]
edge_pepend = check_edge_pepend_connection(pts, lines)
if edge_pepend:
stable_config_type = 'p_p'
stable_config_dist = np.linalg.norm(np.array(edge_pt_2) - np.array(edge_pt_1))
stable_configs.append(stable_config_type)
stable_dists.append(stable_config_dist)
return stable_configs, stable_dists
def get_props():
obj_state, pt_list = get_object_state()
all_obj_pts = []
all_obj_lines = []
all_obj_edge_lines = []
for obj_ind in range(num_objs):
hull_object = ConvexHull(obj_state[obj_ind])
hull_path = Path(hull_object.points[hull_object.vertices])
obj_polygon = Polygon(hull_path.to_polygons()[0])
obj_polygon_coords = wrap_points(obj_polygon.boundary.xy)[0:-1]
obj_lines = generate_lines_from_pts(obj_polygon_coords)
obj_edge_pts = obj_polygon_coords
obj_edge_lines = []
for edge_pt in obj_edge_pts:
edge_lines = extract_edge_lines(edge_pt, obj_lines)
obj_edge_lines.append(edge_lines)
all_obj_pts.append(obj_edge_pts)
all_obj_lines.append(obj_lines)
all_obj_edge_lines.append(obj_edge_lines)
return all_obj_pts, all_obj_lines, all_obj_edge_lines
def extract_edge_lines(edge_pt, obj_lines):
edge_lines = []
SMALL_EPS = 1e-6
for line in obj_lines:
p_l_dist = LineString(line).distance(Point(edge_pt))
if p_l_dist < SMALL_EPS:
edge_lines.append(line)
return edge_lines
def check_valid_init_state():
# No obj_obj collisions and no plate_obj collisions.
obj_obj_collisions = False
obj_state, pt_list = get_object_state()
hull = ConvexHull(np.array(pt_list))
obj_polygons = []
obj_hulls = []
for obj_ind in range(num_objs):
hull_object = ConvexHull(obj_state[obj_ind])
hull_path = Path(hull_object.points[hull_object.vertices])
obj_polygon = Polygon(hull_path.to_polygons()[0])
obj_polygons.append(obj_polygon)
obj_hulls.append(hull_object)
obj_obj_collisions = False
for obj_ind_1 in range(num_objs):
for obj_ind_2 in range(obj_ind_1+1, num_objs):
if obj_polygons[obj_ind_1].intersects(obj_polygons[obj_ind_2]):
obj_obj_collisions = True
break
return obj_obj_collisions
def simulate_grasp_gp(sim_grasp_input, print_flag=False):
""" Check a candidate grasp for success, failure, or maybe
"""
swept_polygon = sim_grasp_input[0]
obj_pts = sim_grasp_input[1]
plate_polygons = sim_grasp_input[2]
object_int_polygons = sim_grasp_input[3]
object_polygons = sim_grasp_input[4]
# Intersection area condition
int_area_cond = int_area_condition_check(object_int_polygons)
# Diameter function check
diameter_cond = diameter_condition_check(plate_polygons, object_int_polygons)
if int_area_cond == False or diameter_cond == False:
grasp_success = 'False'
else:
grasp_success = 'Maybe'
failure_conds = [int_area_cond, diameter_cond]
return grasp_success, failure_conds
def diameter_condition_check(plate_polygons, object_int_polygons):
current_d = compute_current_distance_func(plate_polygons, object_int_polygons)
if min_stable_distance <= current_d:
diameter_cond = True
else:
diameter_cond = False
return diameter_cond
def compute_current_distance_func(plate_polygons, object_int_polygons):
l_plate_polygon = plate_polygons[0]
r_plate_polygon = plate_polygons[1]
lp_distances = []
for obj_ind in range(num_objs):
lp_dist = l_plate_polygon.distance(object_int_polygons[obj_ind])
lp_distances.append(lp_dist)
rp_distances = []
for obj_ind in range(num_objs):
rp_dist = r_plate_polygon.distance(object_int_polygons[obj_ind])
rp_distances.append(rp_dist)
min_dist_to_left_plate = np.min(lp_distances)
min_dist_to_right_plate = np.min(rp_distances)
# Distance between left plate polygon and right plate polygon
plate_plate_init_dist = l_plate_polygon.distance(r_plate_polygon)
total_free_space = min_dist_to_left_plate + min_dist_to_right_plate
dist_func_ini = plate_plate_init_dist - total_free_space
return dist_func_ini
def find_common_lines(lines_a, lines_b):
num_lines_a = len(lines_a)
num_lines_b = len(lines_b)
common_lines = []
SMALL_EPS = 1e-6
for line_a_ind in range(num_lines_a):
for line_b_ind in range(line_a_ind, num_lines_b):
line_a = lines_a[line_a_ind]
line_b = lines_b[line_b_ind]
if np.linalg.norm(line_a - line_b) < SMALL_EPS:
common_lines.append(line_a)
return common_lines
def grasp_planner(cand_grasp_params, gp_params, obj_params, h_fmin, method='Area'):
plan_grasp = True
# Check if the grasp can even happen:
if h_fmin > GRIPPER_STROKE - GRIPPER_WIDTH*2:
# Gripper can't hold all objects in a grasp
plan_grasp = False
if plan_grasp:
# General grasp params
cand_grasps = cand_grasp_params[0]
cand_grasp_areas = cand_grasp_params[1]
# Params to check failure
cand_grasp_swept_polygon = cand_grasp_params[2]
cand_grasp_plate_polygons = cand_grasp_params[3]
cand_grasp_obj_int_polygons = cand_grasp_params[4]
if len(cand_grasps) > 0:
sorted_cand_grasps, sorted_indices = sort_all_grasps(cand_grasps, cand_grasp_areas, gp_params, sort_method=method)
else:
sorted_cand_grasps = []
sorted_indices = []
# Compute centroid of objects in current state
obj_state = gp_params[0].copy()
obj_centroids = []
obj_polygons = []
all_sim_obj_pts = []
for obj_ind in range(num_objs):
obj_pts = obj_state[obj_ind].copy()
obj_centroids.append(np.mean(obj_pts, axis=0))
hull_object = ConvexHull(obj_pts)
hull_path = Path(hull_object.points[hull_object.vertices])
obj_polygon = Polygon(hull_path.to_polygons()[0])
obj_polygons.append(obj_polygon)
all_sim_obj_pts.append(obj_pts)
count_used_samples = 0
grasp_success = 'False'
count_full_sim = 0
for grasp_index in range(len(cand_grasps)):
count_used_samples += 1
cand_grasp = sorted_cand_grasps[grasp_index]
swept_polygon = cand_grasp_swept_polygon[int(sorted_indices[grasp_index])]
plate_polygons = cand_grasp_plate_polygons[int(sorted_indices[grasp_index])]
obj_int_polygons = cand_grasp_obj_int_polygons[int(sorted_indices[grasp_index])]
sim_grasp_input = []
sim_grasp_input.append(swept_polygon)
sim_grasp_input.append(all_sim_obj_pts)
sim_grasp_input.append(plate_polygons)
sim_grasp_input.append(obj_int_polygons)
sim_grasp_input.append(obj_polygons)
grasp_success_gp, failure_conds = simulate_grasp_gp(sim_grasp_input)
if grasp_success_gp == 'Maybe':
init_grasp_state, final_grasp_state, grasp_success_mj, grasp_X = simulate_full_grasp(obj_params, cand_grasp)
if grasp_success_mj == 'True':
grasp_success = 'True'
#visualize_grasp(init_grasp_state, cand_grasp)
else:
grasp_success = 'False'
else:
grasp_X = []
if grasp_success == 'True':
break
if grasp_success != 'True':
break
if len(cand_grasps) > 0:
results = [grasp_success, count_used_samples, int(sorted_indices[grasp_index]), grasp_X]
else:
results = [grasp_success, count_used_samples, 0, []]
sorted_indices = []
cand_grasp = []
else:
cand_grasp = []
results = ['False', 0, 0, []]
sorted_indices = []
return cand_grasp, results, sorted_indices
def evaluate_grasps_exp(cand_grasp_params, gp_params, obj_params, data_path):
# General grasp params
cand_grasps = cand_grasp_params[0]
cand_grasp_areas = cand_grasp_params[1]
# Params to check failure
cand_grasp_swept_polygon = cand_grasp_params[2]
cand_grasp_plate_polygons = cand_grasp_params[3]
cand_grasp_obj_int_polygons = cand_grasp_params[4]
# Compute centroid of objects in current state
obj_state = gp_params[0]
obj_centroids = []
obj_polygons = []
all_obj_pts = []
for obj_num in range(num_objs):
# Object points
obj_pts = obj_state[obj_num]
all_obj_pts.append(obj_pts)
# Centroids
obj_centroid = np.mean(obj_pts, axis=0)
obj_centroids.append(obj_centroid)
# Polygons
hull_object = ConvexHull(obj_pts)
hull_path = Path(hull_object.points[hull_object.vertices])
obj_polygon = Polygon(hull_path.to_polygons()[0])
obj_polygons.append(obj_polygon)
mj_success = []
gp_success = []
gp_conditions = []
init_grasp_states = []
count_c1_examples = 0
count_c2_examples = 0
MAX_COND_EXAMPLES = 3
for grasp_index in range(len(cand_grasps)):
cand_grasp = cand_grasps[grasp_index]
swept_polygon = cand_grasp_swept_polygon[grasp_index]
plate_polygons = cand_grasp_plate_polygons[grasp_index]
obj_int_polygons = cand_grasp_obj_int_polygons[grasp_index]
sim_grasp_input = []
sim_grasp_input.append(swept_polygon)
sim_grasp_input.append(all_obj_pts)
sim_grasp_input.append(plate_polygons)
sim_grasp_input.append(obj_int_polygons)
sim_grasp_input.append(obj_polygons)
grasp_success_gp, failure_conds = simulate_grasp_gp(sim_grasp_input)
gp_success.append(grasp_success_gp)
gp_conditions.append(failure_conds)
init_grasp_state, final_grasp_state, grasp_success_mj, grasp_X = simulate_full_grasp(obj_params, cand_grasp)
init_grasp_states.append(init_grasp_state)
# False Negative
if grasp_success_mj == 'True' and grasp_success_gp == 'False':
fig_path = data_path+'false_negatives/sample_{}/'.format(grasp_index)
subprocess.call(['rm', '-rf', fig_path])
subprocess.call(['mkdir', '-p', fig_path])
capture_state_sequence_frames(grasp_X, fig_path)
if grasp_success_mj == 'True':
fig_path = data_path+'positives/sample_{}/'.format(grasp_index)
subprocess.call(['rm', '-rf', fig_path])
subprocess.call(['mkdir', '-p', fig_path])
capture_state_sequence_frames(grasp_X, fig_path)
if count_c1_examples < MAX_COND_EXAMPLES and failure_conds[0] == False:
fig_path = data_path+'c1_negatives/sample_{}/'.format(grasp_index)
subprocess.call(['rm', '-rf', fig_path])
subprocess.call(['mkdir', '-p', fig_path])
capture_state_sequence_frames(grasp_X, fig_path)
count_c1_examples += 1
if count_c2_examples < MAX_COND_EXAMPLES and failure_conds[1] == False:
fig_path = data_path+'c2_negatives/sample_{}/'.format(grasp_index)
subprocess.call(['rm', '-rf', fig_path])
subprocess.call(['mkdir', '-p', fig_path])
capture_state_sequence_frames(grasp_X, fig_path)
count_c2_examples += 1
mj_success.append(grasp_success_mj)
return mj_success, gp_success, gp_conditions, init_grasp_states
def capture_state_sequence_frames(grasp_X, fig_path):
# 25 fps (We need 25*3 evenly spaced frames)
total_num_frames = grasp_X.shape[0]
total_desired_frames = 25*3.
frame_spacing = int(total_num_frames/total_desired_frames)
frame_indices = np.linspace(start=0, stop=total_num_frames, num=total_desired_frames, endpoint=False)
frame_count = 0
for frame_ind in frame_indices:
x_frame = grasp_X[int(frame_ind)].copy()
frame_path = fig_path+'frame-{}.png'.format(frame_count)
capture_grasp_state(x_frame, frame_path)
frame_count += 1
return None
def sort_all_grasps(cand_grasps, cand_grasp_areas, gp_params, sort_method='Area'):
obj_state = gp_params[0].copy()
SORT_WEIGHT = 1.0
# Rank grasp samples
grasp_ind = np.linspace(start=0, stop=len(cand_grasps), num=len(cand_grasps), endpoint=False)
# Sort criteria is the
grasp_area_sums = np.sum(cand_grasp_areas, axis=1)
sort_criteria_area = grasp_area_sums/np.max(grasp_area_sums)
if sort_method == 'Area':
# Use Area
sorted_indices = [x for _, x in sorted(zip(sort_criteria_area, grasp_ind), reverse=True)]
elif sort_method == 'Random':
# Randomize grasp indices
sorted_indices = np.random.permutation(len(cand_grasps))
else:
print ('Unknown sort method')
new_cand_grasps = []
for g_ind in range(len(cand_grasps)):
new_cand_grasps.append(cand_grasps[int(sorted_indices[g_ind])])
return new_cand_grasps, sorted_indices
def check_edge_pepend_connection(pts, lines, debug_flag=False):
if debug_flag:
IPython.embed()
pepend_connection = False
# Each line meeting at point of interest must have an acute angle
# w.r.t the conecting line.
edge_lines_a = lines[0]
edge_lines_b = lines[1]
edge_pt_a = pts[0]
edge_pt_b = pts[1]
edge_a_line_vec_1, edge_a_line_vec_2 = find_edge_line_vectors(edge_lines_a, edge_pt_a)
edge_b_line_vec_1, edge_b_line_vec_2 = find_edge_line_vectors(edge_lines_b, edge_pt_b)
# Checking edge a
con_line_vec_a = np.array(edge_pt_a) - np.array(edge_pt_b)
angle_a_1 = find_angle_btw_vectors(con_line_vec_a, edge_a_line_vec_1)
angle_a_2 = find_angle_btw_vectors(con_line_vec_a, edge_a_line_vec_2)
edge_a_check = False
if check_acute(angle_a_1, angle_a_2):
# Edge A is fine
edge_a_check = True
# Checking edge b
con_line_vec_b = np.array(edge_pt_b) - np.array(edge_pt_a)
angle_b_1 = find_angle_btw_vectors(con_line_vec_b, edge_b_line_vec_1)
angle_b_2 = find_angle_btw_vectors(con_line_vec_b, edge_b_line_vec_2)
edge_b_check = False
if check_acute(angle_b_1, angle_b_2):
# Edge A is fine
edge_b_check = True
if edge_a_check and edge_b_check:
pepend_connection = True
return pepend_connection
def check_line_edge_point_pepend(line, edge_pt, edge_lines, debug_flag=False):
if debug_flag:
IPython.embed()
line_edge_point_pepend = False
# First find distance between line and point
pepend_dist = LineString(line).distance(Point(edge_pt))
SMALL_EPS = 1e-3
if pepend_dist < SMALL_EPS:
# Point lies on line
line_edge_point_pepend = False
else:
# There is a chance
# Find normal to line of interest
line_vec = np.array(line[1]) - np.array(line[0])
line_unit_vec = line_vec/np.linalg.norm(line_vec)
pepend_vec_1, pepend_vec_2 = find_2d_pepend_vec(line_unit_vec)
line_pt_pepend_vec_1 = pepend_dist*pepend_vec_1
line_pt_pepend_vec_2 = pepend_dist*pepend_vec_2
# Fine normal pointing towards point of interest
# Start from point of interest, add normal vec*dist. If we arrive at line,
# then that is the wrong normal vector.
pt_on_line_1 = line_pt_pepend_vec_1 + np.array(edge_pt)
pt_on_line_2 = line_pt_pepend_vec_2 + np.array(edge_pt)
d_1 = LineString(line).distance(Point(pt_on_line_1))
d_2 = LineString(line).distance(Point(pt_on_line_2))
valid_case = False
if d_1 < SMALL_EPS:
# This is the wrong normal vector index
line_pt_pepend_vec = line_pt_pepend_vec_2.copy()
valid_case = True
elif d_2 < SMALL_EPS:
# This is the wrong normal vector index
line_pt_pepend_vec = line_pt_pepend_vec_1.copy()
valid_case = True
else:
# Closet point on line from edge_pt is not along a pependicular line.
line_edge_point_pepend = False
if valid_case:
edge_line_vec_1, edge_line_vec_2 = find_edge_line_vectors(edge_lines, edge_pt)
############################################################
angle_1 = find_angle_btw_vectors(line_pt_pepend_vec, edge_line_vec_1)
angle_2 = find_angle_btw_vectors(line_pt_pepend_vec, edge_line_vec_2)
if check_acute(angle_1, angle_2):
# Both angles are acute.
# Point line case holds true.
line_edge_point_pepend = True
#print ('Line edge point pepend case found!')
# # Debugging
# line_xs = [line[0][0], line[1][0]]
# line_ys = [line[0][1], line[1][1]]
# edge_line_1 = edge_lines[0]
# edge_line_2 = edge_lines[1]
# edge_line_1_xs = [edge_line_1[0][0], edge_line_1[1][0]]
# edge_line_1_ys = [edge_line_1[0][1], edge_line_1[1][1]]
# edge_line_2_xs = [edge_line_2[0][0], edge_line_2[1][0]]
# edge_line_2_ys = [edge_line_2[0][1], edge_line_2[1][1]]
# plt.cla()
# plt.plot(line_xs, line_ys, 'k--')
# plt.plot(edge_line_1_xs, edge_line_1_ys, 'b--')
# plt.plot(edge_line_2_xs, edge_line_2_ys, 'g--')
# plt.scatter(edge_pt[0], edge_pt[1], color='b')
# plt.scatter(pt_on_line_1[0], pt_on_line_1[1], color='r')
# plt.scatter(pt_on_line_2[0], pt_on_line_2[1], color='g')
# plt.savefig('test_point_line_1.png')
return line_edge_point_pepend
def check_acute(angle_1, angle_2):
SMALL_EPS = 1e-6
if (angle_1 - m.pi/2.) < SMALL_EPS and (angle_2 - m.pi/2.) < SMALL_EPS:
# Both angles are acute.
# Point line case holds true.
return True
else:
return False
def find_edge_line_vectors(edge_lines, edge_pt):
# There are two edge lines corresponding to one edge point
# Edge line vector should point to the edge point
SMALL_EPS = 1e-6
h_0 = np.linalg.norm(np.array(edge_pt) - np.array(edge_lines[0][0]))
h_1 = np.linalg.norm(np.array(edge_pt) - np.array(edge_lines[0][1]))
if h_0 < SMALL_EPS:
edge_line_vec_1 = np.array(edge_lines[0][0]) - np.array(edge_lines[0][1])
elif h_1 < SMALL_EPS:
edge_line_vec_1 = np.array(edge_lines[0][1]) - np.array(edge_lines[0][0])
else:
# There are only two possibilities
#print ('Case not found - debug')
edge_line_vec_1 = None
z_0 = np.linalg.norm(np.array(edge_pt) - np.array(edge_lines[1][0]))
z_1 = np.linalg.norm(np.array(edge_pt) - np.array(edge_lines[1][1]))
if z_0 < SMALL_EPS:
edge_line_vec_2 = np.array(edge_lines[1][0]) - np.array(edge_lines[1][1])
elif z_1 < SMALL_EPS:
edge_line_vec_2 = np.array(edge_lines[1][1]) - np.array(edge_lines[1][0])
else:
# There are only two possibilities
#print ('Case not found - debug')
edge_line_vec_2 = None
return edge_line_vec_1, edge_line_vec_2
def find_angle_btw_vectors(vec_1, vec_2):
# Return only positive numbers
unit_vec_1 = vec_1/np.linalg.norm(vec_1)
unit_vec_2 = vec_2/np.linalg.norm(vec_2)
# Dot product of vectors
dot_prod = np.dot(unit_vec_1, unit_vec_2)
SMALL_EPS = 1e-6
# Avoid math error at 1 and -1
if abs(dot_prod - 1.0) < SMALL_EPS:
angle_btw = 0.
elif abs (dot_prod + 1.0) < SMALL_EPS:
angle_btw = m.pi
else:
#angle_btw = m.acos(dot_prod)
angle_btw = np.arccos(dot_prod)
return angle_btw
def find_2d_pepend_vec(unit_vec) :
pepend_vec = np.empty_like(unit_vec)
pepend_vec[0] = -unit_vec[1]
pepend_vec[1] = unit_vec[0]
return pepend_vec, -pepend_vec
def check_parallel_lines(line_a, line_b):
line_a_vec = np.array(np.array(line_a[1]) - np.array(line_a[0]))
line_b_vec = np.array(np.array(line_b[1]) - np.array(line_b[0]))
line_a_unit_vec = line_a_vec/np.linalg.norm(line_a_vec)
line_b_unit_vec = line_b_vec/np.linalg.norm(line_b_vec)
dot_val = np.dot(line_a_unit_vec, line_b_unit_vec)
SMALL_EPS = 1e-4
parallel = False
if abs(abs(dot_val) - 1) < SMALL_EPS:
parallel = True
return parallel
def simulate_full_grasp(obj_params, cand_grasp):
g1_pos, g2_pos, g1_quat, g2_quat = get_gripper_params(cand_grasp)
with env.physics.reset_context():
for obj_ind in range(num_objs):
obj_state = obj_params[obj_ind].copy()
obj_name = obj_names[obj_ind]+"_joint"
env.physics.named.data.qpos[obj_name][0:2] = obj_state[0].copy()
env.physics.named.data.qpos[obj_name][3:7] = obj_state[1].copy()
env.physics.named.model.body_quat['left_plate'] = g1_quat.copy()
env.physics.named.model.body_quat['right_plate'] = g2_quat.copy()
env.physics.named.model.body_pos['left_plate'][0:2] = g1_pos.copy()
env.physics.named.model.body_pos['right_plate'][0:2] = g2_pos.copy()
env.physics.step()
init_grasp_state = env.physics.get_state()
final_grasp_state, grasp_success, grasp_X = simulate_grasp(init_grasp_state, cand_grasp)
return init_grasp_state, final_grasp_state, grasp_success, grasp_X
def save_state_fig(dum_state, fig_name='fig.png'):
set_state(dum_state)
image_data = env.physics.render(height=480, width=640, camera_id=0)
img = Image.fromarray(image_data, 'RGB')
img.save(fig_name)
return None
def capture_grasp_state(grasp_state, fig_path='./'):
set_state(grasp_state)
image_data = env.physics.render(height=480, width=640, camera_id=0)
img = Image.fromarray(image_data, 'RGB')
img.save(fig_path)
return None
def check_grasp_success(final_state, min_stable_dist, indiv_min, grasp_cand):
# Uses the diameter function to check grasp success
lpy = final_state[0]
rpy = final_state[1]
curr_grip_dist = GRIPPER_STROKE - (abs(lpy) + abs(rpy))
dist_btw_plates = curr_grip_dist - 2*GRIPPER_WIDTH
eps_val = np.min(indiv_min)/2.
stable_low = min_stable_dist - eps_val
stable_high = min_stable_dist + eps_val
# # Or via intersection area
robot_final_coords = get_final_robot_coords(grasp_cand, dist_btw_plates)
grippers_hull = ConvexHull(robot_final_coords[-1])
grippers_hull_path = Path(grippers_hull.points[grippers_hull.vertices])
sp_final_polygon = Polygon(grippers_hull_path.to_polygons()[0])
if final_state != []:
set_state(final_state)
final_obj_state, pt_list = get_object_state()
obj_final_polygons = []
for obj_ind in range(num_objs):
hull_object = ConvexHull(final_obj_state[obj_ind])
hull_path = Path(hull_object.points[hull_object.vertices])
obj_polygon = Polygon(hull_path.to_polygons()[0])
obj_final_polygons.append(obj_polygon)
obj_int_polygons = []
obj_contains = []
for obj_ind in range(num_objs):
obj_final = obj_final_polygons[obj_ind]
obj_fin_int = sp_final_polygon.intersection(obj_final)
obj_contains.append(sp_final_polygon.contains(obj_final))
obj_int_polygons.append(obj_fin_int)
int_area_cond = int_area_condition_check(obj_int_polygons, obj_contains=obj_contains)
if dist_btw_plates > stable_low and int_area_cond:
grasp_success = 'True'
else:
grasp_success = 'False'
return grasp_success
def simulate_grasp(x_0, grasp_cand):
global env
set_state(x_0)
min_stable_dist, indiv_min = compute_min_stable_distance()
grasp_time = 3 # seconds
num_grasp_steps = int(grasp_time/SIM_TIMESTEP)
X = np.zeros((num_grasp_steps, x_0.shape[0]))
for step in range(num_grasp_steps):
env.physics.data.ctrl[:] = np.array([-1., 1.])
env.physics.step()
X[step] = env.physics.get_state()
final_state = env.physics.get_state()
grasp_success = check_grasp_success(final_state, min_stable_dist, indiv_min, grasp_cand)
return final_state, grasp_success, X
def gen_cand_grasps(surr_obj_polygons, init_state=[], plot_all_grasps=False, plot_path='./'):
# State is the position of all points that make up an object.
set_state(init_state)
obj_state, pt_list = get_object_state()
hull = ConvexHull(np.array(pt_list))
hulls = []
obj_polygons = []
hulls.append(hull)
for obj_ind in range(num_objs):
hull_object = ConvexHull(obj_state[obj_ind])
hull_path = Path(hull_object.points[hull_object.vertices])
hulls.append(hull_object)
obj_polygon = Polygon(hull_path.to_polygons()[0])
obj_polygons.append(obj_polygon)
uniform_position_samples = generate_uniform_samples(np.array(pt_list), hulls, plot_path=plot_path)
# Generate grasp candidates
grasp_candidates = []
orientations_per_point = np.linspace(start=0, stop=m.pi, num=N_orns, endpoint=False)
for pt in uniform_position_samples:
for orn in orientations_per_point:
grasp_cand = [pt, orn]
grasp_candidates.append(grasp_cand)
#IPython.embed()
#centroid_pos =
# obj_centroids = []
# for obj_ind in range(len(obj_state)):
# obj_pts = obj_state[obj_ind].copy()
# obj_centroid = np.mean(obj_pts, axis=0)
# obj_centroids.append(obj_centroid)
#
# group_centroid = np.mean(obj_centroids, axis=0)
# #print ('Group centroid is', group_centroid)
#
# grasp_candidates = []
# for pt in [group_centroid]:
# for orn in orientations_per_point:
# grasp_cand = [pt, orn]
# grasp_candidates.append(grasp_cand)
valid_grasps = []
valid_grasp_hulls = []
valid_grasp_areas = []
valid_grasp_swept_polygons = []
valid_grasp_plate_polygons = []
valid_grasp_obj_int_polygons = []
for grasp_cand in grasp_candidates:
# Compute intersecting area between gripper swept area and objects.
A_objs, grasp_hulls, collision, obj_int_polygons, s_poly, plate_polygons = compute_grasp_params(grasp_cand, obj_polygons)
surr_collision = check_surrounding_obj_collision(plate_polygons, surr_obj_polygons)
# Check swept polygon with surrounding object collision
swept_surround_collision = check_swept_surround_collision(s_poly, surr_obj_polygons)
# Eliminate grasps in collision
if collision == False and surr_collision == False and swept_surround_collision == False:
valid_grasps.append(grasp_cand)
valid_grasp_hulls.append(grasp_hulls)
valid_grasp_areas.append(A_objs)
valid_grasp_swept_polygons.append(s_poly)
valid_grasp_plate_polygons.append(plate_polygons)
valid_grasp_obj_int_polygons.append(obj_int_polygons)
# Plot the grasps
if plot_all_grasps:
fig_path = plot_path+'grasp_figs/'
subprocess.call(['mkdir', '-p', fig_path])
for grasp in range(len(valid_grasps)):
grasp_hull = valid_grasp_hulls[grasp]
hull_left_plate = grasp_hull[0]
hull_right_plate = grasp_hull[1]
hull_swept_area = grasp_hull[2]
# all_hulls = [hull_object_1, hull_object_2, hull_left_plate,
# hull_right_plate, hull_swept_area]
all_hulls = hulls[1:].copy()
all_hulls.append(hull_left_plate)
all_hulls.append(hull_right_plate)
all_hulls.append(hull_swept_area)
plot_grasp(valid_grasps[grasp], all_hulls, grasp_index=grasp, p_path=fig_path)
valid_grasp_params = [valid_grasps, valid_grasp_areas, valid_grasp_swept_polygons,
valid_grasp_plate_polygons, valid_grasp_obj_int_polygons]
return valid_grasp_params, obj_state
def check_swept_surround_collision(s_poly, surr_obj_polygons):
#IPython.embed()
swept_surround_collision = False
for surr_poly in surr_obj_polygons:
#print ('Going through the list! ******************')
if s_poly.intersects(surr_poly) or s_poly.contains(surr_poly):
swept_surround_collision = True
#print ('No mate ++++++++++++++++++++++')