-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.py
executable file
·1435 lines (1229 loc) · 51.6 KB
/
env.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
''' Batched Room-to-Room navigation environment '''
import paths
from torch.autograd import Variable
import torch
from utils import load_datasets, load_nav_graphs, structured_map, decode_base64, k_best_indices, try_cuda, spatial_feature_from_bbox
from collections import namedtuple, defaultdict
import itertools
import pickle
import os.path
import functools
import networkx as nx
import random
import json
import math
import numpy as np
import csv
import pdb
import MatterSim
import os
import sys
import copy
from refer360_utils import load_vectors
from refer360_utils import MODEL2PREFIX
from refer360_utils import MODEL2FEATURE_DIM
from refer360_utils import get_object_dictionaries
import base64
from pprint import pprint
file_path = os.path.dirname(__file__)
module_path = os.path.abspath(os.path.join(file_path))
sys.path.append(module_path)
module_path = os.path.abspath(os.path.join(file_path, '..', '..', 'build'))
sys.path.append(module_path)
csv.field_size_limit(sys.maxsize)
class CachedMatterSim(MatterSim.Simulator):
def __init__(self,
raw=False,
sim_cache=None):
super(CachedMatterSim, self).__init__()
self.raw = raw
self.sim_cache = sim_cache
self.img = None
def cachedNewEpisode(self, scanId, viewpointId, heading, elevation, img):
if self.raw:
idx = self.sim_cache['viewpoint2idx'][viewpointId]
self.img = self.sim_cache['panos'][idx, :, :, :]
else:
self.img = None
return self.newEpisode(scanId, viewpointId, heading, elevation)
def cachedGetState(self):
state = self.getState()
state.img = self.img
# Not needed for panorama action space
# FOLLOWER_MODEL_ACTIONS = ['left', 'right', 'up', 'down', 'forward', '<end>', '<start>', '<ignore>']
#
# LEFT_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('left')
# RIGHT_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('right')
# UP_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('up')
# DOWN_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('down')
# FORWARD_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('forward')
# END_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('<end>')
# START_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('<start>')
# IGNORE_ACTION_INDEX = FOLLOWER_MODEL_ACTIONS.index('<ignore>')
# FOLLOWER_ENV_ACTIONS = [
# (0,-1, 0), # left
# (0, 1, 0), # right
# (0, 0, 1), # up
# (0, 0,-1), # down
# (1, 0, 0), # forward
# (0, 0, 0), # <end>
# (0, 0, 0), # <start>
# (0, 0, 0) # <ignore>
# ]
# assert len(FOLLOWER_MODEL_ACTIONS) == len(FOLLOWER_ENV_ACTIONS)
angle_inc = np.pi / 6.
def _build_action_embedding(adj_loc_list, features,
reading=False):
n_skip = 1 + int(reading)
feature_dim = 0
for feature in features:
feature_dim += feature.shape[-1]
embedding = np.zeros((len(adj_loc_list), feature_dim + 128), np.float32)
# 'STOP' adj == current location thus rel_{heading,elevation}=0
embedding[0, 0:32] = np.sin(0)
embedding[0, 32:64] = np.cos(0)
embedding[0, 64:96] = np.sin(0)
embedding[0, 96:] = np.cos(0)
for a, adj_dict in enumerate(adj_loc_list):
if a < n_skip:
# the embedding for the first action ('stop') is left as zero
continue
fd = 0
for feature in features:
fd_new = feature.shape[-1]
embedding[a, fd:fd+fd_new] = feature[adj_dict['absViewIndex']]
fd += fd_new
# embedding[a, :feature_dim] = features[adj_dict['absViewIndex']]
loc_embedding = embedding[a, feature_dim:]
rel_heading = adj_dict['rel_heading']
rel_elevation = adj_dict['rel_elevation']
loc_embedding[0:32] = np.sin(rel_heading)
loc_embedding[32:64] = np.cos(rel_heading)
loc_embedding[64:96] = np.sin(rel_elevation)
loc_embedding[96:] = np.cos(rel_elevation)
return embedding
def build_viewpoint_loc_embedding(viewIndex):
'''
Position embedding:
heading 64D + elevation 64D
1) heading: [sin(heading) for _ in range(1, 33)] +
[cos(heading) for _ in range(1, 33)]
2) elevation: [sin(elevation) for _ in range(1, 33)] +
[cos(elevation) for _ in range(1, 33)]
'''
embedding = np.zeros((36, 128), np.float32)
for absViewIndex in range(36):
relViewIndex = (absViewIndex - viewIndex) % 12 + (absViewIndex // 12) * 12
rel_heading = (relViewIndex % 12) * angle_inc
rel_elevation = (relViewIndex // 12 - 1) * angle_inc
embedding[absViewIndex, 0:32] = np.sin(rel_heading)
embedding[absViewIndex, 32:64] = np.cos(rel_heading)
embedding[absViewIndex, 64:96] = np.sin(rel_elevation)
embedding[absViewIndex, 96:] = np.cos(rel_elevation)
return embedding
def _build_visited_embedding(adj_loc_list, visited):
n_emb = 64
half = int(n_emb/2)
embedding = np.zeros((len(adj_loc_list), n_emb), np.float32)
for kk, adj in enumerate(adj_loc_list):
val = visited[adj['nextViewpointId']]
embedding[kk, 0:half] = np.sin(val)
embedding[kk, half:] = np.cos(val)
return embedding
# pre-compute all the 36 possible paranoram location embeddings
_static_loc_embeddings = [
build_viewpoint_loc_embedding(viewIndex) for viewIndex in range(36)]
def _loc_distance(loc):
return np.sqrt(loc.rel_heading ** 2 + loc.rel_elevation ** 2)
def _canonical_angle(x):
''' Make angle in (-pi, +pi) '''
return x - 2 * np.pi * round(x / (2 * np.pi))
def _adjust_heading(sim, heading):
heading = (heading + 6) % 12 - 6 # minimum action to turn (e.g 11 -> -1)
''' Make possibly more than one heading turns '''
for _ in range(int(abs(heading))):
sim.makeAction(0, np.sign(heading), 0)
def _adjust_elevation(sim, elevation):
for _ in range(int(abs(elevation))):
''' Make possibly more than one elevation turns '''
sim.makeAction(0, 0, np.sign(elevation))
def _navigate_to_location(sim, nextViewpointId, absViewIndex):
state = sim.getState()
if state.location.viewpointId == nextViewpointId:
return # do nothing
# 1. Turn to the corresponding view orientation
_adjust_heading(sim, absViewIndex % 12 - state.viewIndex % 12)
_adjust_elevation(sim, absViewIndex // 12 - state.viewIndex // 12)
# find the next location
state = sim.getState()
assert state.viewIndex == absViewIndex
a, next_loc = None, None
for n_loc, loc in enumerate(state.navigableLocations):
if loc.viewpointId == nextViewpointId:
a = n_loc
next_loc = loc
break
assert next_loc is not None
# 3. Take action
sim.makeAction(a, 0, 0)
def _get_panorama_states(sim):
'''
Look around and collect all the navigable locations
Representation of all_adj_locs:
{'absViewIndex': int,
'relViewIndex': int,
'nextViewpointId': int,
'rel_heading': float,
'rel_elevation': float}
where relViewIndex is normalized using the current heading
Concepts:
- absViewIndex: the absolute viewpoint index, as returned by
state.viewIndex
- nextViewpointId: the viewpointID of this adjacent point
- rel_heading: the heading (radians) of this adjacent point
relative to looking forward horizontally (i.e. relViewIndex 12)
- rel_elevation: the elevation (radians) of this adjacent point
relative to looking forward horizontally (i.e. relViewIndex 12)
Features are 36 x D_vis, ordered from relViewIndex 0 to 35 (i.e.
feature[12] is always the feature of the patch forward horizontally)
'''
state = sim.getState()
initViewIndex = state.viewIndex
# 1. first look down, turning to relViewIndex 0
elevation_delta = -(state.viewIndex // 12)
_adjust_elevation(sim, elevation_delta)
# 2. scan through the 36 views and collect all navigable locations
adj_dict = {}
for relViewIndex in range(36):
# Here, base_rel_heading and base_rel_elevation are w.r.t
# relViewIndex 12 (looking forward horizontally)
# (i.e. the relative heading and elevation
# adjustment needed to switch from relViewIndex 12
# to the current relViewIndex)
base_rel_heading = (relViewIndex % 12) * angle_inc
base_rel_elevation = (relViewIndex // 12 - 1) * angle_inc
state = sim.getState()
absViewIndex = state.viewIndex
# get adjacent locations
for loc in state.navigableLocations[1:]:
distance = _loc_distance(loc)
# if a loc is visible from multiple view, use the closest
# view (in angular distance) as its representation
if (loc.viewpointId not in adj_dict or
distance < adj_dict[loc.viewpointId]['distance']):
rel_heading = _canonical_angle(
base_rel_heading + loc.rel_heading)
rel_elevation = base_rel_elevation + loc.rel_elevation
adj_dict[loc.viewpointId] = {
'absViewIndex': absViewIndex,
'nextViewpointId': loc.viewpointId,
'rel_heading': rel_heading,
'rel_elevation': rel_elevation,
'distance': distance}
# move to the next view
if (relViewIndex + 1) % 12 == 0:
sim.makeAction(0, 1, 1) # Turn right and look up
else:
sim.makeAction(0, 1, 0) # Turn right
# 3. turn back to the original view
_adjust_elevation(sim, - 2 - elevation_delta)
state = sim.getState()
assert state.viewIndex == initViewIndex # check the agent is back
# collect navigable location list
stop = {
'absViewIndex': -1,
'nextViewpointId': state.location.viewpointId}
adj_loc_list = [stop] + sorted(
adj_dict.values(), key=lambda x: abs(x['rel_elevation']))
return state, adj_loc_list
WorldState = namedtuple(
'WorldState', ['scanId', 'viewpointId', 'heading', 'elevation', 'img'])
BottomUpViewpoint = namedtuple('BottomUpViewpoint', [
'cls_prob', 'image_features', 'attribute_indices', 'object_indices', 'spatial_features', 'no_object_mask'])
def load_world_state(sim, world_state):
sim.cachedNewEpisode(*world_state)
def get_world_state(sim):
state = sim.getState()
return WorldState(scanId=state.scanId,
viewpointId=state.location.viewpointId,
heading=state.heading,
elevation=state.elevation,
img=None)
def make_sim(image_w, image_h, vfov, raw=False):
sim = CachedMatterSim(raw=raw)
sim.setRenderingEnabled(False)
sim.setDiscretizedViewingAngles(True)
sim.setCameraResolution(image_w, image_h)
sim.setCameraVFOV(math.radians(vfov))
try:
sim.init()
except:
sim.initialize()
pass
return sim
# def encode_action_sequence(action_tuples):
# encoded = []
# reached_end = False
# if action_tuples[0] == (0, 0, 0):
# # this method can't handle a <start> symbol
# assert all(t == (0, 0, 0) for t in action_tuples)
# for tpl in action_tuples:
# if tpl == (0, 0, 0):
# if reached_end:
# ix = IGNORE_ACTION_INDEX
# else:
# ix = END_ACTION_INDEX
# reached_end = True
# else:
# ix = FOLLOWER_ENV_ACTIONS.index(tpl)
# encoded.append(ix)
# return encoded
# Not needed for panorama action space
# def index_action_tuple(action_tuple):
# ix, heading_chg, elevation_chg = action_tuple
# if heading_chg > 0:
# return FOLLOWER_MODEL_ACTIONS.index('right')
# elif heading_chg < 0:
# return FOLLOWER_MODEL_ACTIONS.index('left')
# elif elevation_chg > 0:
# return FOLLOWER_MODEL_ACTIONS.index('up')
# elif elevation_chg < 0:
# return FOLLOWER_MODEL_ACTIONS.index('down')
# elif ix > 0:
# return FOLLOWER_MODEL_ACTIONS.index('forward')
# else:
# return FOLLOWER_MODEL_ACTIONS.index('<end>')
class ImageFeatures(object):
NUM_VIEWS = 36
MEAN_POOLED_DIM = 2048
feature_dim = MEAN_POOLED_DIM
IMAGE_W = 640
IMAGE_H = 480
VFOV = 60
@staticmethod
def from_args(args):
feats = []
for image_feature_type in sorted(args.image_feature_type):
if 'butd' in image_feature_type:
feats.append(BottomUpTopDownFeatures(use_object_embeddings=args.use_object_embeddings,
nextstep=args.nextstep))
if 'reverie' in image_feature_type:
feats.append(ReverieFeatures(use_object_embeddings=args.use_object_embeddings,
nextstep=args.nextstep))
if 'none' in image_feature_type:
feats.append(NoImageFeatures())
if 'bottom_up_attention' in image_feature_type:
raise NotImplementedError(
'bottom_up_attention has not been implemented for panorama environment')
if 'convolutional_attention' in image_feature_type:
feats.append(ConvolutionalImageFeatures(
args.image_feature_datasets,
split_convolutional_features=True,
downscale_convolutional_features=args.downscale_convolutional_features
))
raise NotImplementedError(
'convolutional_attention has not been implemented for panorama environment')
if 'mean_pooled' in image_feature_type:
feats.append(MeanPooledImageFeatures(args.image_feature_datasets,
feature_model=args.feature_model,
nextstep=args.nextstep))
assert len(feats) >= 1
return feats
@staticmethod
def add_args(argument_parser):
argument_parser.add_argument('--image_feature_type', nargs='+',
choices=['none',
'mean_pooled',
'convolutional_attention',
'bottom_up_attention',
'random',
'butd',
'reverie'],
default=['mean_pooled'])
argument_parser.add_argument('--image_attention_size', type=int)
argument_parser.add_argument('--image_feature_datasets', nargs='+', choices=['imagenet', 'places365'], default=[
'imagenet'], help='only applicable to mean_pooled or convolutional_attention options for --image_feature_type')
argument_parser.add_argument('--feature_model',
choices=['resnet', 'clip', 'clipRN50x4'],
default='clip')
argument_parser.add_argument(
'--bottom_up_detections', type=int, default=20)
argument_parser.add_argument(
'--bottom_up_detection_embedding_size', type=int, default=20)
argument_parser.add_argument(
'--downscale_convolutional_features', action='store_true')
def get_name(self):
raise NotImplementedError('get_name')
def batch_features(self, feature_list):
features = np.stack(feature_list)
return try_cuda(Variable(torch.from_numpy(features), requires_grad=False))
def get_features(self, state):
raise NotImplementedError('get_features')
class NoImageFeatures(ImageFeatures):
feature_dim = ImageFeatures.MEAN_POOLED_DIM
def __init__(self):
print('Image features not provided')
self.features = np.zeros(
(ImageFeatures.NUM_VIEWS, self.feature_dim), dtype=np.float32)
def get_features(self, state):
return self.features
def get_name(self):
return 'none'
class RandImageFeatures(ImageFeatures):
feature_dim = 24
def __init__(self):
print('Random image features will be provided')
self.features = np.random.randn(ImageFeatures.NUM_VIEWS, self.feature_dim)
def get_features(self, state):
return self.features
def get_name(self):
return 'random'
class MeanPooledImageFeatures(ImageFeatures):
def __init__(self, image_feature_datasets,
feature_model='resnet',
nextstep=True):
image_feature_datasets = sorted(image_feature_datasets)
feature_dim = MODEL2FEATURE_DIM[feature_model]
self.feature_model = feature_model
self.feature_prefix = MODEL2PREFIX[feature_model]
self.image_feature_datasets = image_feature_datasets
self.nextstep = nextstep
self.mean_pooled_feature_stores = [paths.mean_pooled_feature_store_paths[feature_model]
for dataset in image_feature_datasets]
self.feature_dim = feature_dim * \
len(image_feature_datasets)
print('Loading image features from %s' %
', '.join(self.mean_pooled_feature_stores))
print('Feature size', self.feature_dim)
tsv_fieldnames = ['scanId', 'viewpointId',
'image_w', 'image_h', 'vfov', 'features']
self.features = defaultdict(list)
for mpfs in self.mean_pooled_feature_stores:
with open(mpfs, 'rt') as tsv_in_file:
reader = csv.DictReader(
tsv_in_file, delimiter='\t', fieldnames=tsv_fieldnames)
for item in reader:
assert int(item['image_h']) == ImageFeatures.IMAGE_H
assert int(item['image_w']) == ImageFeatures.IMAGE_W
assert int(item['vfov']) == ImageFeatures.VFOV
long_id = self._make_id(item['scanId'], item['viewpointId'])
features = np.frombuffer(decode_base64(item['features']), dtype=np.float32).reshape(
(ImageFeatures.NUM_VIEWS, self.feature_dim))
self.features[long_id].append(features)
assert all(len(feats) == len(self.mean_pooled_feature_stores)
for feats in self.features.values())
self.features = {
long_id: np.concatenate(feats, axis=1)
for long_id, feats in self.features.items()
}
if self.nextstep:
self._add_nextstep()
def _add_nextstep(self):
print('nextstep features will be created')
nextstep_features = {}
missed_pano = 0
print('Loading the sim for nextstep features')
sim = make_sim(ImageFeatures.IMAGE_W,
ImageFeatures.IMAGE_H,
ImageFeatures.VFOV,
raw=self.raw)
for long_id in self.features:
scan = long_id.split('_')[0]
pano = long_id.split('_')[1]
world_state = WorldState(scan, pano, 0, 0, None)
sim.cachedNewEpisode(*world_state)
_, neighbors = _get_panorama_states(sim)
nextstep_features[long_id] = self.features[long_id]
for neighbor in neighbors:
absViewIndex = neighbor['absViewIndex']
nextpano = neighbor['nextViewpointId']
neighbor_feature = np.sum(self.features['{}_{}'.format(
scan, nextpano)], axis=0).reshape(1, self.feature_dim)
nextstep_features[long_id][absViewIndex, :] = neighbor_feature
print('missed {} panos'.format(missed_pano))
self.features = nextstep_features
def _make_id(self, scanId, viewpointId):
return scanId + '_' + viewpointId
def get_features(self, state):
long_id = self._make_id(state.scanId, state.location.viewpointId)
# Return feature of all the 36 views
return self.features[long_id]
def get_name(self):
name = '{}_mean_pooled'.format(self.feature_model)
if self.nextstep:
name += '_nextstep'
return name
class ReverieFeatures(ImageFeatures):
def __init__(self,
box_root='./tasks/FAST/data/BBox/',
word_embedding_path='./tasks/FAST/data/cc.en.300.vec',
nextstep=False,
use_object_embeddings=False):
print('Loading ReverieFeatures')
self.features = defaultdict(list)
self.nextstep = nextstep
self.use_object_embeddings = use_object_embeddings
name2count = defaultdict(int)
data = {}
for name in os.listdir(box_root):
extension = name.split('.')[-1]
if extension == 'json':
bboxes = json.load(open(os.path.join(box_root, name), 'r'))
scanId = name.split('_')[0]
viewpointId = name.split('_')[1].split('.')[0]
idx = self._make_id(scanId, viewpointId)
fov2object = defaultdict(list)
for bbox_idx in bboxes[viewpointId]:
name = bboxes[viewpointId][bbox_idx]['name']
visible_pos = bboxes[viewpointId][bbox_idx]['visible_pos']
bbox2d = bboxes[viewpointId][bbox_idx]['bbox2d']
name2count[name] += 1
for bbox, pos in zip(bbox2d, visible_pos):
fov2object[pos].append((name, bbox))
data[idx] = fov2object
THRESHOLD = 5
objid2name = dict()
name2objid = dict()
obj_idx = 0
for name in name2count.keys():
if name2count[name] >= THRESHOLD:
name2objid[name] = obj_idx
objid2name[obj_idx] = name
obj_idx += 1
if self.use_object_embeddings:
feature_dim = 300
else:
feature_dim = len(name2objid)
self.feature_dim = feature_dim
self.features = {}
print('Feature dim:', self.feature_dim)
w2v = load_vectors(word_embedding_path, name2objid)
missing = []
for w in name2objid:
if w not in w2v:
missing += [w]
print(' '.join(missing))
for k in data.keys():
feats = np.zeros(
(ImageFeatures.NUM_VIEWS, self.feature_dim), dtype=np.float32)
for pos in data[k].keys():
for (name, box) in data[k][pos]:
if self.use_object_embeddings:
if name in w2v:
vector = w2v[name]
feats[pos, :] += vector
elif name in name2objid:
obj_id = name2objid[name]
feats[pos, obj_id] = 1.0
self.features[k] = feats
if self.nextstep:
self._add_nextstep()
def _make_id(self, scanId, viewpointId):
return scanId + '_' + viewpointId
def _add_nextstep(self):
print('nextstep features will be created')
nextstep_features = {}
missed_pano = 0
print('Loading the sim for nextstep features')
sim = make_sim(ImageFeatures.IMAGE_W,
ImageFeatures.IMAGE_H,
ImageFeatures.VFOV,
raw=self.raw)
for long_id in self.features:
scan = long_id.split('_')[0]
pano = long_id.split('_')[1]
world_state = WorldState(scan, pano, 0, 0, None)
sim.cachedNewEpisode(*world_state)
_, neighbors = _get_panorama_states(sim)
nextstep_features[long_id] = self.features[long_id]
for neighbor in neighbors:
absViewIndex = neighbor['absViewIndex']
nextpano = neighbor['nextViewpointId']
neighbor_feature = np.sum(self.features['{}_{}'.format(
scan, nextpano)], axis=0).reshape(1, self.feature_dim)
nextstep_features[long_id][absViewIndex, :] = neighbor_feature
print('missed {} panos'.format(missed_pano))
self.features = nextstep_features
def get_features(self, state):
long_id = self._make_id(state.scanId, state.location.viewpointId)
# Return feature of all the 36 views
return self.features[long_id]
def get_name(self):
name = 'reverie'
if self.use_object_embeddings:
name += '_oe'
if self.nextstep:
name += '_nextstep'
return name
class BottomUpTopDownFeatures(ImageFeatures):
def __init__(self,
bottomup_filename='./img_features/mp_obj36.tsv',
use_object_embeddings=False,
word_embedding_path='./tasks/FAST/data/cc.en.300.vec',
obj_dict_file='./tasks/FAST/data/vg_object_dictionaries.all.json',
threshold=0.5,
nextstep=False):
print('Loading BottomUpTopDownFeatures')
self.features = defaultdict(list)
self.use_object_embeddings = use_object_embeddings
if self.use_object_embeddings:
self.objemb, self.feature_dim = True, 300
vg2idx, idx2vg, obj_classes, name2vg, name2idx, vg2name = get_object_dictionaries(
obj_dict_file, return_all=True)
self.name2vg, self.vg2name = name2vg, vg2name
print('Loading word embeddings...')
self.w2v = load_vectors(word_embedding_path, self.name2vg)
missing = []
for w in self.name2vg:
if w not in self.w2v:
missing += [w]
print('Missing object names:', ' '.join(missing))
else:
self.objemb, self.feature_dim = False, 2048
self.w2v, self.vg2name, self.name2vg = None, None, None
self.nextstep = nextstep
print('Feature dim:', self.feature_dim)
FIELDNAMES = ["img_id", "img_h", "img_w", "objects_id", "objects_conf",
"attrs_id", "attrs_conf", "num_boxes", "boxes", "features"]
self.features = {}
with open(bottomup_filename) as f:
reader = csv.DictReader(f, FIELDNAMES, delimiter="\t")
for i, item in enumerate(reader):
for key in ['img_h', 'img_w', 'num_boxes']:
item[key] = int(item[key])
boxes = item['num_boxes']
decode_config = [
('objects_id', (boxes, ), np.int64),
('objects_conf', (boxes, ), np.float32),
('attrs_id', (boxes, ), np.int64),
('attrs_conf', (boxes, ), np.float32),
('boxes', (boxes, 4), np.float32),
('features', (boxes, -1), np.float32),
]
for key, shape, dtype in decode_config:
item[key] = np.frombuffer(base64.b64decode(item[key]), dtype=dtype)
item[key] = item[key].reshape(shape)
item[key].setflags(write=False)
scanId, viewpointId = item['img_id'].split('.')[0].split('_')
fovid = int(item['img_id'].split('.')[1])
idx = self._make_id(scanId, viewpointId)
if idx not in self.features:
self.features[idx] = np.zeros(
(ImageFeatures.NUM_VIEWS, self.feature_dim), dtype=np.float32)
if self.use_object_embeddings:
keep_boxes = np.where(item['objects_conf'] >= threshold)[0]
obj_ids = item['objects_id'][keep_boxes]
emb_feats = np.zeros((obj_ids.shape[0], 300), dtype=np.float32)
for ii, obj_id in enumerate(obj_ids):
obj_name = vg2name.get(obj_id, '</s>')
emb_feats[ii, :] = self.w2v.get(obj_name, self.w2v['</s>'])
feats = emb_feats
else:
feats = item['features']
feats = np.sum(feats, axis=0)
self.features[idx][fovid, :] = feats
if self.nextstep:
self._add_nextstep()
def _make_id(self, scanId, viewpointId):
return scanId + '_' + viewpointId
def _add_nextstep(self):
print('nextstep features will be created')
nextstep_features = {}
missed_pano = 0
print('Loading the sim for nextstep features')
sim = make_sim(ImageFeatures.IMAGE_W,
ImageFeatures.IMAGE_H,
ImageFeatures.VFOV,
raw=self.raw)
for long_id in self.features:
scan = long_id.split('_')[0]
pano = long_id.split('_')[1]
world_state = WorldState(scan, pano, 0, 0, None)
sim.cachedNewEpisode(*world_state)
_, neighbors = _get_panorama_states(sim)
nextstep_features[long_id] = self.features[long_id]
for neighbor in neighbors:
absViewIndex = neighbor['absViewIndex']
nextpano = neighbor['nextViewpointId']
neighbor_feature = np.sum(self.features['{}_{}'.format(
scan, nextpano)], axis=0).reshape(1, self.feature_dim)
nextstep_features[long_id][absViewIndex, :] = neighbor_feature
print('missed {} panos'.format(missed_pano))
self.features = nextstep_features
def get_features(self, state):
long_id = self._make_id(state.scanId, state.location.viewpointId)
# Return feature of all the 36 views
return self.features[long_id]
def get_name(self):
name = 'butd'
if self.use_object_embeddings:
name += '_oe'
if self.nextstep:
name += '_nextstep'
return name
class ConvolutionalImageFeatures(ImageFeatures):
feature_dim = ImageFeatures.MEAN_POOLED_DIM
def __init__(self, image_feature_datasets, split_convolutional_features=True, downscale_convolutional_features=True):
self.image_feature_datasets = image_feature_datasets
self.split_convolutional_features = split_convolutional_features
self.downscale_convolutional_features = downscale_convolutional_features
self.convolutional_feature_stores = [paths.convolutional_feature_store_paths[dataset]
for dataset in image_feature_datasets]
def _make_id(self, scanId, viewpointId):
return scanId + '_' + viewpointId
@functools.lru_cache(maxsize=3000)
def _get_convolutional_features(self, scanId, viewpointId, viewIndex):
feats = []
for cfs in self.convolutional_feature_stores:
if self.split_convolutional_features:
path = os.path.join(cfs, scanId, '{}_{}{}.npy'.format(
viewpointId, viewIndex, '_downscaled' if self.downscale_convolutional_features else ''))
this_feats = np.load(path)
else:
# memmap for loading subfeatures
path = os.path.join(cfs, scanId, '%s.npy' % viewpointId)
mmapped = np.load(path, mmap_mode='r')
this_feats = mmapped[viewIndex, :, :, :]
feats.append(this_feats)
if len(feats) > 1:
return np.concatenate(feats, axis=1)
return feats[0]
def get_features(self, state):
return self._get_convolutional_features(state.scanId, state.location.viewpointId, state.viewIndex)
def get_name(self):
name = '+'.join(sorted(self.image_feature_datasets))
name = '{}_convolutional_attention'.format(name)
if self.downscale_convolutional_features:
name = name + '_downscale'
return name
class BottomUpImageFeatures(ImageFeatures):
PAD_ITEM = ('<pad>',)
feature_dim = ImageFeatures.MEAN_POOLED_DIM
def __init__(self, number_of_detections, precomputed_cache_path=None, precomputed_cache_dir=None, image_width=640, image_height=480):
self.number_of_detections = number_of_detections
self.index_to_attributes, self.attribute_to_index = BottomUpImageFeatures.read_visual_genome_vocab(
paths.bottom_up_attribute_path, BottomUpImageFeatures.PAD_ITEM, add_null=True)
self.index_to_objects, self.object_to_index = BottomUpImageFeatures.read_visual_genome_vocab(
paths.bottom_up_object_path, BottomUpImageFeatures.PAD_ITEM, add_null=False)
self.num_attributes = len(self.index_to_attributes)
self.num_objects = len(self.index_to_objects)
self.attribute_pad_index = self.attribute_to_index[BottomUpImageFeatures.PAD_ITEM]
self.object_pad_index = self.object_to_index[BottomUpImageFeatures.PAD_ITEM]
self.image_width = image_width
self.image_height = image_height
self.precomputed_cache = {}
def add_to_cache(key, viewpoints):
assert len(viewpoints) == ImageFeatures.NUM_VIEWS
viewpoint_feats = []
for viewpoint in viewpoints:
params = {}
for param_key, param_value in viewpoint.items():
if param_key == 'cls_prob':
# make sure it's in descending order
assert np.all(param_value[:-1] >= param_value[1:])
if param_key == 'boxes':
# TODO: this is for backward compatibility, remove it
param_key = 'spatial_features'
param_value = spatial_feature_from_bbox(
param_value, self.image_height, self.image_width)
assert len(param_value) >= self.number_of_detections
params[param_key] = param_value[:self.number_of_detections]
viewpoint_feats.append(BottomUpViewpoint(**params))
self.precomputed_cache[key] = viewpoint_feats
if precomputed_cache_dir:
self.precomputed_cache = {}
import glob
for scene_dir in glob.glob(os.path.join(precomputed_cache_dir, '*')):
scene_id = os.path.basename(scene_dir)
pickle_file = os.path.join(
scene_dir, 'd={}.pkl'.format(number_of_detections))
with open(pickle_file, 'rb') as f:
data = pickle.load(f)
for (viewpoint_id, viewpoints) in data.items():
key = (scene_id, viewpoint_id)
add_to_cache(key, viewpoints)
elif precomputed_cache_path:
self.precomputed_cache = {}
with open(precomputed_cache_path, 'rb') as f:
data = pickle.load(f)
for (key, viewpoints) in data.items():
add_to_cache(key, viewpoints)
@staticmethod
def read_visual_genome_vocab(fname, pad_name, add_null=False):
# one-to-many mapping from indices to names (synonyms)
index_to_items = []
item_to_index = {}
start_ix = 0
items_to_add = [pad_name]
if add_null:
null_tp = ()
items_to_add.append(null_tp)
for item in items_to_add:
index_to_items.append(item)
item_to_index[item] = start_ix
start_ix += 1
with open(fname) as f:
for index, line in enumerate(f):
this_items = []
for synonym in line.split(','):
item = tuple(synonym.split())
this_items.append(item)
item_to_index[item] = index + start_ix
index_to_items.append(this_items)
assert len(index_to_items) == max(item_to_index.values()) + 1
return index_to_items, item_to_index
def batch_features(self, feature_list):
def transform(lst, wrap_with_var=True):
features = np.stack(lst)
x = torch.from_numpy(features)
if wrap_with_var:
x = Variable(x, requires_grad=False)
return try_cuda(x)
return BottomUpViewpoint(
cls_prob=transform([f.cls_prob for f in feature_list]),
image_features=transform([f.image_features for f in feature_list]),
attribute_indices=transform(
[f.attribute_indices for f in feature_list]),
object_indices=transform([f.object_indices for f in feature_list]),
spatial_features=transform([f.spatial_features for f in feature_list]),
no_object_mask=transform(
[f.no_object_mask for f in feature_list], wrap_with_var=False),
)
def parse_attribute_objects(self, tokens):
parse_options = []
# allow blank attribute, but not blank object
for split_point in range(0, len(tokens)):
attr_tokens = tuple(tokens[:split_point])
obj_tokens = tuple(tokens[split_point:])
if attr_tokens in self.attribute_to_index and obj_tokens in self.object_to_index:
parse_options.append(
(self.attribute_to_index[attr_tokens], self.object_to_index[obj_tokens]))
assert parse_options, 'did not find any parses for {}'.format(tokens)
# prefer longer objects, e.g. 'electrical outlet' over 'electrical' 'outlet'
return parse_options[0]
@functools.lru_cache(maxsize=20000)
def _get_viewpoint_features(self, scan_id, viewpoint_id):
if self.precomputed_cache:
return self.precomputed_cache[(scan_id, viewpoint_id)]
fname = os.path.join(paths.bottom_up_feature_store_path,
scan_id, '{}.p'.format(viewpoint_id))
with open(fname, 'rb') as f:
data = pickle.load(f, encoding='latin1')
viewpoint_features = []
for viewpoint in data:
top_indices = k_best_indices(
viewpoint['cls_prob'], self.number_of_detections, sorted=True)[::-1]
no_object = np.full(self.number_of_detections, True,
dtype=np.uint8) # will become torch Byte tensor
no_object[0:len(top_indices)] = False
cls_prob = np.zeros(self.number_of_detections, dtype=np.float32)
cls_prob[0:len(top_indices)] = viewpoint['cls_prob'][top_indices]
assert cls_prob[0] == np.max(cls_prob)
image_features = np.zeros(
(self.number_of_detections, ImageFeatures.MEAN_POOLED_DIM), dtype=np.float32)
image_features[0:len(top_indices)] = viewpoint['features'][top_indices]
spatial_feats = np.zeros(
(self.number_of_detections, 5), dtype=np.float32)
spatial_feats[0:len(top_indices)] = spatial_feature_from_bbox(
viewpoint['boxes'][top_indices], self.image_height, self.image_width)
object_indices = np.full(
self.number_of_detections, self.object_pad_index)
attribute_indices = np.full(
self.number_of_detections, self.attribute_pad_index)
for i, ix in enumerate(top_indices):
attribute_ix, object_ix = self.parse_attribute_objects(
list(viewpoint['captions'][ix].split()))
object_indices[i] = object_ix
attribute_indices[i] = attribute_ix
viewpoint_features.append(BottomUpViewpoint(
cls_prob, image_features, attribute_indices, object_indices, spatial_feats, no_object))
return viewpoint_features
def get_features(self, state):
viewpoint_features = self._get_viewpoint_features(