-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.py
executable file
·409 lines (369 loc) · 17.8 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
''' Batched Room-to-Room navigation environment '''
import sys
sys.path.append('buildpy36')
import MatterSim
import csv
import numpy as np
import math
import base64
import utils
import json
import os
import random
import networkx as nx
from param import args
from utils import load_datasets, load_nav_graphs, Tokenizer
csv.field_size_limit(sys.maxsize)
class EnvBatch():
''' A simple wrapper for a batch of MatterSim environments,
using discretized viewpoints and pretrained features '''
def __init__(self, feature_store=None, batch_size=100):
"""
1. Load pretrained image feature
2. Init the Simulator.
:param feature_store: The name of file stored the feature.
:param batch_size: Used to create the simulator list.
"""
if feature_store:
if type(feature_store) is dict: # A silly way to avoid multiple reading
self.features = feature_store
self.image_w = 640
self.image_h = 480
self.vfov = 60
self.feature_size = next(iter(self.features.values())).shape[-1]
print('The feature size is %d' % self.feature_size)
else:
print('Image features not provided')
self.image_w = 640
self.image_h = 480
self.vfov = 60
self.features = feature_store
self.feature_size = 2048
if args.debug:
self.featurized_scans = set(json.load(open('img_features/debug.json','r')))
else:
self.featurized_scans = set([key.split("_")[0] for key in list(self.features.keys())])
self.batch_size = batch_size
self.sim = MatterSim.Simulator()
self.sim.setRenderingEnabled(False)
self.sim.setDiscretizedViewingAngles(True)
self.sim.setBatchSize(self.batch_size)
self.sim.setCameraResolution(self.image_w, self.image_h)
self.sim.setCameraVFOV(math.radians(self.vfov))
self.sim.initialize()
def _make_id(self, scanId, viewpointId):
return scanId + '_' + viewpointId
def newEpisodes(self, scanIds, viewpointIds, headings, elevations=None):
if elevations == None:
self.sim.newEpisode(scanIds, viewpointIds, headings, [0]*self.batch_size)
else:
self.sim.newEpisode(scanIds, viewpointIds, headings, elevations)
def getStates(self):
"""
Get list of states augmented with precomputed image features. rgb field will be empty.
Agent's current view [0-35] (set only when viewing angles are discretized)
[0-11] looking down, [12-23] looking at horizon, [24-35] looking up
:return: [ ((30, 2048), sim_state) ] * batch_size
"""
feature_states = []
for state in self.sim.getState():
long_id = self._make_id(state.scanId, state.location.viewpointId)
if self.features is not None:
feature = self.features[long_id]
# feature = self.features[long_id][state.viewIndex,:]
feature_states.append((feature, state))
else:
feature_states.append((None, state))
return feature_states
def makeActions(self, actions):
''' Take an action using the full state dependent action interface (with batched input).
Every action element should be an (index, heading, elevation) tuple. '''
ix = []
heading = []
elevation = []
for i,h,e in actions:
ix.append(int(i))
heading.append(float(h))
elevation.append(float(e))
self.sim.makeAction(ix, heading, elevation)
class R2RBatch():
''' Implements the Room to Room navigation task, using discretized viewpoints and pretrained features '''
def __init__(self, feature_store, obj_store, batch_size=100, seed=10, splits=['train'], tokenizer=None,
name=None):
self.env = EnvBatch(feature_store=feature_store, batch_size=batch_size)
self.obj_dict = obj_store
if feature_store:
self.feature_size = self.env.feature_size
if args.debug:
self.feature_size=2048
self.data = []
if tokenizer:
self.tok = tokenizer
scans = []
for split in splits:
for item in load_datasets([split]):
# Split multiple instructions into separate entries
for j,instr in enumerate(item['instructions']):
if item['scan'] not in self.env.featurized_scans: # For fast training
continue
new_item = dict(item)
new_item['instr_id'] = '%s_%d' % (item['path_id'], j)
new_item['instructions'] = instr
if tokenizer:
new_item['instr_encoding'] = tokenizer.encode_sentence(instr)
if not tokenizer or new_item['instr_encoding'] is not None: # Filter the wrong data
self.data.append(new_item)
scans.append(item['scan'])
if name is None:
self.name = splits[0] if len(splits) > 0 else "FAKE"
else:
self.name = name
self.scans = set(scans)
self.splits = splits
self.seed = seed
random.seed(self.seed)
random.shuffle(self.data)
self.ix = 0
self.batch_size = batch_size
self._load_nav_graphs()
self.angle_feature = utils.get_all_point_angle_feature()
self.sim = utils.new_simulator()
self.buffered_state_dict = {}
# near point
self.pid2near_pid = np.zeros([36,5], dtype=np.int32)
self.pid2angle = np.zeros([36,2], dtype=np.float32)
for c in range(36):
l = c+11 if c%12==0 else c-1
r = c-11 if c%12==11 else c+1
t = -1 if c//12==2 else c+12
b = -1 if c//12==0 else c-12
self.pid2near_pid[c,:] = np.array([c,l,t,r,b],dtype=np.int32)
self.pid2angle[c,0] = (c%12)*math.radians(30)
self.pid2angle[c,1] = (c//12)*math.radians(30)+math.radians(-30)
self.pid2near_mask = (self.pid2near_pid == -1)
print('R2RBatch loaded with %d instructions, using splits: %s' % (len(self.data), ",".join(splits)))
def size(self):
return len(self.data)
def _load_nav_graphs(self):
"""
load graph from self.scan,
Store the graph {scan_id: graph} in self.graphs
Store the shortest path {scan_id: {view_id_x: {view_id_y: [path]} } } in self.paths
Store the distances in self.distances. (Structure see above)
Load connectivity graph for each scan, useful for reasoning about shortest paths
:return: None
"""
print('Loading navigation graphs for %d scans' % len(self.scans))
self.graphs = load_nav_graphs(self.scans)
self.paths = {}
for scan, G in self.graphs.items(): # compute all shortest paths
self.paths[scan] = dict(nx.all_pairs_dijkstra_path(G))
self.distances = {}
for scan, G in self.graphs.items(): # compute all shortest paths
self.distances[scan] = dict(nx.all_pairs_dijkstra_path_length(G))
def _next_minibatch(self, tile_one=False, batch_size=None, **kwargs):
"""
Store the minibach in 'self.batch'
:param tile_one: Tile the one into batch_size
:return: None
"""
if batch_size is None:
batch_size = self.batch_size
if tile_one:
batch = [self.data[self.ix]] * batch_size
self.ix += 1
if self.ix >= len(self.data):
random.shuffle(self.data)
self.ix -= len(self.data)
else:
batch = self.data[self.ix: self.ix+batch_size]
if len(batch) < batch_size:
random.shuffle(self.data)
self.ix = batch_size - len(batch)
batch += self.data[:self.ix]
else:
self.ix += batch_size
self.batch = batch
def reset_epoch(self, shuffle=False):
''' Reset the data index to beginning of epoch. Primarily for testing.
You must still call reset() for a new episode. '''
if shuffle:
random.shuffle(self.data)
self.ix = 0
def _shortest_path_action(self, state, goalViewpointId):
''' Determine next action on the shortest path to goal, for supervised training. '''
if state.location.viewpointId == goalViewpointId:
return goalViewpointId # Just stop here
path = self.paths[state.scanId][state.location.viewpointId][goalViewpointId]
nextViewpointId = path[1]
return nextViewpointId
def make_candidate(self, feature, scanId, viewpointId, viewId):
def _loc_distance(loc):
return np.sqrt(loc.rel_heading ** 2 + loc.rel_elevation ** 2)
def _get_near(v, base_heading):
def _np_angle_feature(heading, elevation):
e_heading = np.expand_dims(heading, axis=1)
e_elevation = np.expand_dims(elevation, axis=1)
N = args.angle_feat_size // 4 # repeat time
return np.concatenate([np.sin(e_heading).repeat(N,1), np.cos(e_heading).repeat(N,1), np.sin(e_elevation).repeat(N,1), np.cos(e_elevation).repeat(N,1)], -1)
c = v['pointId']
cand_heading = v['heading']
cand_elevation = v['elevation']
near_pointId = self.pid2near_pid[c,:]
near_mask = self.pid2near_mask[c,:]
default_near_pointId = near_pointId.copy()
default_near_pointId[near_mask==True] = 0
near_heading = self.pid2angle[default_near_pointId,0]-base_heading
near_elevation = self.pid2angle[default_near_pointId,1]
near_rel_heading = near_heading-cand_heading
near_rel_elevation = near_elevation-cand_elevation
near_visual_feat = feature[default_near_pointId]
near_angle_feat = _np_angle_feature(near_heading, near_elevation)
near_edge_feat = _np_angle_feature(near_rel_heading, near_rel_elevation)
near_obj_class = [self.obj_dict[scanId][viewpointId][pointId]['object_class'][:args.top_N_obj]
if pointId != -1 else np.zeros(args.top_N_obj) for pointId in near_pointId]
near_obj_class = np.stack(near_obj_class)
near_view_id = np.array(near_pointId)
return near_pointId, near_mask, near_visual_feat, near_angle_feat, near_edge_feat, near_obj_class,near_view_id
base_heading = (viewId % 12) * math.radians(30)
adj_dict = {}
long_id = "%s_%s" % (scanId, viewpointId)
if long_id not in self.buffered_state_dict:
for ix in range(36):
if ix == 0:
self.sim.newEpisode([scanId], [viewpointId], [0], [math.radians(-30)])
elif ix % 12 == 0:
self.sim.makeAction([0], [1.0], [1.0])
else:
self.sim.makeAction([0], [1.0], [0])
state = self.sim.getState()[0]
assert state.viewIndex == ix
# Heading and elevation for the viewpoint center
heading = state.heading - base_heading
elevation = state.elevation
visual_feat = feature[ix]
# get adjacent locations
for j, loc in enumerate(state.navigableLocations[1:]):
# if a loc is visible from multiple view, use the closest
# view (in angular distance) as its representation
distance = _loc_distance(loc)
# Heading and elevation for for the loc
loc_heading = heading + loc.rel_heading
loc_elevation = elevation + loc.rel_elevation
angle_feat = utils.angle_feature(loc_heading, loc_elevation)
if (loc.viewpointId not in adj_dict or
distance < adj_dict[loc.viewpointId]['distance']):
adj_dict[loc.viewpointId] = {
'heading': loc_heading,
'elevation': loc_elevation,
"normalized_heading": state.heading + loc.rel_heading,
'scanId':scanId,
'viewpointId': loc.viewpointId, # Next viewpoint id
'pointId': ix,
'distance': distance,
'idx': j + 1,
'angle_feat': angle_feat,
'visual_feat': visual_feat,
}
for k,v in adj_dict.items():
adj_dict[k]['obj_class'] = self.obj_dict[scanId][viewpointId][v['pointId']]['object_class'][:args.top_N_obj]
near_pointId, near_mask, near_visual_feat, near_angle_feat, near_edge_feat, near_obj_class,near_view_id = _get_near(v, base_heading)
adj_dict[k]['near_pointId'] = near_pointId
adj_dict[k]['near_mask'] = near_mask
adj_dict[k]['near_visual_feat'] = near_visual_feat
adj_dict[k]['near_angle_feat'] = near_angle_feat
adj_dict[k]['near_edge_feat'] = near_edge_feat
adj_dict[k]['near_obj_class'] = near_obj_class
adj_dict[k]['near_view_id'] = near_view_id
candidate = list(adj_dict.values())
self.buffered_state_dict[long_id] = [
{key: c[key]
for key in
['normalized_heading', 'elevation', 'scanId', 'viewpointId',
'pointId', 'idx']}
for c in candidate
]
return candidate
else:
candidate = self.buffered_state_dict[long_id]
candidate_new = []
for c in candidate:
c_new = c.copy()
ix = c_new['pointId']
normalized_heading = c_new['normalized_heading']
visual_feat = feature[ix]
loc_heading = normalized_heading - base_heading
c_new['heading'] = loc_heading
angle_feat = utils.angle_feature(c_new['heading'], c_new['elevation'])
c_new['angle_feat'] = angle_feat
c_new['visual_feat'] = visual_feat
c_new.pop('normalized_heading')
c_new['obj_class'] = self.obj_dict[scanId][viewpointId][ix]['object_class'][:args.top_N_obj]
near_pointId, near_mask, near_visual_feat, near_angle_feat, near_edge_feat, near_obj_class,near_view_id = _get_near(c_new, base_heading)
c_new['near_pointId'] = near_pointId
c_new['near_mask'] = near_mask
c_new['near_visual_feat'] = near_visual_feat
c_new['near_angle_feat'] = near_angle_feat
c_new['near_edge_feat'] = near_edge_feat
c_new['near_obj_class'] = near_obj_class
c_new['near_view_id'] = near_view_id
candidate_new.append(c_new)
return candidate_new
def _get_obs(self):
obs = []
for i, (feature, state) in enumerate(self.env.getStates()):
item = self.batch[i]
base_view_id = state.viewIndex
# Full features
candidate = self.make_candidate(feature, state.scanId, state.location.viewpointId, state.viewIndex)
# (visual_feature, angel_feature) for views
feature = np.concatenate((feature, self.angle_feature[base_view_id]), -1)
obs.append({
'instr_id' : item['instr_id'],
'scan' : state.scanId,
'viewpoint' : state.location.viewpointId,
'viewIndex' : state.viewIndex,
'heading' : state.heading,
'elevation' : state.elevation,
'feature' : feature,
'candidate': candidate,
'navigableLocations' : state.navigableLocations,
'instructions' : item['instructions'],
'teacher' : self._shortest_path_action(state, item['path'][-1]),
'gt_path': item['path'],
'path_id' : item['path_id']
})
if 'instr_encoding' in item:
obs[-1]['instr_encoding'] = item['instr_encoding']
# A2C reward. The negative distance between the state and the final state
obs[-1]['distance'] = self.distances[state.scanId][state.location.viewpointId][item['path'][-1]]
return obs
def reset(self, batch=None, inject=False, **kwargs):
''' Load a new minibatch / episodes. '''
if batch is None: # Allow the user to explicitly define the batch
self._next_minibatch(**kwargs)
else:
if inject: # Inject the batch into the next minibatch
self._next_minibatch(**kwargs)
self.batch[:len(batch)] = batch
else: # Else set the batch to the current batch
self.batch = batch
scanIds = [item['scan'] for item in self.batch]
viewpointIds = [item['path'][0] for item in self.batch]
headings = [item['heading'] for item in self.batch]
self.env.newEpisodes(scanIds, viewpointIds, headings)
return self._get_obs()
def step(self, actions):
''' Take action (same interface as makeActions) '''
self.env.makeActions(actions)
return self._get_obs()
def get_statistics(self):
stats = {}
length = 0
path = 0
for datum in self.data:
length += len(self.tok.split_sentence(datum['instructions']))
path += self.distances[datum['scan']][datum['path'][0]][datum['path'][-1]]
stats['length'] = length / len(self.data)
stats['path'] = path / len(self.data)
return stats