-
Notifications
You must be signed in to change notification settings - Fork 3
/
dal_ros_aml.py
4040 lines (3380 loc) · 168 KB
/
dal_ros_aml.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
#!/usr/bin/env python
from __future__ import print_function
import rospy
import actionlib
from move_base_msgs.msg import *
from utils import *
from random_box_map import *
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry
from geometry_msgs.msg import PoseStamped, Twist
from tf.transformations import *
import numpy as np
from scipy import ndimage, interpolate
from collections import OrderedDict
import pdb
import glob
import os
import multiprocessing
import errno
import re
import time
import random
import cv2
from recordtype import recordtype
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR
import torchvision
from torchvision import transforms
from torchvision.models.densenet import densenet121, densenet169, densenet201, densenet161
# from logger import Logger
from copy import deepcopy
from networks import policy_A3C
from resnet_pm import resnet18, resnet34, resnet50, resnet101, resnet152
from torchvision.models.resnet import resnet18 as resnet18s
from torchvision.models.resnet import resnet34 as resnet34s
from torchvision.models.resnet import resnet50 as resnet50s
from torchvision.models.resnet import resnet101 as resnet101s
from torchvision.models.resnet import resnet152 as resnet152s
from networks import intrinsic_model
import math
import argparse
from datetime import datetime
from maze import generate_map
import matplotlib.pyplot as plt
import matplotlib.colors as cm
from matplotlib.patches import Wedge
import matplotlib.gridspec as gridspec
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def shift(grid, d, axis=None, fill = 0.5):
grid = np.roll(grid, d, axis=axis)
if axis == 0:
if d > 0:
grid[:d,:] = fill
elif d < 0:
grid[d:,:] = fill
elif axis == 1:
if d > 0:
grid[:,:d] = fill
elif d < 0:
grid[:,d:] = fill
return grid
def softmax(w, t = 1.0):
e = np.exp(np.array(w) / t)
dist = e / np.sum(e)
return dist
def softermax(w, t = 1.0):
w = np.array(w)
w = w - w.min() + np.exp(1)
e = np.log(w)
dist = e / np.sum(e)
return dist
def normalize(x):
if x.min() == x.max():
return 0.0*x
x = x-x.min()
x = x/x.max()
return x
Pose2d = recordtype("Pose2d", "theta x y")
Grid = recordtype("Grid", "head row col")
class Lidar():
def __init__(self, ranges, angle_min, angle_max,
range_min, range_max, noise=0):
# self.ranges = np.clip(ranges, range_min, range_max)
self.ranges = np.array(ranges)
self.angle_min = angle_min
self.angle_max = angle_max
num_data = len(self.ranges)
self.angle_increment = (self.angle_max-self.angle_min)/num_data #math.increment
self.angles_2pi= np.linspace(angle_min, angle_max, len(ranges), endpoint=True) % (2*np.pi)
idx = np.argsort(self.angles_2pi)
self.ranges_2pi = self.ranges[idx]
self.angles_2pi = self.angles_2pi[idx]
class LocalizationNode(object):
def __init__(self, args):
self.skip_to_end = False
# self.wait_for_scan = False
self.scan_once = False
self.scan_bottom_once = False
self.scan_on = False
self.scan_ready = False
self.scan_bottom_ready = False
self.wait_for_move = False
self.robot_pose_ready = False
self.args = args
self.rl_test = False
self.start_time = time.time()
if (self.args.use_gpu) > 0 and torch.cuda.is_available():
self.device = torch.device("cuda" )
torch.set_default_tensor_type(torch.cuda.FloatTensor)
else:
self.device = torch.device("cpu")
torch.set_default_tensor_type(torch.FloatTensor)
# self.args.n_maze_grids
# self.args.n_local_grids
# self.args.n_lm_grids
self.init_fig = False
self.n_maze_grids = None
self.grid_rows = self.args.n_local_grids #self.args.map_size * self.args.sub_resolution
self.grid_cols = self.args.n_local_grids #self.args.map_size * self.args.sub_resolution
self.grid_dirs = self.args.n_headings
num_dirs = 1
num_classes = self.args.n_lm_grids ** 2 * num_dirs
final_num_classes = num_classes
if self.args.n_pre_classes is not None:
num_classes = self.args.n_pre_classes
else:
num_classes = final_num_classes
if self.args.pm_net == "none":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = None
elif self.args.pm_net == "densenet121":
#/home/sr2/keehong.seo/my_python/lib/python2.7/site-packages/torchvision/models/densenet.py
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = densenet121(pretrained = self.args.use_pretrained, drop_rate = self.args.drop_rate)
num_ftrs = self.perceptual_model.classifier.in_features # 1024
self.perceptual_model.classifier = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "densenet169":
#/home/sr2/keehong.seo/my_python/lib/python2.7/site-packages/torchvision/models/densenet.py
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = densenet169(pretrained = self.args.use_pretrained, drop_rate = self.args.drop_rate)
num_ftrs = self.perceptual_model.classifier.in_features # 1664
self.perceptual_model.classifier = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "densenet201":
#/home/sr2/keehong.seo/my_python/lib/python2.7/site-packages/torchvision/models/densenet.py
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = densenet201(pretrained = self.args.use_pretrained, drop_rate = self.args.drop_rate)
num_ftrs = self.perceptual_model.classifier.in_features # 1920
self.perceptual_model.classifier = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "densenet161":
#/home/sr2/keehong.seo/my_python/lib/python2.7/site-packages/torchvision/models/densenet.py
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = densenet161(pretrained = self.args.use_pretrained, drop_rate = self.args.drop_rate)
num_ftrs = self.perceptual_model.classifier.in_features # 2208
self.perceptual_model.classifier = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "resnet18s":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet18s(pretrained=self.args.use_pretrained)
num_ftrs = self.perceptual_model.fc.in_features
self.perceptual_model.fc = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "resnet34s":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet34s(pretrained=self.args.use_pretrained)
num_ftrs = self.perceptual_model.fc.in_features
self.perceptual_model.fc = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "resnet50s":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet50s(pretrained=self.args.use_pretrained)
num_ftrs = self.perceptual_model.fc.in_features
self.perceptual_model.fc = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "resnet101s":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet101s(pretrained=self.args.use_pretrained)
num_ftrs = self.perceptual_model.fc.in_features
self.perceptual_model.fc = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "resnet152s":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet152s(pretrained=self.args.use_pretrained)
num_ftrs = self.perceptual_model.fc.in_features
self.perceptual_model.fc = nn.Linear(num_ftrs, num_classes)
elif self.args.pm_net == "resnet18":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet18(num_classes = num_classes)
num_ftrs = self.perceptual_model.fc.in_features
elif self.args.pm_net == "resnet34":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet34(num_classes = num_classes)
num_ftrs = self.perceptual_model.fc.in_features
elif self.args.pm_net == "resnet50":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet50(num_classes = num_classes)
num_ftrs = self.perceptual_model.fc.in_features
elif self.args.pm_net == "resnet101":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet101(num_classes = num_classes)
num_ftrs = self.perceptual_model.fc.in_features
elif self.args.pm_net == "resnet152":
self.map_rows = 224
self.map_cols = 224
self.perceptual_model = resnet152(num_classes = num_classes)
num_ftrs = self.perceptual_model.fc.in_features # 2048
else:
raise Exception('pm-net required: resnet or densenet')
if self.args.RL_type == 0:
self.policy_model = policy_A3C(self.args.n_state_grids, 2+self.args.n_state_dirs, num_actions = self.args.num_actions)
elif self.args.RL_type == 1:
self.policy_model = policy_A3C(self.args.n_state_grids, 1+self.args.n_state_dirs, num_actions = self.args.num_actions)
elif self.args.RL_type == 2:
self.policy_model = policy_A3C(self.args.n_state_grids, 2*self.args.n_state_dirs, num_actions = self.args.num_actions, add_raw_map_scan = True)
self.intri_model = intrinsic_model(self.grid_rows)
## D.P. was here ##
# load models
if self.args.pm_model is not None:
state_dict = torch.load(self.args.pm_model)
new_state_dict = OrderedDict()
for k,v in state_dict.items():
if 'module.' in k:
name = k[7:]
else:
name = k
new_state_dict[name] = v
self.perceptual_model.load_state_dict(new_state_dict)
print ('perceptual model %s is loaded.'%self.args.pm_model)
if self.args.rl_model == "none":
self.args.rl_model = None
if self.args.rl_model is not None:
state_dict = torch.load(self.args.rl_model)
new_state_dict = OrderedDict()
for k,v in state_dict.items():
if 'module.' in k:
name = k[7:]
else:
name = k
new_state_dict[name] = v
self.policy_model.load_state_dict(new_state_dict)
print ('policy model %s is loaded.'%self.args.rl_model)
if self.args.ir_model is not None:
self.intri_model.load_state_dict(torch.load(self.args.ir_model))
print ('intri model %s is loaded.'%self.args.ir_model)
# change n-classes
if self.args.n_pre_classes is not None:
# resize the output layer:
new_num_classes = final_num_classes
if "resnet" in self.args.pm_net:
self.perceptual_model.fc = nn.Linear(self.perceptual_model.fc.in_features, new_num_classes, bias=True)
elif "densenet" in args.pm_net:
num_ftrs = self.perceptual_model.classifier.in_features
self.perceptual_model.classifier = nn.Linear(num_ftrs, new_num_classes)
print ('model: num_classes now changed to', new_num_classes)
# data parallel, multi GPU
# https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html
if self.device==torch.device("cuda") and torch.cuda.device_count()>0:
print ("Use", torch.cuda.device_count(), 'GPUs')
if self.perceptual_model != None:
self.perceptual_model = nn.DataParallel(self.perceptual_model)
self.policy_model = nn.DataParallel(self.policy_model)
self.intri_model = nn.DataParallel(self.intri_model)
else:
print ("Use CPU")
if self.perceptual_model != None:
self.perceptual_model.to(self.device)
self.policy_model.to(self.device)
self.intri_model.to(self.device)
#
if self.perceptual_model != None:
if self.args.update_pm_by == "NONE":
self.perceptual_model.eval()
else:
self.perceptual_model.train()
if self.args.update_rl:
self.policy_model.train()
else:
self.policy_model.eval()
self.min_scan_range, self.max_scan_range = self.args.scan_range #[0.1, 3.5]
self.prob=np.zeros((1,3))
self.values = []
self.log_probs = []
self.manhattans = []
self.xyerrs = []
self.manhattan = 0
self.rewards = []
self.intri_rewards = []
self.reward = 0
self.entropies = []
self.gamma = 0.99
self.tau = 0.95 #Are we sure?
self.entropy_coef = self.args.c_entropy
if self.args.update_pm_by == "NONE":
self.optimizer_pm = None
else:
self.optimizer_pm = torch.optim.Adam(list(self.perceptual_model.parameters()), lr=self.args.lrpm)
if self.args.schedule_pm:
self.scheduler_pm = StepLR(self.optimizer_pm, step_size=self.args.pm_step_size, gamma=self.args.pm_decay)
# self.scheduler_lp = ReduceLROnPlateau(self.optimizer_pm,
# factor = 0.5,
# patience = 2,
# verbose = True)
models = []
if self.args.update_pm_by=="RL" or self.args.update_pm_by=="BOTH":
models = models + list(self.perceptual_model.parameters())
if self.args.update_rl:
models = models + list(self.policy_model.parameters())
if self.args.update_ir:
models = models + list(self.intri_model.parameters())
if models==[]:
self.optimizer = None
print("WARNING: no model for RL")
else:
self.optimizer = torch.optim.Adam(models, lr=self.args.lrrl)
if self.args.schedule_rl:
self.scheduler_rl = StepLR(self.optimizer, step_size=self.args.rl_step_size, gamma=self.args.rl_decay)
self.pm_backprop_cnt = 0
self.rl_backprop_cnt = 0
self.step_count = 0
self.step_max = self.args.num[2]
self.episode_count = 0
self.acc_epi_cnt = 0
self.episode_max = self.args.num[1]
self.env_count = 0
self.env_max = self.args.num[0]
self.env_count = 0
self.next_bin = 0
self.done = False
if self.args.verbose>0:
print('maps, episodes, steps = %d, %d, %d'%(self.args.num[0], self.args.num[1], self.args.num[2]))
self.cx = torch.zeros(1,256) #Variable(torch.zeros(1, 256))
self.hx = torch.zeros(1,256) #Variable(torch.zeros(1, 256))
self.max_grad_norm = 40
map_side_len = 224 * self.args.map_pixel
self.xlim = (-0.5*map_side_len, 0.5*map_side_len)
self.ylim = (-0.5*map_side_len, 0.5*map_side_len)
self.xlim = np.array(self.xlim)
self.ylim = np.array(self.ylim)
self.map_width_meter = map_side_len
# decide maze grids for each env
# if self.args.maze_grids_range[0] == None:
# pass
# else:
# self.n_maze_grids = np.random.randint(self.args.maze_grids_range[0],self.args.maze_grids_range[1])
# self.hall_width = self.map_width_meter/self.n_maze_grids
# if self.args.thickness == None:
# self.obs_radius = 0.25*self.hall_width
# else:
# self.obs_radius = 0.5*self.args.thickness * self.hall_width
self.collision_radius = self.args.collision_radius #0.25 # robot radius for collision
self.longest = float(self.grid_dirs/2 + self.grid_rows-1 + self.grid_cols-1) #longest possible manhattan distance
self.cell_size = (self.xlim[1]-self.xlim[0])/self.grid_rows
self.heading_resol = 2*np.pi/self.grid_dirs
self.fwd_step_meters = self.cell_size*self.args.fwd_step
self.collision = False
self.sigma_xy = self.args.sigma_xy # self.cell_size * 0.05
self.cr_pixels = int(np.ceil(self.collision_radius / self.args.map_pixel))
self.front_margin_pixels = int(np.ceil((self.collision_radius+self.fwd_step_meters) / self.args.map_pixel)) # how many pixels robot moves forward per step.
self.side_margin_pixels = int(np.ceil(self.collision_radius / self.args.map_pixel))
self.scans_over_map = np.zeros((self.grid_rows,self.grid_cols,360))
self.scan_2d_low_tensor = torch.zeros((1,self.args.n_state_grids, self.args.n_state_grids),device=torch.device(self.device))
self.map_for_LM = np.zeros((self.map_rows, self.map_cols))
self.map_for_pose = np.zeros((self.grid_rows, self.grid_cols),dtype='float')
self.map_for_RL = torch.zeros((1,self.args.n_state_grids, self.args.n_state_grids),device=torch.device(self.device))
self.data_cnt = 0
self.explored_space = np.zeros((self.grid_dirs,self.grid_rows, self.grid_cols),dtype='float')
self.new_pose = False
self.new_bel = False
self.bel_list = []
self.scan_list = []
self.target_list = []
self.likelihood = torch.ones((self.grid_dirs,self.grid_rows, self.grid_cols),
device=torch.device(self.device),
dtype=torch.float)
self.likelihood = self.likelihood / self.likelihood.sum()
self.gt_likelihood = np.ones((self.grid_dirs,self.grid_rows,self.grid_cols))
self.gt_likelihood_unnormalized = np.ones((self.grid_dirs,self.grid_rows,self.grid_cols))
self.belief = torch.ones((self.grid_dirs,self.grid_rows, self.grid_cols),device=torch.device(self.device))
self.belief = self.belief / self.belief.sum()
self.prior = self.belief.detach().cpu().numpy()
self.bel_ent = (self.belief * torch.log(self.belief)).sum().detach()
# self.bel_ent = np.log(1.0/(self.grid_dirs*self.grid_rows*self.grid_cols))
self.loss_likelihood = [] # loss for training PM model
self.loss_ll=0
self.loss_policy = 0
self.loss_value = 0
self.turtle_loc = np.zeros((self.map_rows,self.map_cols))
self.policy_out = None
self.value_out = None
self.action_idx = -1
self.action_from_policy = -1
# what to do
# current pose: where the robot really is. motion incurs errors in pose
self.current_pose = Pose2d(0,0,0)
self.live_pose = Pose2d(0,0,0) # updated on-line from cbRobotPose
self.odom_pose = Pose2d(0,0,0) # updated from jay1/odom
self.map_pose = Pose2d(0,0,0) # updated from jay1/odom and transformed to map coordinates
self.goal_pose = Pose2d(0,0,0)
self.last_pose = Pose2d(0,0,0)
self.perturbed_goal_pose = Pose2d(0,0,0)
self.start_pose = Pose2d(0,0,0)
self.collision_pose = Pose2d(0,0,0)
self.believed_pose = Pose2d(0,0,0)
#grid pose
self.true_grid = Grid(head=0,row=0,col=0)
self.bel_grid = Grid(head=0,row=0,col=0)
self.collision_grid = Grid(head=0,row=0,col=0)
self.action_space = list(("turn_left", "turn_right", "go_fwd", "hold"))
self.action_str = 'none'
self.current_state = "new_env_pose"
self.obj_act = None
self.obj_rew = None
self.obj_err = None
self.obj_map = None
self.obj_robot = None
self.obj_heading = None
self.obj_robot_bel = None
self.obj_heading_bel = None
self.obj_pose = None
self.obj_scan = None
self.obj_gtl = None
self.obj_lik = None
self.obj_bel = None
self.obj_bel_prior = None
self.obj_bel_dist = None
self.obj_gtl_dist = None
self.obj_lik_dist = None
self.obj_collision = None
if self.args.save:
home=os.environ['HOME']
str_date_time = datetime.now().strftime('%Y%m%d-%H%M%S')
# 1. try create /logs/YYMMDD-HHMMSS-00
# 2. if exist create /logs/YYMMDD-HHMMSS-01, and so on
i = 0
dir_made=False
while dir_made==False:
# self.log_dir = os.path.join(home, anl_loc, 'logs/', str_date_time+'-%02d'%i)
# self.log_dir = os.path.join(home, self.args.save_loc, str_date_time+'-%02d'%i)
self.log_dir = os.path.join(self.args.save_loc, str_date_time+'-%02d'%i)
try:
os.mkdir(self.log_dir)
dir_made=True
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
i=i+1
if self.args.verbose > 0:
print ('new directory %s'%self.log_dir)
self.param_filepath = os.path.join(self.log_dir, 'param.txt')
with open(self.param_filepath,'w+') as param_file:
for arg in vars(self.args):
param_file.write('<%s=%s> '%(arg, getattr(self.args, arg)))
if self.args.verbose > -1:
print ('parameters saved at %s'%self.param_filepath)
self.log_filepath = os.path.join(self.log_dir, 'log.txt')
self.rollout_list = os.path.join(self.log_dir, 'rollout_list.txt')
self.pm_filepath = os.path.join(self.log_dir, 'perceptual.model')
self.rl_filepath = os.path.join(self.log_dir, 'rl.model')
self.ir_filepath = os.path.join(self.log_dir, 'ir.model')
self.data_path = os.path.join(self.log_dir, 'data')
self.fig_path = os.path.join(self.log_dir, 'figures')
# if self.args.save_data:
try:
os.mkdir(self.data_path)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
if self.args.figure:
try:
os.mkdir(self.fig_path)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
self.twist_msg_move = Twist()
self.twist_msg_move.linear.x = 0
self.twist_msg_move.linear.y = 0
self.twist_msg_move.angular.z = 0
self.twist_msg_stop = Twist()
self.twist_msg_stop.linear.x = 0
self.twist_msg_stop.linear.y = 0
self.twist_msg_stop.angular.z = 0
#Subscribers
#self.sub_map = rospy.Subscriber('map', OccupancyGrid, self.cbMap, queue_size = 1)
# self.sub_odom = rospy.Subscriber('odom', Odometry, self.cbOdom, queue_size
# = 1)
self.dal_pose = PoseStamped()
self.pose_seq_cnt = 0
if self.args.gazebo:
self.sub_laser_scan = rospy.Subscriber('scan', LaserScan, self.cbScan, queue_size = 1)
self.pub_cmdvel = rospy.Publisher('cmd_vel', Twist, queue_size = 1)
self.pub_dalpose = rospy.Publisher('dal_pose', PoseStamped, queue_size = 1)
# self.sub_odom = rospy.Subscriber('odom', Odometry, self.cbOdom, queue_size = 1)
elif self.args.jay1:
self.pub_cmdvel = rospy.Publisher('jay1/cmd_vel', Twist, queue_size = 1)
self.pub_dalpose = rospy.Publisher('dal_pose', PoseStamped, queue_size = 1)
self.sub_laser_scan = rospy.Subscriber('jay1/scan', LaserScan, self.cbScanTop, queue_size = 1)
self.sub_laser_scan = rospy.Subscriber('jay1/scan1', LaserScan, self.cbScanBottom, queue_size = 1)
self.sub_robot_pose = rospy.Subscriber('jay1/robot_pose', PoseStamped, self.cbRobotPose, queue_size = 1)
self.sub_odom = rospy.Subscriber('jay1/odom', Odometry, self.cbOdom, queue_size = 1)
self.client = actionlib.SimpleActionClient('jay1/move_base', MoveBaseAction)
self.client.wait_for_server()
rospy.loginfo("Waiting for move_base action server...")
wait = self.client.wait_for_server(rospy.Duration(5.0))
if not wait:
rospy.logerr("Action server not available!")
rospy.signal_shutdown("Action server not available!")
exit()
rospy.loginfo("Connected to move base server")
rospy.loginfo("Starting goals achievements ...")
if self.args.gazebo or self.args.jay1:
rospy.Timer(rospy.Duration(self.args.timer), self.loop_jay)
self.max_turn_rate = 1.0
self.turn_gain = 10
self.fwd_err_margin = 0.005
self.ang_err_margin = math.radians(0.2)
self.fsm_state = "init"
#end of init
def loop(self):
if self.current_state == "new_env_pose":
### place objects in the env
self.clear_objects()
if self.args.load_map == None:
self.set_maze_grid()
self.set_walls()
elif self.args.load_map == 'randombox':
self.random_box()
else:
self.read_map()
self.map_for_LM = fill_outer_rim(self.map_for_LM, self.map_rows, self.map_cols)
if self.args.distort_map:
self.map_for_LM = distort_map(self.map_for_LM, self.map_rows, self.map_cols)
self.make_low_dim_maps()
if self.args.gtl_off == False:
self.get_synth_scan_mp(self.scans_over_map, map_img=self.map_for_LM, xlim=self.xlim, ylim=self.ylim) # generate synthetic scan data over the map (and directions)
self.reset_explored()
placed = self.place_turtle()
if placed:
self.current_state = "update_likelihood"
else:
print ("place turtle failed. retrying a new map")
return
if self.args.figure==True:
self.update_figure(newmap=True)
elif self.current_state == "new_pose":
self.reset_explored()
self.place_turtle()
self.current_state = "update_likelihood"
elif self.current_state == "update_likelihood":
self.get_lidar()
self.update_explored()
if self.step_count == 0:
self.save_roll_out = self.args.save & np.random.choice([False, True], p=[1.0-self.args.prob_roll_out, self.args.prob_roll_out])
if self.save_roll_out:
#save roll-out for next episode.
self.roll_out_filepath = os.path.join(self.log_dir, 'roll-out-%03d-%03d.txt'%(self.env_count,self.episode_count))
print ('roll-out saving: %s'%self.roll_out_filepath)
self.scan_2d, self.scan_2d_low = self.get_scan_2d_n_headings(self.scan_data, self.xlim, self.ylim)
self.slide_scan()
### 2. update likelihood from observation
self.compute_gtl(self.scans_over_map)
if self.args.generate_data: # end the episode ... (no need for measurement/motion model)
self.generate_data()
if self.args.figure:
self.update_figure()
plt.pause(1e-4)
self.next_step()
return
self.likelihood = self.update_likelihood_rotate(self.map_for_LM, self.scan_2d)
if self.args.mask:
self.mask_likelihood()
#self.likelihood.register_hook(print)
### z(t) = like x belief
### z(t) = like x belief
# if self.collision == False:
self.product_belief()
### reward r(t)
self.update_bel_list()
self.get_reward()
### action a(t) given s(t) = (z(t)|Map)
if self.args.verbose>0:
self.report_status(end_episode=False)
if self.save_roll_out:
self.collect_data()
if self.args.figure:
self.update_figure()
self.run_action_module()
if self.skip_to_end:
self.skip_to_end = False
self.next_ep()
return
### environment: set target
self.update_target_pose()
# do the rest: ation, trans-belief, update gt
self.collision_check()
self.execute_action_teleport()
### environment: change belief z_hat(t+1)
self.transit_belief()
### increase time step
# self.update_current_pose()
if self.collision == False:
self.update_true_grid()
## Prior ##
# if self.args.figure:
# ax=self.ax_prior
# self.update_prior_plot(ax)
# ax=self.ax_map
# self.draw_robot(ax)
# self.draw_bel(ax)
# self.draw_collision(ax, self.collision)
# ax=self.ax_pose
# self.update_pose_plot(ax)
# plt.pause(1e-3)
self.next_step()
return
else:
print("undefined state name %s"%self.current_state)
self.current_state = None
exit()
return
def get_statistics(self, dis, name):
DIRS = 'NWSE'
this=[]
for i in range(self.grid_dirs):
# this.append('%s(%s%1.3f,%s%1.3f,%s%1.3f%s)'\
# %(DIRS[i], bcolors.WARNING,100*dis[i,:,:].max(),
# bcolors.OKGREEN,100*dis[i,:,:].median(),
# bcolors.FAIL,100*dis[i,:,:].min(),bcolors.ENDC))
this.append(' %s(%1.2f,%1.2f,%1.2f)'\
%(DIRS[i], 100*dis[i,:,:].max(),
100*dis[i,:,:].median(),
100*dis[i,:,:].min()))
return name+':%19s|%23s|%23s|%23s|'%tuple(this[th] for th in range(self.grid_dirs))
def circular_placement(self, x, n):
width = x.shape[2]
height = x.shape[1]
N = (n/2+1)*max(width,height)
img = np.zeros((N,N))
for i in range(n):
if i < n/4:
origin = (i, (n/4-i))
elif i < 2*n/4:
origin = (i, (i-n/4))
elif i < 3*n/4:
origin = (n-i, (i-n/4))
else:
origin = (n-i, n+n/4-i)
ox = origin[0]*height
oy = origin[1]*width
img[ox:ox+height, oy:oy+width] = x[i,:,:]
return img
def square_clock(self, x, n):
width = x.shape[2]
height = x.shape[1]
quater = n/4-1
#even/odd
even = 1 - quater % 2
side = quater+2+even
N = side*max(width,height)
img = np.zeros((N,N))
for i in range(n):
s = (i+n/8)%n
if s < n/4:
org = (0, n/4-s)
elif s < n/2:
org = (s-n/4+even, 0)
elif s < 3*n/4:
org = (n/4+even, s-n/2+even)
else:
org = (n/4-(s-3*n/4), n/4+even)
ox = org[0]*height
oy = org[1]*width
img[ox:ox+height, oy:oy+width] = x[i,:,:]
del x
return img, side
def draw_compass(self, ax):
cx = 0.9 * self.xlim[1]
cy = 0.9 * self.ylim[0]
lengthNS = self.xlim[1] * 0.1
lengthEW = self.ylim[1] * 0.075
theta = - self.current_pose.theta
Nx = cx + lengthNS * np.cos(theta)
Ny = cy + lengthNS* np.sin(theta)
Sx = cx + lengthNS * np.cos(theta+np.pi)
Sy = cy + lengthNS * np.sin(theta+np.pi)
Ni = to_index(Nx, self.map_rows, self.xlim)
Nj = to_index(Ny, self.map_cols, self.ylim)
Si = to_index(Sx, self.map_rows, self.xlim)
Sj = to_index(Sy, self.map_cols, self.ylim)
Ex = cx + lengthEW * np.cos(theta-np.pi/2)
Ey = cy + lengthEW * np.sin(theta-np.pi/2)
Wx = cx + lengthEW * np.cos(theta+np.pi/2)
Wy = cy + lengthEW * np.sin(theta+np.pi/2)
Ei = to_index(Ex, self.map_rows, self.xlim)
Ej = to_index(Ey, self.map_cols, self.ylim)
Wi = to_index(Wx, self.map_rows, self.xlim)
Wj = to_index(Wy, self.map_cols, self.ylim)
xdata = Sj, Nj, Wj, Ej
ydata = Si, Ni, Wi, Ei
if hasattr(self, 'obj_compass1'):
self.obj_compass1.update({'xdata':xdata, 'ydata':ydata})
else:
self.obj_compass1, = ax.plot(xdata, ydata, 'r', alpha = 0.5)
def draw_center(self, ax):
x = to_index(0, self.map_rows, self.xlim)
y = to_index(0, self.map_cols, self.ylim)
# radius = self.map_rows*0.4/self.grid_rows
radius = self.cr_pixels # self.collision_radius / (self.xlim[1]-self.xlim[0]) * self.map_rows
theta = 0-np.pi/2
xdata = y, y+radius*3*np.cos(theta)
ydata = x, x+radius*3*np.sin(theta)
obj_robot = Wedge((y,x), radius, 0, 360, color='r',alpha=0.5)
obj_heading, = ax.plot(xdata, ydata, 'r', alpha=0.5)
ax.add_artist(obj_robot)
def draw_collision(self, ax, collision):
if collision == False:
if self.obj_collision == None:
return
else:
self.obj_collision.update({'visible':False})
else:
x = to_index(self.collision_pose.x, self.map_rows, self.xlim)
y = to_index(self.collision_pose.y, self.map_cols, self.ylim)
radius = self.cr_pixels #self.collision_radius / (self.xlim[1]-self.xlim[0]) * self.map_rows
if self.obj_collision == None:
self.obj_collision = Wedge((y,x), radius, 0, 360, color='y',alpha=0.5, visible=True)
ax.add_artist(self.obj_collision)
else:
self.obj_collision.update({'center': [y,x], 'visible':True})
# self.obj_robot.set_data(self.turtle_loc)
# plt.pause(0.01)
def draw_robot(self, ax):
x = to_index(self.current_pose.x, self.map_rows, self.xlim)
y = to_index(self.current_pose.y, self.map_cols, self.ylim)
# radius = self.map_rows*0.4/self.grid_rows
radius = self.cr_pixels # self.collision_radius / (self.xlim[1]-self.xlim[0]) * self.map_rows
theta = -self.current_pose.theta-np.pi/2
xdata = y, y+radius*3*np.cos(theta)
ydata = x, x+radius*3*np.sin(theta)
if self.obj_robot == None:
#self.obj_robot = ax.imshow(self.turtle_loc, alpha=0.5, cmap=plt.cm.binary)
# self.obj_robot = ax.imshow(self.turtle_loc, alpha=0.5, cmap=plt.cm.Reds,interpolation='nearest')
self.obj_robot = Wedge((y,x), radius, 0, 360, color='r',alpha=0.5)
self.obj_heading, = ax.plot(xdata, ydata, 'r', alpha=0.5)
ax.add_artist(self.obj_robot)
else:
self.obj_robot.update({'center': [y,x]})
self.obj_heading.update({'xdata':xdata, 'ydata':ydata})
# self.obj_robot.set_data(self.turtle_loc)
# plt.pause(0.01)
def update_believed_pose(self):
o_bel,i_bel,j_bel = np.unravel_index(np.argmax(self.belief.cpu().detach().numpy(), axis=None), self.belief.shape)
x_bel = to_real(i_bel, self.xlim,self.grid_rows)
y_bel = to_real(j_bel, self.ylim,self.grid_cols)
theta = o_bel * self.heading_resol
self.believed_pose.x = x_bel
self.believed_pose.y = y_bel
self.believed_pose.theta = theta
self.publish_dal_pose(x_bel, y_bel, theta)
def publish_dal_pose(self,x,y,theta):
self.dal_pose.pose.position.x = -y
self.dal_pose.pose.position.y = x
self.dal_pose.pose.position.z = 0
quatern = quaternion_from_euler(0,0, theta+np.pi/2)
self.dal_pose.pose.orientation.x=quatern[0]
self.dal_pose.pose.orientation.y=quatern[1]
self.dal_pose.pose.orientation.z=quatern[2]
self.dal_pose.pose.orientation.w=quatern[3]
self.dal_pose.header.frame_id = 'map'
self.dal_pose.header.seq = self.pose_seq_cnt
self.pose_seq_cnt += 1
self.pub_dalpose.publish(self.dal_pose)
def update_map_T_odom(self):
map_pose = (self.believed_pose.x, self.believed_pose.y, self.believed_pose.theta)
odom_pose = (self.odom_pose.x, self.odom_pose.y, self.odom_pose.theta)
self.map_T_odom = define_tf(map_pose, odom_pose)
def draw_bel(self, ax):
o_bel,i_bel,j_bel = np.unravel_index(np.argmax(self.belief.cpu().detach().numpy(), axis=None), self.belief.shape)
x_bel = to_real(i_bel, self.xlim,self.grid_rows)
y_bel = to_real(j_bel, self.ylim,self.grid_cols)
x = to_index(x_bel, self.map_rows, self.xlim)
y = to_index(y_bel, self.map_cols, self.ylim)
# radius = self.map_rows*0.4/self.grid_rows
radius = self.cr_pixels # self.collision_radius / (self.xlim[1]-self.xlim[0]) * self.map_rows
theta = o_bel * self.heading_resol
theta = -theta-np.pi/2
xdata = y, y+radius*3*np.cos(theta)
ydata = x, x+radius*3*np.sin(theta)
if self.obj_robot_bel == None:
#self.obj_robot = ax.imshow(self.turtle_loc, alpha=0.5, cmap=plt.cm.binary)
# self.obj_robot = ax.imshow(self.turtle_loc, alpha=0.5, cmap=plt.cm.Reds,interpolation='nearest')
self.obj_robot_bel = Wedge((y,x), radius*0.95, 0, 360, color='b',alpha=0.5)
self.obj_heading_bel, = ax.plot(xdata, ydata, 'b', alpha=0.5)
ax.add_artist(self.obj_robot_bel)
else:
self.obj_robot_bel.update({'center': [y,x]})
self.obj_heading_bel.update({'xdata':xdata, 'ydata':ydata})
def init_figure(self):
self.init_fig = True
if self.args.figure == True:# and self.obj_fig==None:
self.obj_fig = plt.figure(figsize=(16,12))
plt.set_cmap('viridis')
self.gridspec = gridspec.GridSpec(3,5)
self.ax_map = plt.subplot(self.gridspec[0,0])
self.ax_scan = plt.subplot(self.gridspec[1,0])
self.ax_pose = plt.subplot(self.gridspec[2,0])
self.ax_bel = plt.subplot(self.gridspec[0,1])
self.ax_lik = plt.subplot(self.gridspec[1,1])
self.ax_gtl = plt.subplot(self.gridspec[2,1])