-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSCNav_agent.py
1815 lines (1470 loc) · 64.5 KB
/
SCNav_agent.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
from models import QNet, ResNet, Bottleneck,\
DeconvBottleneck, ACNet, Q_discrete
#from models import QNet, QNet512, SegNet, ConfNet, ResNet, Bottleneck,\
#DeconvBottleneck, ACNet, Q_discrete
#from pathfinding.core.diagonal_movement import DiagonalMovement
#from pathfinding.core.grid import Grid
#from pathfinding.finder.a_star import AStarFinder
from utils.dataloader_seg import *
import habitat
from habitat.tasks.nav.nav import NavigationEpisode
from habitat.tasks.nav.object_nav_task import (
ObjectGoal,
ObjectGoalNavEpisode,
ObjectViewLocation,
)
import torch
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import pickle
import _pickle as cPickle
import random
import numpy as np
#import pandas as pd
from quaternion import as_rotation_matrix, from_rotation_matrix
from utils.utils import generate_pc, color2local3d, repeat4, pc2local, pc2local_gpu, d3_41_colors_rgb
from collections import namedtuple, OrderedDict
import copy
import os
from utils.mapper import Mapper
#import skfmm
name2id = {
'door': 3,
'table': 4,
'sofa': 9,
'bed': 10,
'sink': 14,
'toilet': 17,
'bathtub': 24,
'shower': 22,
'counter': 25
}
layer_infos = [
[64, 7, 2, 3],
[3, 2, 1],
[12, 64, 3, 2, 1, 1],
[16, 128, 3, 1, 1, 1],
[24, 256, 3, 1, 1, 1],
[12, 512, 3, 1, 1, 1],
[12, 512, 3, 1, 1, 0, 1],
[24, 256, 3, 1, 1, 0, 1],
[16, 128, 3, 1, 1, 0, 1],
[12, 64, 3, 2, 1, 1, 1],
[4, 64, 3, 2, 1, 1, 1]
]
transform = transforms.Compose([
scaleNorm(),
ToTensor(),
Normalize()
])
Transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward'))
class replay_buffer(object):
def __init__(self, capacity, save_dir, current_position):
self.capacity = capacity
self.memory = []
self.position = 0
if current_position is None:
self.save_dir = os.path.join(save_dir, "replay_buffer")
if os.path.exists(self.save_dir):
assert False, "Replay Buffer Directory already exists!"
os.mkdir(self.save_dir)
else:
self.save_dir = os.path.join(save_dir, 'replay_buffer')
self.position = current_position
files = [f for f in os.listdir(self.save_dir) if f.endswith('pkl')]
for fid in range(len(files)):
f = '.'.join([str(fid), 'pkl'])
self.memory.append(os.path.join(self.save_dir, f))
def push(self, *args):
if len(self.memory) < self.capacity:
self.memory.append(None)
target_file = os.path.join(self.save_dir, "%s.pkl" % (self.position))
with open(target_file, 'wb') as f:
cPickle.dump(Transition(*args), f, protocol=-1)
self.memory[self.position] = target_file
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
paths = random.sample(self.memory, batch_size)
result = []
for path in paths:
with open(path, 'rb') as f:
data = cPickle.load(f)
result.append(data)
return result
def __len__(self):
return len(self.memory)
class Memory:
def __init__(
self,
aggregate,
memory_size,
pano,
num_channel,
id2cat,
roof_thre,
floor_thre,
ignore,
fov=np.pi / 2.):
self.points = None
self.rgbs = None
self.semantics = None
self.aggregate = aggregate
self.pano = pano
self.memory_size = memory_size
self.markers = []
self.num_channel = num_channel
self.id2cat = id2cat
self.roof_thre = roof_thre
self.floor_thre = floor_thre
self.ignore = ignore
self.fov = fov
self.ready_counter = 0
def reset(self):
self.points = None
self.rgbs = None
self.semantics = None
self.markers = []
self.ready_counter = 0
def get_height_map(self, quaternion, translation, area_x, area_z, h, w):
if self.pano:
assert self.ready_counter ==0, "memory accumulating for pano case"
assert len(self.markers) > 0, "Cannot view an empty memory"
rotation = as_rotation_matrix(quaternion)
T_world = np.eye(4)
T_world[0:3, 0:3] = rotation
T_world[0:3, 3] = translation
pointss = pc2local(T_world, self.points)
round_agent = (np.abs(pointss[:, 0]) < area_x / 2.)\
& (np.abs(pointss[:, 2]) < area_z / 2.)
pointss = pointss[round_agent, :]
rgbss = self.rgbs[round_agent, :]
semanticss = self.semantics[round_agent]
scale_h = area_z / h
scale_w = area_x / w
X = (pointss[:, 0] + (area_x / 2.)) / float(scale_w)
Y = pointss[:, 1]
Z = (pointss[:, 2] + (area_z / 2.)) / float(scale_h)
# 1 for 4
XZ_ff = np.column_stack((np.floor(X), np.floor(Z))) #0, 1, ... n-1
XZ_fc = np.column_stack((np.floor(X), np.ceil(Z)))
XZ_cc = np.column_stack((np.ceil(X), np.ceil(Z)))
XZ_cf = np.column_stack((np.ceil(X), np.floor(Z)))
XZ = np.concatenate((np.concatenate((XZ_ff, XZ_fc), axis=0),\
np.concatenate((XZ_cc, XZ_cf), axis=0)), axis=0) #0, 1, ... 4n - 1
assert h == w, "Currently only support square!"
XZ[XZ >= h] = h - 1
XZ[XZ < 0.] = 0.
Y = repeat4(Y)
XYZ = np.column_stack((XZ, Y))
df = pd.DataFrame(XYZ)
idx = df.groupby([0, 1])[2].transform(max) == df[2]
idx = idx.values
height_rgb = np.zeros((h, w, 3))
height_sem = np.ones((h, w), dtype=np.int32) * (self.num_channel - 1)
rgbss_4 = repeat4(rgbss)
semanticss_4 = repeat4(semanticss)
XZ = XZ.astype(int)
height_rgb[XZ[idx][:, 0], XZ[idx][:, 1], :] = rgbss_4[idx, :]
height_sem[XZ[idx][:, 0], XZ[idx][:, 1]] = semanticss_4[idx]
height_rgb = np.swapaxes(height_rgb, 0, 1)
height_sem = np.swapaxes(height_sem, 0, 1)
height_sem\
= np.eye(self.num_channel)[height_sem.flatten()].reshape((height_rgb.shape[0], height_rgb.shape[1], self.num_channel))
height_sem = torch.from_numpy(height_sem).permute(2, 0, 1).unsqueeze(0).float()
return height_rgb, height_sem
# ignore: start from 1
def append(self, quaternion, translation, observations, raw_semantics=None):
# transform camera -> location in world
rotation = as_rotation_matrix(quaternion)
T_world = np.eye(4)
T_world[0:3, 0:3] = rotation
T_world[0:3, 3] = translation
# get points rgbs, depths and semantics
points = generate_pc(T_world, observations['depth'], self.fov)
rgbs = color2local3d(observations['rgb'])
# use system semantic observation or user semantic observation
if raw_semantics is None:
# get gt semantic sensor input
semantics = observations['semantic'].flatten()
# map from objId to category [0, num_channel-1]
semantics = np.vectorize(lambda x: self.id2cat.get(x,\
self.num_channel))(semantics)
semantics -= 1
semantics[((semantics < 0) | (semantics >= self.num_channel))] = self.num_channel - 1
else:
semantics = raw_semantics.flatten()
# ignore certain category
valid = None
for ctg in self.ignore:
if valid is None:
valid = (semantics != (ctg - 1))
else:
valid = valid & (semantics != (ctg - 1))
points = points[valid, :]
rgbs = rgbs[valid, :]
semantics = semantics[valid]
# ignore roof/ ground points
no_roof = (points[:, 1] < self.roof_thre) & (points[:, 1] > self.floor_thre)
points = points[no_roof, : ]
rgbs = rgbs[no_roof, : ]
semantics = semantics[no_roof]
if self.points is None:
self.markers = [len(points)]
self.points = points
self.rgbs = rgbs
self.semantics = semantics
else:
# remember the newest observation
self.points = np.concatenate((self.points, points), axis=0)
self.rgbs = np.concatenate((self.rgbs, rgbs), axis=0)
self.semantics = np.concatenate((self.semantics, semantics), axis=0)
self.markers.append(len(self.points))
if self.pano:
self.ready_counter = self.ready_counter + 1
if self.ready_counter == 4:
if len(self.markers) == 4:
self.markers = [self.markers[-1]]
else:
self.markers = self.markers[:-4] + [self.markers[-1]]
self.ready_counter = 0
if not self.aggregate:
if self.ready_counter == 0 and len(self.markers) > 1:
self.points = self.points[self.markers[0]:]
self.rgbs = self.rgbs[self.markers[0]:]
self.semantics = self.semantics[self.markers[0]:]
self.markers = self.markers[1:]
# forget the oldest observation
if self.ready_counter == 0 and len(self.markers) > 1 and len(self.markers) == self.memory_size + 1:
# forget the oldest observation
self.points = self.points[self.markers[0]:]
self.rgbs = self.rgbs[self.markers[0]:]
self.semantics = self.semantics[self.markers[0]:]
# update memory markers
for it in range(1, len(self.markers)):
self.markers[it] = self.markers[it] - self.markers[0]
self.markers = self.markers[1:]
class Memory_gpu(Memory):
def __init__(self,
aggregate,
memory_size,
pano,
num_channel,
id2cat,
roof_thre,
floor_thre,
ignore,
device,
fov=np.pi / 2.,
):
super(Memory_gpu, self).__init__(aggregate, memory_size,
pano, num_channel, id2cat, roof_thre, floor_thre,
ignore, fov)
self.device = device
def get_height_map(self, quaternion, translation, area_x, area_z, h, w):
if self.pano:
assert self.ready_counter ==0, "memory accumulating for pano case"
assert len(self.markers) > 0, "Cannot view an empty memory"
rotation = as_rotation_matrix(quaternion)
T_world = np.eye(4)
T_world[0:3, 0:3] = rotation
T_world[0:3, 3] = translation
T_world = torch.from_numpy(T_world)
cam = torch.cat((self.points.float(), torch.ones(self.points.shape[0],
1).to(self.device).float()),
dim=1).cpu()
cam = torch.mm(cam, torch.inverse(T_world.t()).float()).to(self.device)
pointss = cam[:, 0:3]
round_agent = (torch.abs(pointss[:, 0]) < area_x / 2.)\
& (torch.abs(pointss[:, 2]) < area_z / 2.)
pointss = pointss[round_agent, :]
scale_h = area_z / h
scale_w = area_x / w
X = (pointss[:, 0:1] + (area_x / 2.)) / float(scale_w)
Y = pointss[:, 1:2]
Z = (pointss[:, 2:3] + (area_z / 2.)) / float(scale_h)
XZ_ff = torch.cat((torch.floor(X), torch.floor(Z)), dim=1)
XZ_fc = torch.cat((torch.floor(X), torch.ceil(Z)), dim=1)
XZ_cc = torch.cat((torch.ceil(X), torch.ceil(Z)), dim=1)
XZ_cf = torch.cat((torch.ceil(X), torch.floor(Z)), dim=1)
XZ = torch.cat((torch.cat((XZ_ff, XZ_fc), dim=0),
torch.cat((XZ_cc, XZ_cf), dim=0)), dim=0)
assert h == w, "Currently only support square!"
XZ[XZ >= h] = h - 1.
XZ[XZ < 0.] = 0.
Y = torch.cat((Y, Y), dim=0)
Y = torch.cat((Y, Y), dim=0)
XYZ = torch.cat((XZ, Y), dim=1)
sort_ind =torch.argsort(XYZ[..., 2])
XYZ = XYZ[sort_ind].long()
height_sem = torch.ones(h, w, device=self.device) * (self.num_channel - 1)
height_sem = height_sem.int()
semanticss = torch.cat((self.semantics[round_agent],
self.semantics[round_agent]), dim=0)
semanticss = torch.cat((semanticss, semanticss), dim=0)
semanticss = semanticss.int()
semanticss = semanticss[sort_ind]
height_sem[XYZ[:, 0], XYZ[:, 1]] = semanticss[:]
height_sem = torch.rot90(height_sem, 3, [0, 1])
height_sem = torch.flip(height_sem, [1])
height_sem = F.one_hot(height_sem.long(), num_classes=self.num_channel)
height_sem = height_sem.reshape((h,
w, self.num_channel))
height_sem = height_sem.permute(2, 0, 1).unsqueeze(0).float().cpu()
pointss, X, Y, Z, XZ_ff, XZ_fc, XZ_cc, XZ_cf =\
pointss.cpu(), X.cpu(), Y.cpu(),\
Z.cpu(), XZ_ff.cpu(),\
XZ_fc.cpu(), XZ_cc.cpu(),\
XZ_cf.cpu()
XYZ, semanticss = XYZ.cpu(), semanticss.cpu()
T_world, cam, round_agent = T_world.cpu(), cam.cpu(), round_agent.cpu()
return None, height_sem
def append(self, quaternion, translation, observations, raw_semantics=None):
# transform camera -> location in world
rotation = as_rotation_matrix(quaternion)
T_world = np.eye(4)
T_world[0:3, 0:3] = rotation
T_world[0:3, 3] = translation
T_world = torch.from_numpy(T_world)
# get points rgbs, depths and semantics
depth = observations['depth'][..., 0]
depth = torch.from_numpy(depth).to(self.device)
h, w = depth.shape
f = float(0.5 / np.tan(self.fov / 2.) * float(w))
x = torch.linspace(0, w-1, w)
y = torch.linspace(0, h-1, h)
xv, yv = torch.meshgrid(x, y)
xv, yv = xv.t().to(self.device), yv.t().to(self.device)
dfl = depth.reshape(-1)
points = torch.cat((\
(dfl * (xv.reshape(-1) - w / 2.) / f).unsqueeze(-1),\
- (dfl * (yv.reshape(-1) - h / 2.) / f).unsqueeze(-1),\
- dfl.unsqueeze(-1)), dim=1)
cam = torch.cat((points, torch.ones((points.shape[0],
1)).to(self.device)),
dim=1).cpu()
cam = torch.mm(cam, T_world.t().float()).to(self.device)
points = cam[:, 0:3]
# use system semantic observation or user semantic observation
if raw_semantics is None:
# get gt semantic sensor input
semantics = observations['semantic'].flatten()
# map from objId to category [0, num_channel-1]
semantics = np.vectorize(lambda x: self.id2cat.get(x,\
self.num_channel))(semantics)
semantics = torch.from_numpy(semantics).to(self.device)
semantics -= 1
semantics[((semantics < 0) | (semantics >= self.num_channel))] = self.num_channel - 1
else:
semantics\
= torch.from_numpy(raw_semantics).to(self.device).flatten()
# ignore certain category
valid = None
for ctg in self.ignore:
if valid is None:
valid = (semantics != (ctg - 1))
else:
valid = valid & (semantics != (ctg - 1))
points = points[valid, :]
semantics = semantics[valid]
# ignore roof/ ground points
no_roof = (points[:, 1] < self.roof_thre) & (points[:, 1] > self.floor_thre)
points = points[no_roof, : ]
semantics = semantics[no_roof]
if self.points is None:
self.markers = [points.shape[0]]
self.points = points.clone()
self.semantics = semantics.clone()
else:
# remember the newest observation
self.points = torch.cat((self.points, points), dim=0)
self.semantics = torch.cat((self.semantics, semantics), dim=0)
self.markers.append(self.points.shape[0])
if self.pano:
self.ready_counter = self.ready_counter + 1
if self.ready_counter == 4:
if len(self.markers) == 4:
self.markers = [self.markers[-1]]
else:
self.markers = self.markers[:-4] + [self.markers[-1]]
self.ready_counter = 0
if not self.aggregate:
if self.ready_counter == 0 and len(self.markers) > 1:
self.points = self.points[self.markers[0]:]
self.semantics = self.semantics[self.markers[0]:]
self.markers = self.markers[1:]
# forget the oldest observation
if self.ready_counter == 0 and len(self.markers) > 1 and len(self.markers) == self.memory_size + 1:
# forget the oldest observation
self.points = self.points[self.markers[0]:]
self.semantics = self.semantics[self.markers[0]:]
# update memory markers
for it in range(1, len(self.markers)):
self.markers[it] = self.markers[it] - self.markers[0]
self.markers = self.markers[1:]
valid, no_roof, points, semantics = valid.cpu(), no_roof.cpu(), points.cpu(), semantics.cpu()
T_world, depth, dfl, xv, yv, cam = T_world.cpu(), depth.cpu(), dfl.cpu(), xv.cpu(), yv.cpu(), cam.cpu()
class SCNavAgent:
def __init__(
self,
device,
config_paths,
flip,
pano,
user_semantics,
seg_pretrained,
cmplt,
cmplt_pretrained,
conf,
conf_pretrained,
targets,
aggregate,
memory_size,
num_channel,
success_threshold,
collision_threshold,
ignore,
training,
Q_pretrained,
offset,
floor_threshold,
lr,
momentum,
weight_decay,
gamma,
batch_size,
buffer_size,
height,
area_x,
area_z,
h,
w,
h_new,
w_new,
max_step,
navigable_base,
success_reward,
step_penalty,
approach_reward,
collision_penalty,
save_dir,
scene_types,
max_dist,
double_dqn,
TAU,
preconf,
seg_threshold,
current_position,
min_dist=0.,
shortest=False,
new_eval=False,
fake_conf=False,
discrete=False,
att=False,
rc=False,
unconf=False,
full_map=False,
num_local=25,
adj=11
):
self.adj = adj
self.num_local = num_local
self.new_eval = new_eval
assert self.new_eval, "Only support challenge setting!"
self.shortest = shortest
self.min_dist = min_dist
self.TAU = TAU
self.double_dqn = double_dqn
self.scene_types = scene_types.split("|")
self.max_dist = max_dist
self.seg_threshold = seg_threshold
self.success_reward = success_reward
self.step_penalty = step_penalty
self.approach_reward = approach_reward
self.collision_penalty = collision_penalty
self.rc = rc
self.unconf = unconf
if self.unconf:
assert fake_conf, "currently only one-hot completion when fake confidence map is provided"
self.batch_size = batch_size
self.device = device
self.save_dir = save_dir
# create environment
# disable habitat's metrics
config = habitat.get_config(config_paths=config_paths)
config.defrost()
config.TASK.SUCCESS_DISTANCE = -float("inf")
config.ENVIRONMENT.MAX_EPISODE_STEPS = float("inf")
config.ENVIRONMENT.MAX_EPISODE_SECONDS = float("inf")
config.freeze()
self.env = habitat.Env(config=config)
self.num_channel = num_channel
self.ignore = ignore.split("|")
self.ignore = [int(ig) for ig in self.ignore]
self.offset = offset
self.floor_threshold = floor_threshold
self.success_threshold = success_threshold
self.collision_threshold = collision_threshold
self.user_semantics = user_semantics
self.max_step = max_step
if self.new_eval:
self.max_step = 500
self.navigable_base = navigable_base.split("|")
self.navigable_base = [int(base) for base in self.navigable_base]
if user_semantics:
self.seg_model = ACNet(num_class = num_channel - 1)
self.seg_model.load_state_dict(torch.load(seg_pretrained))
self.seg_model = torch.nn.DataParallel(self.seg_model).to(device)
self.seg_model.eval()
self.cmplt = cmplt
self.fake_conf = fake_conf
self.conf = conf
if cmplt:
self.cmplt_model = ResNet(Bottleneck, DeconvBottleneck,
layer_infos, num_channel).to(device)
self.cmplt_model.load_state_dict(torch.load(cmplt_pretrained))
self.cmplt_model = torch.nn.DataParallel(self.cmplt_model)
self.cmplt_model.eval()
if conf and not self.fake_conf:
self.conf_model = ResNet(Bottleneck, DeconvBottleneck,
layer_infos, num_channel, inp=1).to(device)
self.conf_model.load_state_dict(torch.load(conf_pretrained))
self.conf_model = torch.nn.DataParallel(self.conf_model)
self.conf_model.eval()
self.pano = pano
self.discrete = discrete
self.att = att
if discrete:
self.Q\
= Q_discrete(self.num_channel, (not att and conf) or
self.fake_conf, preconf=preconf)
else:
self.Q\
= QNet(self.num_channel, (not att and conf) or self.fake_conf,
rc=rc, preconf=preconf)
if Q_pretrained != "":
state_dict = torch.load(Q_pretrained)
own_state = self.Q.state_dict()
try:
for name, param in state_dict.items():
if name not in own_state:
continue
own_state[name].copy_(param)
except:
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[7:] # remove `module.`
new_state_dict[name] = v
for name, param in state_dict.items():
if name not in own_state:
continue
own_state[name].copy_(param)
self.Q = torch.nn.DataParallel(self.Q).to(device)
self.training = training
if training:
if discrete:
self.Q_t\
= Q_discrete(self.num_channel, (not att and conf) or self.fake_conf,
preconf=preconf)
else:
self.Q_t\
= QNet(self.num_channel, (not att and conf) or self.fake_conf,
rc=rc, preconf=preconf)
self.Q_t.load_state_dict(self.Q.module.state_dict())
self.Q_t.eval()
self.optimizer = optim.SGD(self.Q.parameters(), lr=lr,
momentum=momentum, weight_decay=weight_decay)
self.gamma = gamma
self.Q_t = torch.nn.DataParallel(self.Q_t).to(device)
else:
self.Q.eval()
self.targets = targets.split("|")
self.aggregate = aggregate
self.memory_size = memory_size
self.replay_buffer = replay_buffer(buffer_size, save_dir,
current_position)
self.height = height
self.area_x = area_x
self.area_z = area_z
self.h = h
self.w = w
self.h_new = h_new
self.w_new = w_new
self.d2x = np.zeros((480, 640, 1))
for i in range(480):
for j in range(640):
self.d2x[i, j, 0] =np.sqrt(3) / 2. + (240. - i) /640.
self.mapper = Mapper(self.device, 1024, 1024, 48., 48.,
self.num_channel - 1, np.pi / 2., self.ignore)
# every episode
self.memory = None
self.target = None
self.target_map = None
self.target_objects = []
self.target_radiuss = []
self.target_positions = []
self.best_path_length = float("inf")
self.path_length = 0.
self.eps_len = 0.
self.reward = 0.
self.action = None
self.raw_semantics = None
self.current_obs = None
self.cmplted_obs = None
self.conf_obs = None
self.old_state = None
self.state = None
self.q_map = None
self.obstacle = None
self.action_list = []
self.done = False
self.success = False
self.image = None
self.depth = None
self.navigable = None
self.flip = flip
self.episode = None
self.full_map = full_map
def embedding(self, target):
embed = torch.zeros(1, self.num_channel, self.h, self.w)
embed[:, target, ...] = 1
return embed
# reset: create a new episode and restart
# target: object name
def reset_config(self, config):
# randomly choose a target if no specific target is given
self.target = config['target']
# find a valid habitat episode setting to start with
# valid: at least one target object reachable
# and no one target is too close
start_position = [float(pos) for pos in config['start_position']]
start_rotation = [float(rot) for rot in config['start_rotation']]
scene_id = config['scene_id']
if not self.new_eval:
start_rotation.reverse()
self.episode = NavigationEpisode(
goals= [],
episode_id="0",
scene_id=scene_id,
start_position=start_position,
start_rotation=start_rotation
)
else:
self.episode = ObjectGoalNavEpisode(
goals = [],
episode_id='0',
scene_id=scene_id,
start_position=start_position,
start_rotation=start_rotation,
)
self.env.episode_iterator = iter([
self.episode
])
self.env.reset()
# pick a target candidate for this episode
candidate_targets = [obj.category.name() for obj in
self.env.sim.semantic_annotations().objects if
obj.category.name() in self.targets]
self.target_objects = []
self.target_radiuss = []
self.target_positions = []
self.best_path_length = float("inf")
for obj in self.env.sim.semantic_annotations().objects:
if obj.category.name() == self.target:
distance = self.env.sim.geodesic_distance(start_position,
obj.aabb.center)
radius = np.sqrt(obj.aabb.sizes[0]**2\
+ obj.aabb.sizes[2]**2)/2.
if distance < float("inf"):
self.best_path_length = min(distance
- self.success_threshold,
self.best_path_length)
self.target_objects.append(int(obj.id.split("_")[-1]))
self.target_radiuss.append(radius)
self.target_positions.append(obj.aabb.center)
if self.new_eval:
self.best_path_length = config['best_path_length']
self.env.step("LOOK_DOWN")
roof_thre = start_position[1] + self.height/2. + self.offset
floor_thre = start_position[1] - self.height/2. - self.floor_threshold
id2cat = {int(obj.id.split("_")[-1]): obj.category.index() for obj in
self.env.sim.semantic_annotations().objects}
if self.full_map:
self.mapper.reset(id2cat, roof_thre, floor_thre)
else:
self.memory = Memory_gpu(self.aggregate, self.memory_size, self.pano,
self.num_channel, id2cat, roof_thre, floor_thre,
ignore=self.ignore, device=self.device)
self.id2cat = id2cat
# name2id: map from "sofa" to sofa's int id
# id: [0, 1, 2, ... 40]
self.target = name2id[self.target]
# embed target as part of state
self.target_map = self.embedding(self.target)
self.reward = 0.
self.action = None
self.current_obs = None
self.cmplted_obs = None
self.conf_obs = None
self.raw_semantics = None
self.state = None
self.old_state = None
self.q_map = None
self.done = False
self.success = False
self.image = None
self.depth = None
self.navigable = self.navigable_base + [self.target]
self.eps_len = 0.
self.path_length = 0.
self.view()
# reset: create a new episode and restart
# target: object name
def reset(self, target=None):
# randomly choose a target if no specific target is given
self.target = None
if target is not None:
self.target = target
# find a valid habitat episode setting to start with
# valid: at least one target object reachable
# and no one target is too close
random_heading = np.random.uniform(-np.pi, np.pi)
start_rotation = [
0,
np.sin(random_heading / 2),
0,
np.cos(random_heading / 2),
]
while True:
# change house by certain probability
if self.episode is None or random.random() < self.flip:
self.episode = random.choice(self.env.episodes)
self.env.episode_iterator = iter([NavigationEpisode(
goals=[],
episode_id="0",
scene_id=self.episode.scene_id,
start_position=self.episode.start_position,
start_rotation=self.episode.start_rotation)]
)
self.env.reset()
# pick a target candidate for this episode
candidate_targets = [obj.category.name() for obj in
self.env.sim.semantic_annotations().objects if
obj.category.name() in self.targets]
legal_rooms = [room.aabb for room in
self.env.sim.semantic_annotations().regions if
room.category.name() in self.scene_types]
# if no legal target to pick in this scene, remove episode
if len(candidate_targets) == 0:
self.episode = None
continue
if len(legal_rooms) == 0:
self.episode = None
continue
if self.target is not None:
if self.target not in candidate_targets:
self.episode = None
continue
for trial in range(100):
self.target_objects = []
self.target_radiuss = []
self.target_positions = []
self.best_path_length = float("inf")
edistance = float("inf")
if target is None:
self.target = random.choice(candidate_targets)
target_room = random.choice(legal_rooms)
start_position = [target_room.center[0]
+ (random.random() - 0.5) * abs(target_room.sizes[0]),
target_room.center[1] - abs(target_room.sizes[1]) / 2.,
target_room.center[2]
+ (random.random() - 0.5) * abs(target_room.sizes[2])]
if not self.env.sim.is_navigable(start_position):
continue
for obj in self.env.sim.semantic_annotations().objects:
if obj.category.name() == self.target:
distance = self.env.sim.geodesic_distance(start_position,
obj.aabb.center)
radius = np.sqrt(obj.aabb.sizes[0]**2\
+ obj.aabb.sizes[2]**2)/2.
cedistance =self.euclidean_distance(start_position,
obj.aabb.center)
# already in success state, illegal, start from very
# beginning
# or if min_dist is set, cannot be closer
if min(cedistance, distance) < radius + self.success_threshold + self.min_dist:
self.target_objects = []
self.target_radiuss = []
self.target_positions = []
self.best_path_length = float("inf")
edistance = float("inf")
break
if distance < float("inf"):
self.best_path_length = min(distance
- self.success_threshold,
self.best_path_length)
self.target_objects.append(int(obj.id.split("_")[-1]))
self.target_radiuss.append(radius)
self.target_positions.append(obj.aabb.center)
# update shortest euclidean distance
edistance = min(edistance, self.euclidean_distance(start_position,
obj.aabb.center))
if edistance < self.max_dist and len(self.target_objects) >= 1:
break
if edistance < self.max_dist and len(self.target_objects) >= 1:
break
self.env.sim.set_agent_state(position=start_position,
rotation=start_rotation)
self.env.step("LOOK_DOWN")
roof_thre = start_position[1] + self.height/2. + self.offset
floor_thre = start_position[1] - self.height/2. - self.floor_threshold
id2cat = {int(obj.id.split("_")[-1]): obj.category.index() for obj in
self.env.sim.semantic_annotations().objects}
if self.full_map:
self.mapper.reset(id2cat, roof_thre, floor_thre)
else:
self.memory = Memory_gpu(self.aggregate, self.memory_size, self.pano,
self.num_channel, id2cat, roof_thre, floor_thre,
ignore=self.ignore, device=self.device)
self.id2cat = id2cat
# name2id: map from "sofa" to sofa's int id
# id: [0, 1, 2, ... 40]
self.target = name2id[self.target]
# embed target as part of state
self.target_map = self.embedding(self.target)
self.reward = 0.