-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsample_trajectories.py
1672 lines (1321 loc) · 62.5 KB
/
sample_trajectories.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
"""
Sample trajectories
"""
import sys
sys.path.append('../')
from sampler.ai2thor_env import AI2ThorEnvironment, VISIBILITY_DISTANCE, round_to_factor
import random
import numpy as np
from sampler.data_utils import GCSH5Writer
import json
from tqdm import tqdm
import os
import pandas as pd
import argparse
import glob
parser = argparse.ArgumentParser(description='Sample Trajectories')
parser.add_argument(
'-display',
dest='display',
default=0,
type=int,
help='which display we are on'
)
parser.add_argument(
'-seed',
dest='seed',
default=123456,
type=int,
help='seed to use'
)
parser.add_argument(
'-out_path',
dest='out_path',
type=str,
help='Base path to use.'
)
parser.add_argument(
'-nex',
dest='nex',
default=10000,
type=int,
help='Num examples to generate'
)
args = parser.parse_args()
with open(os.path.join(os.path.dirname(os.path.join(__file__)), '..', 'data', 'size_deltas.json'), 'r') as f:
SIZE_DELTAS = json.load(f)
with open(os.path.join(os.path.dirname(os.path.join(__file__)), '..', 'data', 'knob_to_burner.json'), 'r') as f:
KNOB_TO_BURNER = json.load(f)
def rotation_angle_to_object(object_info, point):
"""
Given a point, compute the best rotation angle to object
the coordinate system is a bit weird
90 degrees
^ +x
180 degrees ------> +z 0 degrees
|
|
V
270 degrees
:param object_info:
:param point: [x,y,z]
:return:
"""
object_coords = object_info['axisAlignedBoundingBox']['center'] if 'axisAlignedBoundingBox' in object_info else \
object_info['position']
x_delta = object_coords['x'] - point['x']
z_delta = object_coords['z'] - point['z']
r = np.sqrt(np.square(x_delta) + np.square(z_delta))
angle = np.arctan2(x_delta / r, z_delta / r) * 180 / np.pi
if angle < 0:
angle += 360
if angle > 360.0:
angle -= 360.0
return angle
def horizon_angle_to_object(object_info, point):
"""
^ - angle
/
me reference pt
\
V + angle
we're facing the object already
:param object_info:
:param point: [x,y,z]
:return:
"""
object_coords = object_info['axisAlignedBoundingBox']['center'] if 'axisAlignedBoundingBox' in object_info else \
object_info['position']
my_height = 1.575
y_delta = object_coords['y'] - my_height
xz_dist = np.sqrt(np.square(object_coords['x'] - point['x']) + np.square(object_coords['z'] - point['z']))
r = np.sqrt(np.square(xz_dist) + np.square(y_delta))
angle = np.arctan2(-y_delta / r, xz_dist / r) * 180 / np.pi
if angle < 0:
angle += 360
if angle > 360.0:
angle -= 360.0
return angle
def clip_angle_to_nearest(true_angle, possible_angles=(0, 90, 180, 270)):
"""
Clips angle to the nearest one
:param true_angle: float
:param possible_angles: other angles
:return:
"""
pa = np.array(possible_angles)
dist = np.abs(pa - true_angle)
dist = np.minimum(dist, 360.0 - dist)
return int(pa[np.argmin(dist)])
def get_object_zxwh_and_expansion(target_object, openable_object_pad_distance=0.0, object_pad_distance=0.0):
"""
Compute object bounding box coordinates, with possible expansion
:param target_object:
:param openable_object_pad_distance: pad openable objects that are currently closed this much EXTRA
:param object_pad_distance: pad all objects this much
:return:
"""
object_zxwh = np.array([target_object['axisAlignedBoundingBox']['center']['z'],
target_object['axisAlignedBoundingBox']['center']['x'],
target_object['axisAlignedBoundingBox']['size']['z'],
target_object['axisAlignedBoundingBox']['size']['x'],
])
object_zxwh2 = np.copy(object_zxwh)
# Increase size a bit accordingly
if target_object['openable'] and not target_object['isOpen']:
sd = SIZE_DELTAS['object_name_to_size_delta'].get(target_object['name'],
SIZE_DELTAS['object_type_to_size_delta'].get(
target_object['objectType'], [0.0, 0.0]))
# Rotation matrix
theta = target_object['rotation']['y'] * np.pi / 180
R = np.array([
[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]
])
sd = np.abs(R @ np.array(sd)) + openable_object_pad_distance # Agent radius is tehcnically 0.2 (I dealt with that elsewhere) but 0.4 seems
# needed for some annoying objects
object_zxwh2[2:] += sd
object_zxwh2[2:] += object_pad_distance # agent radius is 0.2
return object_zxwh, object_zxwh2
def zxwh_to_zzxx(bbox_xywh):
sizes = bbox_xywh[..., 2:] / 2.0
return np.concatenate((bbox_xywh[..., :2] - sizes, bbox_xywh[..., :2] + sizes), -1)
def interval_pos(test_x, x0, x1):
"""
In 1D space:
x0 x1
############## ################## ##############
# ---- position 0 position + position
:param test_x:
:param x0:
:param x1:
:return:
"""
assert x1 >= x0
if test_x < x0:
return test_x - x0
if test_x > x1:
return test_x - x1
return 0.0
def distance_to_object_manifold(agent_pos, target_object, openable_object_pad_distance=0.0, object_pad_distance=0.0):
"""
Distance from the agent to the object manifold. If the object is openable we'll pretend it's open and hallucinate accordingly
For simplicitly we'll just use 2d distances
The agent is a circle around its position with radius 0.2
:param agent_pos:
:param object:
:return:
"""
if target_object['objectType'] == 'Floor':
return 0.0
# Just return the expanded box.
_, object_zxwh = get_object_zxwh_and_expansion(target_object,
openable_object_pad_distance=openable_object_pad_distance,
object_pad_distance=object_pad_distance)
# Compute distance to the manifold. negative distance if INSIDE.
# Check if we're inside
object_zzxx = zxwh_to_zzxx(object_zxwh)
z_dist = interval_pos(agent_pos['z'], object_zzxx[0], object_zzxx[2])
x_dist = interval_pos(agent_pos['x'], object_zzxx[1], object_zzxx[3])
if z_dist == 0.0 and x_dist == 0.0:
# Inside the boundary?
return -0.01
r = np.sqrt(np.square(z_dist) + np.square(x_dist))
return r
# Subactions. they aren't DOING anything yet just planning ======================================
def path_to_object(env: AI2ThorEnvironment, target_object, angle_noise=10, dist_noise=0.1, dist_to_obj_penalty=2.0,
faces_good_side_penalty=10.0):
"""
Go to the object (starting from the Agent's location)
:param env:
:param target_object:
:param angle_noise:
:param dist_noise: standard deviation for noise we'll add to shortest pathfinder
:param dist_to_obj_penalty:
:return:
"""
reachable_pts = env.currently_reachable_points
start_location = env.get_agent_location()
receptacle = None
if target_object['openable'] and not target_object['isOpen']:
receptacle = target_object
for pr in target_object['parentReceptacles']:
mr = env.get_object_by_id(pr)
if mr['openable'] and not mr['isOpen']:
receptacle = mr
# Find all pts
reachable_points_touching_object = []
for pt in reachable_pts:
ctr_dist = env.position_dist(pt, target_object['position'])
pt_dist = distance_to_object_manifold(pt, target_object, object_pad_distance=0.0)
if receptacle is not None:
# I really don't know what to set this to safely
oopd = random.random()
pt_dist_to_receptacle = distance_to_object_manifold(pt, receptacle,
openable_object_pad_distance=oopd,
object_pad_distance=0.2)
if pt_dist_to_receptacle < 0.0:
continue
vd = 1.49
if target_object['objectType'] in ('Fridge',):
vd += 0.5
if (ctr_dist > vd) and (pt_dist > vd):
continue
# Might need a minimum distance away from the object
# Get angle
ra = rotation_angle_to_object(target_object, pt) + float(np.random.uniform(-angle_noise, angle_noise))
ra = clip_angle_to_nearest(ra)
ha = horizon_angle_to_object(target_object, pt) + float(np.random.uniform(-angle_noise, angle_noise))
ha = clip_angle_to_nearest(ha, [-30, 0, 30, 60])
pt2 = {k: v for k, v in pt.items()}
pt2['horizon'] = ha
pt2['rotation'] = ra
pt2['dist'] = pt_dist
pt2['dist_to_me'] = env.position_dist(start_location, pt)
# Check if we're facing the good side of the object for an object like fridge
pt2['faces_good_side'] = True
if receptacle is not None:
obj, obj_expanded = get_object_zxwh_and_expansion(receptacle,
openable_object_pad_distance=0.2,
object_pad_distance=0.2)
object_zzxx = zxwh_to_zzxx(obj_expanded)
# Figure out what quadrant we're in
z_dist = interval_pos(pt2['z'], object_zzxx[0], object_zzxx[2])
x_dist = interval_pos(pt2['x'], object_zzxx[1], object_zzxx[3])
# Z expansion, X expansion.
size_delta_z, size_delta_x = (obj_expanded - obj)[2:]
if (abs(z_dist) > 0) and (abs(x_dist) > 0):
pt2['faces_good_side'] = False
else:
# If X expansion is a lot longer, we want Z cordinates to be 0 dist and X coordinates to be + dist
if size_delta_x > (size_delta_z + 0.25):
pt2['faces_good_side'] = (z_dist == 0.0)
if size_delta_z > (size_delta_x + 0.25):
pt2['faces_good_side'] = (x_dist == 0.0)
reachable_points_touching_object.append(pt2)
if len(reachable_points_touching_object) == 0:
raise ValueError("No points touching object {}".format(target_object['objectId']))
dists = np.array(
[(pt2['dist'], pt2['dist_to_me'], float(pt2['faces_good_side'])) for pt2 in reachable_points_touching_object])
# 1 standard dist -> 0.25
joint_dist = dist_to_obj_penalty * dists[:, 0] + dists[:, 1] + np.random.randn(
dists.shape[0]) * dist_noise + faces_good_side_penalty * (1.0 - dists[:, 2])
pt = reachable_points_touching_object[int(np.argmin(joint_dist))]
res = env.get_fancy_shortest_path(start_location, pt)
if res is None:
raise ValueError("Shortest path failed")
return res
def objects_equal(obj1, obj2):
def _bbox_equal(b1, b2, tolerance=4e-2):
b1_np = np.array(b1['cornerPoints'])
b2_np = np.array(b2['cornerPoints'])
return np.abs(b1_np - b2_np).max() < tolerance
def _xyz_equal(b1, b2, tolerance=4e-2, mod360=False):
p1_np = np.array([b1[k2] for k2 in 'xyz'])
p2_np = np.array([b2[k2] for k2 in 'xyz'])
dist = np.abs(p1_np - p2_np)
if mod360:
dist = np.minimum(dist, 360.0 - dist)
return dist.max() < tolerance
if obj1 == obj2:
return True
if obj1.keys() != obj2.keys():
print("Keys differ", flush=True)
return False
keys = sorted(obj1.keys())
for k in keys:
if obj1[k] == obj2[k]:
continue
# Float distance
if k == 'position':
if not _xyz_equal(obj1[k], obj2[k]):
# print(f"{k} - {obj1[k]} {obj2[k]}")
return False
elif k == 'rotation':
if not _xyz_equal(obj1[k], obj2[k], mod360=True, tolerance=1.0):
# print(f"{k} - {obj1[k]} {obj2[k]}")
return False
elif k == 'axisAlignedBoundingBox':
for k3 in ['center', 'size']:
if not _xyz_equal(obj1[k][k3], obj2[k][k3]):
# print(f"AxisAlignedBoundingBox -> {k3} ({obj1['objectId']})")
return False
elif k in ('isMoving', 'distance', 'visible'):
continue
else:
# print(k, flush=True)
return False
return True
def randomize_toggle_states(env: AI2ThorEnvironment, random_prob=0.9):
"""
Randomize toggle states. unfortunately this does this uniformly for the entire scene
:param env:
:param random_prob:
:return:
"""
possible_object_attributes = {
# 'openable': ('isOpen', (True, False)),
'toggleable': ('isToggled', (True, False)),
'breakable': ('isBroken', (True, False)),
'canFillWithLiquid': ('isFilledWithLiquid', (True, False)),
'dirtyable': ('isDirty', (True, False)),
'cookable': ('isCooked', (True, False)),
'sliceable': ('isSliced', (True, False)),
'canBeUsedUp': ('isUsedUp', (True, False)),
}
possible_actions_to_vals = {}
for obj in env.all_objects():
overlapping_properties = [(k, v[0], v[1]) for k, v in possible_object_attributes.items() if obj.get(k, False)]
for k, v0, v1 in overlapping_properties:
possible_actions_to_vals[(obj['objectType'], k, v0)] = v1
for k, v in possible_actions_to_vals.items():
if random.random() > random_prob:
new_state = random.choice(v)
env.controller.step(action='SetObjectStates', SetObjectStates={
'objectType': k[0],
'stateChange': k[1],
k[2]: new_state,
})
def break_all(env: AI2ThorEnvironment, object_type):
env.controller.step(action='SetObjectStates', SetObjectStates={
'objectType': object_type,
'stateChange': 'breakable',
'isBroken': True,
})
def fill_all_objects_with_liquid(env: AI2ThorEnvironment):
empty_objects = set()
empty_object_types = set()
for obj in env.all_objects():
if obj['canFillWithLiquid'] and not obj['isFilledWithLiquid']:
empty_objects.add(obj['objectId'])
empty_object_types.add(obj['objectType'])
#
# for ot in empty_object_types:
# env.controller.step(action='SetObjectStates', SetObjectStates={
# 'objectType': ot,
# 'stateChange': 'canFillWithLiquid',
# 'isFilledWithLiquid': True,
# })
for obj in empty_objects:
liquid = random.choice(['coffee', 'wine', 'water'])
env.controller.step({'action': 'FillObjectWithLiquid', 'objectId': obj, 'fillLiquid': liquid,
'forceVisible': True})
def close_everything(env: AI2ThorEnvironment):
object_types_open = set()
for obj in env.all_objects():
if obj['openable'] and obj['isOpen']:
object_types_open.add(obj['objectType'])
for x in object_types_open:
env.controller.step(action='SetObjectStates', SetObjectStates={
'objectType': x,
'stateChange': 'openable',
'isOpen': False,
})
def retract_hand(env: AI2ThorEnvironment):
"""
Move the hand back so it's not super visible. this will be reset.
:param env:
:return:
"""
oih = env.object_in_hand()
if oih is None:
return
# current_rotation = clip_angle_to_nearest(env.get_agent_location()['rotation'])
env.controller.step(action='MoveHandDown', moveMagnitude=0.2)
env.controller.step(action='MoveHandBack', moveMagnitude=0.1)
def group_knobs_and_burners(env: AI2ThorEnvironment):
"""
We'll group together stoves and knobs that go together
:param env:
:return:
"""
stoveburners = {x['name']: x for x in env.all_objects_with_properties({'objectType': 'StoveBurner'})}
knobs = {x['name']: x for x in env.all_objects_with_properties({'objectType': 'StoveKnob'})}
knobs_and_burners = []
for k, v in knobs.items():
if k not in KNOB_TO_BURNER:
print(f"{k} not found???")
continue
bn = KNOB_TO_BURNER[k]
if bn in stoveburners:
knobs_and_burners.append((v, stoveburners[bn]))
else:
print("Oh no burner {} not found?".format(bn), flush=True)
return knobs_and_burners
class RecordingEnv(object):
"""
Record
# this class needs to be able to record the path:
# 1. actions
# 2. images
# 3. bounding boxes, including object attrs
"""
def __init__(self, env: AI2ThorEnvironment, text='', main_object_ids=(), ):
self.env = env
# Things we're recording
# "inputs"
self.meta_info = None
self.frames = []
self.object_id_to_states = {} # objid -> {t} -> obj. Default prior is that states don't change
self.bboxes = []
self.agent_states = []
# "outputs"
self.output_actions = []
self.output_action_results = []
self.alias_object_id_to_old_object_id = {}
self.meta_info = {
'scene_name': self.env.scene_name,
'text': text,
'main_object_ids': main_object_ids,
'width': env._start_player_screen_width,
'height': env._start_player_screen_height,
}
self.log_observations()
def __len__(self):
return len(self.frames)
@property
def new_items(self):
return {k: v[len(self) - 1] for k, v in self.object_id_to_states.items() if (len(self) - 1) in v}
def step(self, action_dict, action_can_fail=False, record_failure=True):
"""
:param action_dict:
:param action_can_fail: Whether we're OK with the action failing
:return:
"""
res = self.env.step(action_dict)
if (not self.env.last_action_success) and (not action_can_fail):
raise ValueError("Action {} failed, {}".format(action_dict, self.env.last_event.metadata['errorMessage']))
if (not record_failure) and (not self.env.last_action_success):
return False
self.output_actions.append(action_dict)
self.output_action_results.append({
'action_success': self.env.last_action_success,
'action_err_msg': self.env.last_event.metadata['errorMessage'],
})
self.log_observations()
return self.env.last_action_success
def log_observations(self):
t = len(self.frames)
# frames
self.frames.append(self.env.last_event.frame)
# Update object states
for obj in self.env.all_objects():
# We must have added a new object
if obj['objectId'] not in self.object_id_to_states:
# if (t > 0) and (not 'Slice' in obj['name']):
# import ipdb
# ipdb.set_trace()
self.object_id_to_states[obj['objectId']] = {t: obj}
else:
last_t = sorted(self.object_id_to_states[obj['objectId']].keys())[-1]
# Object changed
if not objects_equal(self.object_id_to_states[obj['objectId']][last_t], obj):
self.object_id_to_states[obj['objectId']][t] = obj
# Bounding boxes
self.bboxes.append({k: v.tolist() for k, v in self.env.last_event.instance_detections2D.items()})
self.agent_states.append(self.env.get_agent_location())
def save(self, fn='temp.h5'):
writer = GCSH5Writer(fn)
# Get object
object_ids = sorted(self.object_id_to_states)
object_id_to_ind = {id: i for i, id in enumerate(object_ids)}
# No need to store identities
for k, v in sorted(self.alias_object_id_to_old_object_id.items()):
if k == v:
self.alias_object_id_to_old_object_id.pop(k)
writer.create_dataset('alias_object_id_to_old_object_id',
data=np.string_(json.dumps(self.alias_object_id_to_old_object_id).encode('utf-8')))
writer.create_dataset('object_ids', np.string_(object_ids))
writer.create_dataset('frames', data=np.stack(self.frames), compression='gzip', compression_opts=9)
# Get bounding box -> ind
# [ind, box_x1, box_y1, box_x2, box_y2]
bbox_group = writer.create_group('bboxes')
for t, bbox_dict_t in enumerate(self.bboxes):
# NOTE: This filters out some objects.
bbox_list = [[object_id_to_ind[k]] + v for k, v in bbox_dict_t.items() if k in object_id_to_ind]
bbox_array = np.array(sorted(bbox_list, key=lambda x: x[0]), dtype=np.uint16) ###### oh no I was saving this as uint8 earlier and things were clipping. UGH
bbox_group.create_dataset(f'{t}', data=bbox_array)
# Position / Rotation / center / size
xyz_coords = writer.create_group('pos3d')
for k in sorted(self.object_id_to_states):
xyz_coords_k = xyz_coords.create_group(k)
for t in sorted(self.object_id_to_states[k]):
coords_to_use = [self.object_id_to_states[k][t].pop('position'),
self.object_id_to_states[k][t].pop('rotation'),
self.object_id_to_states[k][t]['axisAlignedBoundingBox'].pop('center'),
self.object_id_to_states[k][t]['axisAlignedBoundingBox'].pop('size')]
xyz_coords_kt_np = np.array([[p[k2] for k2 in 'xyz'] for p in coords_to_use], dtype=np.float32)
xyz_coords_k.create_dataset(f'{t}', data=xyz_coords_kt_np)
self.object_id_to_states[k][t].pop('axisAlignedBoundingBox')
self.object_id_to_states[k][t].pop('objectOrientedBoundingBox')
# print("{} total object things".format(sum([len(v) for v in self.object_id_to_states.values()])))
writer.create_dataset('object_id_to_states', data=np.string_(
json.dumps(self.object_id_to_states).encode('utf-8'),
))
writer.create_dataset('agent_states', data=np.array([[s[k] for k in ['x', 'y', 'z', 'rotation', 'horizon']]
for s in self.agent_states], dtype=np.float32))
writer.create_dataset('output_actions', data=np.string_(json.dumps(self.output_actions).encode('utf-8')))
writer.create_dataset('output_action_results',
data=np.string_(json.dumps(self.output_action_results).encode('utf-8')))
writer.create_dataset('meta_info', data=np.string_(json.dumps(self.meta_info).encode('utf-8')))
writer.close()
#############################################################################
def inch_closer_path(renv: RecordingEnv, target_receptacle):
"""
Assuming the receptacle is open, scoot a bit closer. Keep existing horizon and rotation.
:param env:
:param target_receptacle:
:return:
"""
env.recompute_reachable()
reachable_pts = renv.env.currently_reachable_points
start_location = renv.env.get_agent_location()
start_location['horizon'] = clip_angle_to_nearest(start_location['horizon'], [-30, 0, 30, 60])
start_location['rotation'] = clip_angle_to_nearest(start_location['rotation'])
start_dist = renv.env.position_dist(start_location, target_receptacle['position'])
closer_pts = []
for pt in reachable_pts:
pt_dist = renv.env.position_dist(pt, target_receptacle['position'])
if pt_dist >= (start_dist - 0.05):
continue
pt2 = {k: v for k, v in pt.items()}
pt2['dist'] = pt_dist
pt2['dist_to_me'] = renv.env.position_dist(start_location, pt)
pt2['horizon'] = start_location['horizon']
if pt2['horizon'] != clip_angle_to_nearest(horizon_angle_to_object(target_receptacle, pt), [-30, 0, 30, 60]):
continue
pt2['rotation'] = start_location['rotation']
if pt2['rotation'] != clip_angle_to_nearest(rotation_angle_to_object(target_receptacle, pt)):
continue
closer_pts.append(pt2)
if len(closer_pts) == 0:
return []
dists = np.array([(pt2['dist'], pt2['dist_to_me']) for pt2 in closer_pts])
score = 20.0 * dists[:, 0] + dists[:, 1] + 0.5 * np.random.randn(dists.shape[0])
pt = closer_pts[int(np.argmin(score))]
forward_path = env.get_fancy_shortest_path(start_location, pt, fix_multi_moves=False, num_inner_max=4)
if forward_path is None:
return []
forward_path = [x for x in forward_path if not x['action'].startswith('Look')]
if any([x['action'] in ('JumpAhead', 'RotateLeft', 'RotateRight') for x in forward_path]):
forward_path = []
# Now we can have a reverse path too
antonyms = {'MoveAhead': 'MoveBack', 'MoveLeft': 'MoveRight', 'MoveRight': 'MoveLeft'}
reverse_path = []
for p in forward_path[::-1]:
reverse_path.append({
'action': antonyms[p['action']],
'_start_state_key': p['_end_state_key'],
'_end_state_key': p['_start_state_key'],
})
for i, p in enumerate(forward_path):
good = renv.step(p, action_can_fail=True, record_failure=False)
if not good:
my_key = env.get_key(env.get_agent_location())
key_matches = np.array([rp['_start_state_key'] == my_key for rp in reverse_path])
if not np.any(key_matches):
reverse_path = []
else:
ki = int(np.where(key_matches)[0][0])
reverse_path = reverse_path[ki:]
break
return reverse_path
def pickup_object(renv: RecordingEnv, target_object_id, navigate=True,
action_can_fail=False, force_visible=False):
"""
:param renv:
:param target_object_id:
:param navigate: Whether to navigate there
:param action_can_fail: Whether the final pickup action can fail
:return:
"""
target_object = renv.env.get_object_by_id(target_object_id)
if target_object is None:
raise ValueError("No target object")
# Check if any objects are held, drop if so
held_object = renv.env.object_in_hand()
if held_object is not None:
raise ValueError("held object??")
must_open = False
if target_object['parentReceptacles'] is not None and len(target_object['parentReceptacles']) > 0:
pr = env.get_object_by_id(target_object['parentReceptacles'][0])
if pr['openable'] and not pr['isOpen']:
must_open = True
else:
pr = None
if navigate:
d2op = (random.random()*0.5 - 0.25) if must_open else random.random()
fgsp = 10.0 if random.random() > 0.5 else 0.0
for p in path_to_object(renv.env, target_object=target_object, dist_to_obj_penalty=d2op, faces_good_side_penalty=fgsp):
renv.step(p, action_can_fail=False)
# Inch closer
if must_open and (pr is not None):
renv.step({'action': 'OpenObject', 'objectId': pr['objectId']}, action_can_fail=False)
reverse_path = inch_closer_path(renv, pr)
else:
pr = None
reverse_path = []
renv.step({'action': 'PickupObject', 'objectId': target_object_id, 'forceVisible': force_visible}, action_can_fail=action_can_fail)
for p in reverse_path:
good = renv.step(p, action_can_fail=True, record_failure=False)
if not good:
break
if (pr is not None) and (pr['openable'] and not pr['isOpen']):
renv.step({'action': 'CloseObject', 'objectId': pr['objectId']}, action_can_fail=False)
return True
def put_object_in_receptacle(renv: RecordingEnv, target_receptacle_id, navigate=True, close_receptacle=True,
action_can_fail=False):
"""
:param renv:
:param target_receptacle:
:return:
"""
target_receptacle = renv.env.get_object_by_id(target_receptacle_id)
# Sanity check we're holding an object
held_object = renv.env.object_in_hand()
if held_object is None:
if action_can_fail:
return False
raise ValueError("No held object")
if target_receptacle is None:
raise ValueError("No receptacle?")
# Don't go too close to the object if it's open
must_open = target_receptacle['openable'] and not target_receptacle['isOpen']
d2op = (random.random() * 0.5 - 0.25) if must_open else random.random()
if navigate:
fgsp = 10.0 if random.random() > 0.5 else 0.0
path = path_to_object(renv.env, target_object=target_receptacle, dist_to_obj_penalty=d2op, faces_good_side_penalty=fgsp)
for p in path:
renv.step(p, action_can_fail=False)
# Open if needed
if must_open:
renv.step({'action': 'OpenObject', 'objectId': target_receptacle_id}, action_can_fail=False)
reverse_path = inch_closer_path(renv, renv.env.get_object_by_id(target_receptacle_id))
else:
reverse_path = []
# Move hand back
if not env.get_object_by_id(held_object['objectId'])['visible']:
retract_hand(renv.env)
succeeds = renv.step(
{'action': 'PutObject', 'objectId': held_object['objectId'], 'receptacleObjectId': target_receptacle_id},
action_can_fail=action_can_fail)
for p in reverse_path:
good = renv.step(p, action_can_fail=True, record_failure=False)
if not good:
break
if succeeds and close_receptacle and target_receptacle['openable']:
succeeds = renv.step({'action': 'CloseObject', 'objectId': target_receptacle_id}, action_can_fail=False)
return succeeds
def pour_out_liquid(renv: RecordingEnv, action_can_fail=True):
"""
Assuming we're holding stuff -- pour it out
:param renv:
:param action_can_fail:
:return:
"""
held_obj = renv.env.object_in_hand()
if held_obj is None:
if not action_can_fail:
raise ValueError("NO held obj")
return False
# Option 1: Rotate 180 degrees upside down
if random.random() < 0.5:
renv.step({'action': 'RotateHand', 'x': 180}, action_can_fail=action_can_fail)
renv.step({'action': 'RotateHand', 'x': 0}, action_can_fail=action_can_fail)
else:
if held_obj['isFilledWithLiquid']:
renv.step({'action': 'EmptyLiquidFromObject', 'objectId': held_obj['objectId']},
action_can_fail=action_can_fail)
return True
#########################
def use_water_source_to_fill_or_clean_held(renv: RecordingEnv, water_source,
skip_turning_on_water=False,
empty_afterwards=False,
action_can_fail=True):
"""
Start with a held object. Go to the water source and put it in. Water will magically clean and fill everything in it
:param renv:
:param water_source: watersource
:param skip_turning_on_water: Whether to fake out the model and NOT turn on the water
:param empty_afterwards: Empty the held object afterwards
:param action_can_fail:
:return:
"""
if water_source['objectType'] != 'Faucet':
raise ValueError("needs 2 be faucet")
sink_basins = sorted(env.all_objects_with_properties({'receptacle': True, 'objectType': 'SinkBasin'}),
key=lambda obj: env.position_dist(
water_source['position'], obj['position'], ignore_y=True)
)
sink_basin = sink_basins[0]
held_obj = renv.env.object_in_hand()
if held_obj is None:
if not action_can_fail:
raise ValueError("No held obj")
return False
s_a = put_object_in_receptacle(renv, sink_basin['objectId'], navigate=True, action_can_fail=False)
if not skip_turning_on_water:
# Hack 1. clean everything under water
for obj_id in env.get_object_by_id(sink_basin['objectId'])['receptacleObjectIds']:
obj = env.get_object_by_id(obj_id)
if obj['isDirty']:
env.controller.step({'action': 'CleanObject', 'objectId': obj['objectId'], 'forceVisible': True})
if not obj['isFilledWithLiquid']:
env.controller.step({'action': 'FillObjectWithLiquid', 'objectId': obj['objectId'],
'fillLiquid': 'water',
'forceVisible': True})
inch_closer_path(renv, water_source)
# Now turn on the water
s_a &= renv.step({'action': 'ToggleObjectOn', 'objectId': water_source['objectId']},
action_can_fail=action_can_fail)
if random.random() < 0.8:
s_a &= renv.step({'action': 'ToggleObjectOff', 'objectId': water_source['objectId']},
action_can_fail=action_can_fail)
s_b = pickup_object(renv, held_obj['objectId'], navigate=False, action_can_fail=action_can_fail)
if empty_afterwards:
s_b &= pour_out_liquid(renv, action_can_fail=action_can_fail)
return s_a and s_b
def slice_held_object(renv: RecordingEnv, anchor_pt=None, action_can_fail=False):
"""
Slice the held object. but for this we need to put it DOWN first.
:param renv:
:param anchor_pt: put held object down somewhere NEAR here
:return:
"""
all_cutting_surfaces = renv.env.all_objects_with_properties({'objectType': 'CounterTop'})
if len(all_cutting_surfaces) == 0:
raise ValueError("No cutting surfaces")
held_obj = env.object_in_hand()
if held_obj is None:
raise ValueError("No held obj")
anchor_pt_loc = anchor_pt if anchor_pt is not None else renv.env.get_agent_location()
all_cutting_surfaces = sorted(all_cutting_surfaces,
key=lambda x: renv.env.position_dist(x['position'],
anchor_pt_loc) + np.random.randn() * 0.25 + len(
x['receptacleObjectIds']))
surface = all_cutting_surfaces[0]
put_object_in_receptacle(renv, surface['objectId'], navigate=True, action_can_fail=False)
ok = renv.step({'action': 'SliceObject', 'objectId': held_obj['objectId']}, action_can_fail=action_can_fail)
# Get constituent objects
slices = sorted([x for x in env.visible_objects() if x['objectId'].startswith(held_obj['objectId'])],
key=lambda x: x['name'])
random.shuffle(slices)
if len(slices) == 0:
raise ValueError("no slices?")
renv.alias_object_id_to_old_object_id[slices[0]['objectId']] = held_obj['objectId']
ok &= pickup_object(renv, slices[0]['objectId'], navigate=False, action_can_fail=action_can_fail)
return ok
# 1. Put object X in receptacle Y, wait, take it out.
env = AI2ThorEnvironment(
make_agents_visible=True,
object_open_speed=0.05,
restrict_to_initially_reachable_points=True,
render_class_image=True,
render_object_image=True,
player_screen_height=384,
player_screen_width=640,
quality="Very High",
x_display="0.{}".format(args.display),
fov=90.0,
)
def _weighted_choice(weights):
"""
Choose based on weights
:param weights: they don't necessarily need to sum to 1
:return:
"""
weights_np = np.array(weights)
assert np.all(weights_np >= 0)
return int(np.random.choice(weights_np.size, p=weights_np / weights_np.sum()))
def _sample_bigger_receptacle_than_me(object_x, all_receptacles, min_ratio=2.0):
"""
Sample a random object that's usually bigger than obj
:param obj:
:param receptacles: List of receptacles
:return:
"""
def _size3d(o):
xyz = np.array([o['axisAlignedBoundingBox']['size'][k] for k in 'xyz'])
return np.sqrt(xyz[0] * xyz[2])
x_size3d = _size3d(object_x)+0.001
r_weights = [(0.05 if _size3d(r)/x_size3d < min_ratio else 1.0) for r in all_receptacles]
receptacle_y = all_receptacles[_weighted_choice(r_weights)]
object_is_bigger = x_size3d > _size3d(receptacle_y)
return receptacle_y, object_is_bigger
######################################
def _place_held_object_in_receptacle():