-
Notifications
You must be signed in to change notification settings - Fork 0
/
MBExperiment.py
2794 lines (2323 loc) · 125 KB
/
MBExperiment.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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from dotmap import DotMap
from scipy.io import savemat
from tqdm import trange
from Agent import Agent
import scipy.io as sio
import torch
import numpy as np
import rospy
import scipy.io as scio
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from replay_buffer import ReplayBuffer
from neural_nets import PPO_model,Conv_autoencoder
import time
from time import localtime, strftime
from tensorboardX import SummaryWriter
from normalization import Normalization, RewardScaling
cuda = torch.cuda.is_available()
TORCH_DEVICE = torch.device('cuda:0' if cuda else 'cpu')
class MBExperiment:
def __init__(self, params, env, policy, logger, meta = False):
"""Initializes class instance.
Argument:
params (DotMap): A DotMap containing the following:
.sim_cfg:
.env (gym.env): Environment for this experiment
.task_hor (int): Task horizon
.stochastic (bool): (optional) If True, agent adds noise to its actions.
Must provide noise_std (see below). Defaults to False.
.noise_std (float): for stochastic agents, noise of the form N(0, noise_std^2I)
will be added.
.exp_cfg:
.ntrain_iters (int): Number of training iterations to be performed.
.nrollouts_per_iter (int): (optional) Number of rollouts done between training
iterations. Defaults to 1.
.ninit_rollouts (int): (optional) Number of initial rollouts. Defaults to 1.
.policy (controller): Policy that will be trained.
.log_cfg:
.logdir (str): Parent of directory path where experiment data will be saved.
Experiment will be saved in logdir/<date+time of experiment start>
.nrecord (int): (optional) Number of rollouts to record for every iteration.
Defaults to 0.
.neval (int): (optional) Number of rollouts for performance evaluation.
Defaults to 1.
"""
# Assert True arguments that we currently do not support
# assert params.sim_cfg.get("stochastic", False) == False
self.env = env
self.task_hor = params.task_hor
self.log_sample_data = params.log_sample_data
self.horizon = params.plan_hor
# self.space_3d = rospy.get_param("/firefly/3d_space")
# print(self.wind_test_types)
self.meta = meta
#params of MBRL
if not meta:
self.agent = Agent(env)
self.ntrain_iters = params.ntrain_iters
self.nrollouts_per_iter = params.nrollouts_per_iter
self.ninit_rollouts = params.ninit_rollouts
self.neval = params.neval
else:
if not params.embedding:
#params of Meta learning
self.agent = Agent(env,meta=True)
self.meta_train_iters = params.meta_train_iters
self.meta_nrollouts_per_iter = params.meta_nrollouts_per_iter
self.k_spt = params.k_spt
self.k_qry = params.k_qry
self.load_model = params.load_model
self.running_total_points = params.running_total_points
self.abandon_samples = params.abandon_samples
else:
if params.VI:
pass
else:
self.agent = Agent(env,meta=True)
self.policy = policy
self.logger = logger
def run_experiment(self,training,path):
"""Perform model-based experiment.
"""
# seed 222,50,8,1,20,45,60,104,165,200
torch.manual_seed(200)
torch.cuda.manual_seed_all(200)
np.random.seed(200)
#task 1: wind 0.0 L 0.6
# task 2: wind 0.3 L 1.0
# task 3: wind 0.5 L 0.8
# task 4: wind 0.8 L 1.2
# test task 1: wind 1.0 L 0.8
# test task 2: wind 0.6 L 1.4
wind_condition_x = 0.6
wind_condition_y = 0.0
L = 1.4
if training:
# Perform initial rollouts
samples = []
mat_contents = sio.loadmat("/home/wawa/catkin_meta/src/MBRL_transport/firefly_data_3d_wind_x{0}_2agents_L{1}_dt_0.15.mat".format(wind_condition_x,L))
train_obs = mat_contents['obs']
train_acs = mat_contents['acs']
#samples [episode, steps,n]
self.policy.train(train_obs, train_acs,self.logger)
# Training loop
for i in trange(self.ntrain_iters):
print("####################################################################")
print("Starting training iteration %d." % (i + 1))
samples = []
#horizon, policy, wind_test_type, adapt_size=None, log_data=None, data_path=None
#MBRL is baseline no need to log data in agent sampling
for j in range(max(self.neval, self.nrollouts_per_iter)):
samples.append(
self.agent.sample(
self.task_hor, self.policy, wind_condition_x,wind_condition_y,L
)
)
# print("Rewards obtained:", [sample["reward_sum"] for sample in samples[:self.neval]])
self.logger.add_scalar('Reward', np.mean([sample["reward_average"] for sample in samples[:]]), i)
samples = samples[:self.nrollouts_per_iter]
if i < self.ntrain_iters - 1:
#add new samples into the whole dataset and train the whole dataset
self.policy.train(
[sample["obs"] for sample in samples],
[sample["ac"] for sample in samples],
self.logger
)
self.logger.close()
else:
sample = self.agent.sample(self.task_hor, self.policy, wind_condition_x,wind_condition_y, L, log_data=self.log_sample_data, data_path=path)
#if path_length of path i is less than k_spt+k_qry, we have to resample it
if self.log_sample_data:
print("start logging")
savemat(path+'/storeReward.mat', mdict={'arr': sample["rewards"]})
savemat(path+'/store_errorx.mat', mdict={'arr': sample["error_x"]})
savemat(path+'/store_errory.mat', mdict={'arr': sample["error_y"]})
savemat(path+'/store_errorz.mat', mdict={'arr': sample["error_z"]})
savemat(path+'/storeObs.mat', mdict={'arr': sample["obs"]})
data = scio.loadmat('/home/wawa/catkin_meta/src/MBRL_transport/current_waypoints.mat')
savemat(path+'/store_destraj.mat', mdict={'arr': data['arr']})
self.logger.close()
# def run_experiment_meta(self):
# """Perform meta experiment.
# we load the offline meta model and do the online training
# """
# torch.manual_seed(222)
# torch.cuda.manual_seed_all(222)
# np.random.seed(222)
# if not self.load_model:
# self.policy.offline_train(self.logger)
# for i in range(self.meta_train_iters):
# samples = []
# total_num = 0
# while total_num < self.running_total_points:
# #runing rollouts for collection samples for meta training
# chosen_winds = np.random.choice(self.wind_test_types,self.meta_nrollouts_per_iter,replace=False)
# for j in range(self.meta_nrollouts_per_iter):
# sample = self.agent.sample(self.task_hor, self.policy, chosen_winds[j], self.k_spt)
# #if path_length of path i is less than k_spt+k_qry, we have to resample it
# if sample['ac'].shape[0] > self.k_spt+self.k_qry:
# samples.append(sample)
# total_num += sample['ac'].shape[0]
# self.logger.add_scalar('Reward', np.mean([sample["reward_sum"] for sample in samples[:]]), i)
# self.policy.train_meta([sample["obs"] for sample in samples],
# [sample["ac"] for sample in samples], self.logger,i)
# self.logger.close()
# def test_experiment_meta(self):
# """Perform meta experiment.
# we load the offline meta model and do the online training
# """
# torch.manual_seed(222)
# torch.cuda.manual_seed_all(222)
# np.random.seed(222)
# samples = []
# #runing rollouts for collection samples for meta training
# chosen_winds = np.random.choice(self.wind_test_types,self.meta_nrollouts_per_iter,replace=False)
# for j in range(self.meta_nrollouts_per_iter):
# sample = self.agent.sample(self.task_hor, self.policy, chosen_winds[j], self.k_spt)
# samples.append(sample)
# self.logger.add_scalar('Reward', samples[j]["reward_sum"], j)
# self.logger.close()
def run_experiment_meta_without_online(self, path):
"""Perform meta experiment.
we load the offline meta model and without the online training, only one episode adaptation
"""
# seed 222,50,8,1,20,45,60,104,165,200
torch.manual_seed(222)
torch.cuda.manual_seed_all(222)
np.random.seed(222)
# if not self.load_model:
# self.policy.offline_train(self.logger)
#runing rollouts for collection samples for meta training
#task 1: wind 0.0 L 0.6
# task 2: wind 0.3 L 1.0
# task 3: wind 0.5 L 0.8
# task 4: wind 0.8 L 1.2
# test task 1: wind 1.0 L 0.8
# test task 2: wind 0.6 L 1.4
wind_condition_x = 1.0
wind_condition_y = 0.0
L = 0.8
sample = self.agent.sample(self.task_hor, self.policy, wind_condition_x,wind_condition_y, L, adapt_size = self.k_spt, log_data=self.log_sample_data, data_path=path)
#if path_length of path i is less than k_spt+k_qry, we have to resample it
if self.log_sample_data:
savemat(path+'/storeReward.mat', mdict={'arr': sample["rewards"]})
savemat(path+'/store_errorx.mat', mdict={'arr': sample["error_x"]})
savemat(path+'/store_errory.mat', mdict={'arr': sample["error_y"]})
savemat(path+'/store_errorz.mat', mdict={'arr': sample["error_z"]})
savemat(path+'/storeObs.mat', mdict={'arr': sample["obs"]})
data = scio.loadmat('/home/wawa/catkin_meta/src/MBRL_transport/current_waypoints.mat')
savemat(path+'/store_destraj.mat', mdict={'arr': data['arr']})
# savemat(path+'/storeAcs.mat', mdict={'arr': sample["ac"]})
# self.logger.add_scalar('Reward', sample["reward_sum"], 0)
##########
#plot results
# data = scio.loadmat('/home/wawa/catkin_meta/src/MBRL_transport/current_waypoints.mat')
# figure1 = plt.figure('figure1')
# plt.plot(sample["rewards"])
# plt.plot(sample["error_x"])
# plt.plot(sample["error_y"])
# plt.plot(sample["error_z"])
# plt.gca().legend(('Euclidean', 'x', 'y', 'z'))
# plt.title('position error')
# plt.xlabel('t')
# plt.ylabel('error(m)')
# figure2 = plt.figure('figure2')
# ax = figure2.gca(projection='3d')
# ax.plot3D(sample["obs"][:,6]*4,sample["obs"][:,7]*2,sample["obs"][:,8]*2, 'gray')
# ax.plot3D(data['arr'][:,0],data['arr'][:,1],data['arr'][:,2], 'r--')
# plt.title('3d trajectory')
# ax.set_xlabel('x(m)')
# ax.set_ylabel('y(m)')
# ax.set_zlabel('z(m)')
# # figure3 = plt.figure('figure3')
# # plt.plot(sample["prediction_error"])
# # plt.title('Prediction error')
# # plt.xlabel('t')
# # plt.ylabel('MSE')
# plt.show()
##########
self.logger.close()
# def run_experiment_meta_online1(self, path):
# """
# Correct actions
# Perform meta experiment.
# we load the offline meta model and without the online training, only one episode adaptation
# """
# torch.manual_seed(222)
# torch.cuda.manual_seed_all(222)
# np.random.seed(222)
# train_iters = 1600
# #ppo logger
# log_path_ppo = os.path.join("/home/wawa/catkin_meta/src/MBRL_transport/log_PPO_model",strftime("%Y-%m-%d--%H:%M:%S", localtime()))
# os.makedirs(log_path_ppo, exist_ok=True)
# logger_ppo = SummaryWriter(logdir=log_path_ppo) # used for tensorboard
# args = DotMap()
# # if not use image, change dimension
# args.with_image = False
# args.state_dim = 48
# args.action_dim = 3
# args.max_action = 0.1
# args.batch_size = 2048
# args.mini_batch_size = 64
# args.max_train_steps = train_iters * self.task_hor
# args.lr_a = 3e-4
# args.lr_c = 3e-4
# args.gamma = 0.99
# args.lamda = 0.95
# args.epsilon = 0.2
# args.K_epochs = 10
# args.entropy_coef = 0.005#0.01
# args.use_grad_clip = True
# args.use_lr_decay = True
# args.use_adv_norm = True
# # args.horizon = 1
# args.evaluate_s = 0
# #runing rollouts for collection samples for meta training
# wind_condition_x = 0.0
# wind_condition_y = 0.0
# L = 0.6
# replay_buffer = ReplayBuffer(args)
# ppo_agent = PPO_model(args,logger_ppo).to(TORCH_DEVICE)
# if args.with_image:
# act_encoder = Conv_autoencoder().to(TORCH_DEVICE)
# act_encoder.load_encoder()
# act_encoder.eval()
# adapt_size = self.k_spt
# log_data=self.log_sample_data
# data_path=path
# total_steps = 0
# evaluate_frequency = 20
# reward_index = 0
# reward_index_log = 0
# reward_repeat = []
# episode_n = 0
# repeat_eval = False
# # reward_scaling = RewardScaling(shape=1, gamma=args.gamma)
# if self.meta:
# self.adapt_buffer = dict(obs=[],act=[])
# self.env.wind_controller_x.publish(wind_condition_x)
# self.env.wind_controller_y.publish(wind_condition_y)
# else:
# self.env.wind_controller_x.publish(wind_condition_x)
# self.env.wind_controller_y.publish(wind_condition_y)
# for i in range(train_iters):
# if i == 1:
# if self.meta:
# self.policy.model.save_model(0,model_path=data_path)
# times, rewards = [], []
# errorx = []
# errory = []
# errorz = []
# self.env.set_L(L)
# o1, goal, g_s = self.env.reset()
# O, A, reward_sum, done = [o1], [], 0, False
# top_act_seq = []
# prediction_error = []
# # reward_scaling.reset()
# past_corrected_goals = [np.zeros((1,3))]
# past_traj = [np.zeros((1,15))]
# past_traj_error = [np.zeros((1,3))]
# if i>0:
# if args.with_image == True:
# g_map = torch.from_numpy(self.env.get_depth_map()).cuda().float()
# g_map_conv = g_map[None][None]
# d = act_encoder.encoder_forward(g_map_conv)
# O_t = torch.from_numpy(O[t]).cuda().float()
# s_all = torch.cat((d,O_t[None]),dim=1)
# assert s_all.shape[1]==72
# else:
# #normalize goal input in observation
# O_t = torch.from_numpy(o1).cuda().float()
# g_normalize_s = g_s.copy()
# g_normalize_s[:,0] = g_normalize_s[:,0]/4.0
# g_normalize_s[:,1] = g_normalize_s[:,1]/2.0
# g_normalize_s[:,2] = g_normalize_s[:,2]/2.0
# g_current = torch.from_numpy(g_normalize_s.reshape(1,-1)).cuda().float()
# # print("old:",past_traj[-1])
# g_normalize_past = past_traj[-1]
# g_normalize_past[:,0] = g_normalize_past[:,0]/4.0
# g_normalize_past[:,1] = g_normalize_past[:,1]/2.0
# g_normalize_past[:,2] = g_normalize_past[:,2]/2.0
# g_old = torch.from_numpy(g_normalize_past.reshape(1,-1)).cuda().float()
# g_normalize_past_c = past_corrected_goals[-1]
# g_normalize_past_c[:,0] = g_normalize_past_c[:,0]/2.0
# g_normalize_past_c[:,1] = g_normalize_past_c[:,1]/2.0
# g_normalize_past_c[:,2] = g_normalize_past_c[:,2]/2.0
# g_old_correct = torch.from_numpy(g_normalize_past_c.reshape(1,-1)).cuda().float()
# e_normalize_past = past_traj_error[-1]
# e_old = torch.from_numpy(e_normalize_past.reshape(1,-1)).cuda().float()
# s_all = torch.cat((O_t[None],g_current,g_old,g_old_correct,e_old),dim=1)
# assert s_all.shape[1]==12+15+15+3+3
# # if log_data:
# # obs1_l = []
# # obs2_l = []
# # obs1 = self.env.get_uav_obs()[0]
# # obs2 = self.env.get_uav_obs()[1]
# # obs1_l.append(obs1)
# # obs2_l.append(obs2)
# if i == 0:
# if self.meta:
# self.adapt_buffer['obs'].append(o1)
# self.policy.model.fast_adapted_params = None
# self.policy.reset()
# if (episode_n%evaluate_frequency==0 and episode_n!=0) and not repeat_eval:
# for t in range(self.task_hor):
# # if t>100:
# # self.env.wind_controller_x.publish(0.2)
# # self.env.wind_controller_y.publish(0.5) #for tesing the middle fault
# # self.env.set_L(0.8)
# # break
# start = time.time()
# action,act_l,store_top_s,store_bad_s = self.policy.act(O[t], t, goal) #[6,5,2] store top s
# a = ppo_agent.evaluate(s_all)
# a_correct = a.reshape(1,3).copy()
# past_corrected_goals.append(a_correct+action.reshape(1,3).copy())
# # print(g_s)
# past_traj.append(g_s.copy())
# action+=a
# # print(store_top_s)
# self.env.pub_action_sequence(store_top_s) #visualize top states in rviz, long traj needs to use stored model
# self.env.pub_action_sequence1(store_bad_s)
# A.append(action)
# top_act_seq.append(act_l)
# times.append(time.time() - start)
# obs, reward, done, (goal, g_s) = self.env.step(A[t])
# new_error_traj = np.zeros((1,3))
# new_error_traj[:,0] = reward['error_x']
# new_error_traj[:,1] = reward['error_y']
# new_error_traj[:,2] = reward['error_z']
# past_traj_error.append(new_error_traj)
# #reward process
# reward['reward'] = -reward['reward']**2
# # reward['reward'] = reward_scaling(reward['reward'])
# if args.with_image == True:
# if_obs = self.policy.occupancy_predictor(obs)
# # print(if_obs)
# #post process reward and done
# if if_obs:
# done = 1
# reward['reward']-=50
# if args.with_image == True:
# g_map1 = torch.from_numpy(self.env.get_depth_map()).cuda().float()
# g_map_conv1 = g_map1[None][None]
# d1 = act_encoder.encoder_forward(g_map_conv1)
# obs_t = torch.from_numpy(obs).cuda().float()
# s_all1 = torch.cat((d1,obs_t[None]),dim=1)
# assert(s_all1.shape[1]==72)
# else:
# O_t1 = torch.from_numpy(obs).cuda().float()
# g_normalize_s1 = g_s.copy()
# g_normalize_s1[:,0] = g_normalize_s1[:,0]/4.0
# g_normalize_s1[:,1] = g_normalize_s1[:,1]/2.0
# g_normalize_s1[:,2] = g_normalize_s1[:,2]/2.0
# g_current1 = torch.from_numpy(g_normalize_s1.reshape(1,-1)).cuda().float()
# # print("old1:",past_traj[-1])
# g_normalize_past1 = past_traj[-1]
# g_normalize_past1[:,0] = g_normalize_past1[:,0]/4.0
# g_normalize_past1[:,1] = g_normalize_past1[:,1]/2.0
# g_normalize_past1[:,2] = g_normalize_past1[:,2]/2.0
# g_old1 = torch.from_numpy(g_normalize_past1.reshape(1,-1)).cuda().float()
# g_normalize_past_c1 = past_corrected_goals[-1]
# g_normalize_past_c1[:,0] = g_normalize_past_c1[:,0]/2.0
# g_normalize_past_c1[:,1] = g_normalize_past_c1[:,1]/2.0
# g_normalize_past_c1[:,2] = g_normalize_past_c1[:,2]/2.0
# g_old_correct1 = torch.from_numpy(g_normalize_past_c1.reshape(1,-1)).cuda().float()
# e_normalize_past1 = past_traj_error[-1]
# e_old1 = torch.from_numpy(e_normalize_past1.reshape(1,-1)).cuda().float()
# s_all1 = torch.cat((O_t1[None],g_current1,g_old1,g_old_correct1,e_old1),dim=1)
# assert s_all1.shape[1]==12+15+15+3+3
# s_all = s_all1
# # prediction_error.append(self.policy._validate_prediction(O[t],A[t],obs))
# O.append(obs)
# reward_sum += reward['reward']
# rewards.append(reward['reward'])
# errorx.append(reward['abs_error_x'])
# errory.append(reward['abs_error_y'])
# errorz.append(reward['abs_error_z'])
# if done:
# break
# if reward_index%3==0 and reward_index!=0:
# repeat_eval = True
# reward_repeat.append(reward_sum)
# if repeat_eval:
# reward_sum_av = np.mean(np.array(reward_repeat))
# logger_ppo.add_scalar('Episode reward', reward_sum_av, reward_index_log)
# ppo_agent.save_network(reward_index_log)
# reward_index_log+=1
# reward_repeat = []
# reward_index+=1
# else:
# for t in range(self.task_hor):
# # if t>100:
# # self.env.wind_controller_x.publish(0.2)
# # self.env.wind_controller_y.publish(0.5) #for tesing the middle fault
# # self.env.set_L(0.8)
# # break
# start = time.time()
# if self.meta:
# if i == 0:
# if len(self.adapt_buffer['act'])>adapt_size:
# #transform trajectories into adapt dataset
# new_train_in = np.concatenate([self.policy.obs_preproc_3d(np.array(self.adapt_buffer['obs'])[-adapt_size-1:-1]), np.array(self.adapt_buffer['act'])[-adapt_size:]], axis=-1)
# new_train_targs = self.policy.targ_proc(np.array(self.adapt_buffer['obs'])[-adapt_size-1:-1], np.array(self.adapt_buffer['obs'])[-adapt_size:])
# new_train_in = torch.from_numpy(new_train_in).float().to(TORCH_DEVICE)
# new_train_targs = torch.from_numpy(new_train_targs).float().to(TORCH_DEVICE)
# self.policy.model.adapt(new_train_in, new_train_targs)
# #add ppo here
# # print("i:",self.env.trajectory.get_i())
# # print("s_all:", s_all)
# action,act_l,store_top_s,store_bad_s = self.policy.act(O[t], t, goal) #[6,5,2] store top s
# if i>0:
# a, a_logprob = ppo_agent.choose_action(s_all)
# # print("a:",a)
# #before added to goal, we need transform it to dimension [horizon,1,dim=3]
# a_correct = a.reshape(1,3).copy()
# past_corrected_goals.append(a_correct+action.reshape(1,3).copy())
# # print(g_s)
# past_traj.append(g_s.copy())
# # print(past_traj)
# action+=a
# # print(store_top_s)
# self.env.pub_action_sequence(store_top_s) #visualize top states in rviz, long traj needs to use stored model
# self.env.pub_action_sequence1(store_bad_s)
# A.append(action)
# top_act_seq.append(act_l)
# times.append(time.time() - start)
# obs, reward, done, (goal, g_s) = self.env.step(A[t])
# new_error_traj = np.zeros((1,3))
# new_error_traj[:,0] = reward['error_x']
# new_error_traj[:,1] = reward['error_y']
# new_error_traj[:,2] = reward['error_z']
# past_traj_error.append(new_error_traj)
# #reward process
# reward['reward'] = -reward['reward']**2
# # reward['reward'] = reward_scaling(reward['reward'])
# if i>0:
# if args.with_image == True:
# if_obs = self.policy.occupancy_predictor(obs)
# # print(if_obs)
# #post process reward and done
# if if_obs:
# done = 1
# reward['reward']-=50
# if args.with_image == True:
# g_map1 = torch.from_numpy(self.env.get_depth_map()).cuda().float()
# g_map_conv1 = g_map1[None][None]
# d1 = act_encoder.encoder_forward(g_map_conv1)
# obs_t = torch.from_numpy(obs).cuda().float()
# s_all1 = torch.cat((d1,obs_t[None]),dim=1)
# assert(s_all1.shape[1]==72)
# else:
# O_t1 = torch.from_numpy(obs).cuda().float()
# g_normalize_s1 = g_s.copy()
# g_normalize_s1[:,0] = g_normalize_s1[:,0]/4.0
# g_normalize_s1[:,1] = g_normalize_s1[:,1]/2.0
# g_normalize_s1[:,2] = g_normalize_s1[:,2]/2.0
# g_current1 = torch.from_numpy(g_normalize_s1.reshape(1,-1)).cuda().float()
# # print("old1:",past_traj[-1])
# g_normalize_past1 = past_traj[-1]
# g_normalize_past1[:,0] = g_normalize_past1[:,0]/4.0
# g_normalize_past1[:,1] = g_normalize_past1[:,1]/2.0
# g_normalize_past1[:,2] = g_normalize_past1[:,2]/2.0
# g_old1 = torch.from_numpy(g_normalize_past1.reshape(1,-1)).cuda().float()
# g_normalize_past_c1 = past_corrected_goals[-1]
# g_normalize_past_c1[:,0] = g_normalize_past_c1[:,0]/2.0
# g_normalize_past_c1[:,1] = g_normalize_past_c1[:,1]/2.0
# g_normalize_past_c1[:,2] = g_normalize_past_c1[:,2]/2.0
# g_old_correct1 = torch.from_numpy(g_normalize_past_c1.reshape(1,-1)).cuda().float()
# e_normalize_past1 = past_traj_error[-1]
# e_old1 = torch.from_numpy(e_normalize_past1.reshape(1,-1)).cuda().float()
# s_all1 = torch.cat((O_t1[None],g_current1,g_old1,g_old_correct1,e_old1),dim=1)
# assert s_all1.shape[1]==12+15+15+3+3
# if done or t == self.task_hor-1:
# dw = True
# else:
# dw = False
# # print(goal)
# # print("reward:",reward['reward'])
# if i>0:
# replay_buffer.store(s_all, a, a_logprob, reward['reward'], s_all1, done, dw)
# # print("obs:", s_all)
# # print("next_obs:",s_all1)
# # print("action:",a)
# # print("reward:",reward['reward'])
# s_all = s_all1
# total_steps+=1
# if replay_buffer.count == args.batch_size:
# ppo_agent.update(replay_buffer, total_steps)
# replay_buffer.count = 0
# prediction_error.append(self.policy._validate_prediction(O[t],A[t],obs))
# if i==0:
# if self.meta:
# self.adapt_buffer['obs'].append(obs)
# self.adapt_buffer['act'].append(A[t])
# # if log_data:
# # obs1 = self.env.get_uav_obs()[0]
# # obs2 = self.env.get_uav_obs()[1]
# # obs1_l.append(obs1)
# # obs2_l.append(obs2)
# O.append(obs)
# reward_sum += reward['reward']
# rewards.append(reward['reward'])
# errorx.append(reward['abs_error_x'])
# errory.append(reward['abs_error_y'])
# errorz.append(reward['abs_error_z'])
# if done:
# break
# episode_n+=1
# repeat_eval = False
# print("Average action selection time: ", np.mean(times))
# print("Rollout length: ", len(A))
# print("Rollout reward: ", reward_sum)
# self.logger.close()
def run_experiment_ppo(self,path):
torch.manual_seed(222)
torch.cuda.manual_seed_all(222)
np.random.seed(222)
train_iters = 1600
#ppo logger
log_path_ppo = os.path.join("/home/wawa/catkin_meta/src/MBRL_transport/log_pure_PPO_model",strftime("%Y-%m-%d--%H:%M:%S", localtime()))
os.makedirs(log_path_ppo, exist_ok=True)
logger_ppo = SummaryWriter(logdir=log_path_ppo) # used for tensorboard
args = DotMap()
# if not use image, change dimension
args.state_dim = 24
args.action_dim = 3
args.max_action = 1.0
args.batch_size = 2048
args.mini_batch_size = 64
args.max_train_steps = train_iters * self.task_hor
args.lr_a = 3e-4
args.lr_c = 3e-4
args.gamma = 0.99
args.lamda = 0.95
args.epsilon = 0.2
args.K_epochs = 10
args.entropy_coef = 0.005#0.01
args.use_grad_clip = True
args.use_lr_decay = True
args.use_adv_norm = True
# args.horizon = 1
args.evaluate_s = 0
#runing rollouts for collection samples for meta training
wind_condition_x = 0.0
wind_condition_y = 0.0
L = 0.6
replay_buffer = ReplayBuffer(args)
ppo_agent = PPO_model(args,logger_ppo).to(TORCH_DEVICE)
total_steps = 0
evaluate_frequency = 20
reward_index = 0
reward_index_log = 0
reward_repeat = []
episode_n = 0
repeat_eval = False
# reward_scaling = RewardScaling(shape=1, gamma=args.gamma)
for i in range(train_iters):
self.env.wind_controller_x.publish(0.0)
self.env.wind_controller_y.publish(0.0)
self.env.set_L(L)
times, rewards = [], []
o1, goal, g_s = self.env.reset()
O, A, reward_sum, done = [o1], [], 0, False
# reward_scaling.reset()
past_corrected_goals = [np.zeros((1,3))]
past_traj = [np.zeros((1,3))]
past_traj_error = [np.zeros((1,3))]
#normalize goal input in observation
O_t = torch.from_numpy(o1).cuda().float()
g_normalize_s = g_s.copy()
g_normalize_s[:,0] = g_normalize_s[:,0]/4.0
g_normalize_s[:,1] = g_normalize_s[:,1]/2.0
g_normalize_s[:,2] = g_normalize_s[:,2]/2.0
g_current = torch.from_numpy(g_normalize_s.reshape(1,-1)).cuda().float()
# print("old:",past_traj[-1])
g_normalize_past = past_traj[-1]
g_normalize_past[:,0] = g_normalize_past[:,0]/4.0
g_normalize_past[:,1] = g_normalize_past[:,1]/2.0
g_normalize_past[:,2] = g_normalize_past[:,2]/2.0
g_old = torch.from_numpy(g_normalize_past.reshape(1,-1)).cuda().float()
g_normalize_past_c = past_corrected_goals[-1]
g_normalize_past_c[:,0] = g_normalize_past_c[:,0]
g_normalize_past_c[:,1] = g_normalize_past_c[:,1]
g_normalize_past_c[:,2] = g_normalize_past_c[:,2]
g_old_correct = torch.from_numpy(g_normalize_past_c.reshape(1,-1)).cuda().float()
e_normalize_past = past_traj_error[-1]
e_old = torch.from_numpy(e_normalize_past.reshape(1,-1)).cuda().float()
s_all = torch.cat((O_t[None],g_current[:,:3],g_old[:,:3],g_old_correct,e_old),dim=1)
assert s_all.shape[1]==12+3+3+3+3
self.policy.reset()
if (episode_n%evaluate_frequency==0 and episode_n!=0) and not repeat_eval:
self.env.wind_controller_x.publish(wind_condition_x)
self.env.wind_controller_y.publish(wind_condition_y)
for t in range(self.task_hor):
# if t>100:
# self.env.wind_controller_x.publish(0.2)
# self.env.wind_controller_y.publish(0.5) #for tesing the middle fault
# self.env.set_L(0.8)
# break
start = time.time()
a = ppo_agent.evaluate(s_all)
past_corrected_goals.append(a.reshape(1,3).copy())
# print(g_s)
past_traj.append(g_s.copy())
action=a
# print(store_top_s)
A.append(action)
times.append(time.time() - start)
obs, reward, done, (goal, g_s) = self.env.step(A[t])
new_error_traj = np.zeros((1,3))
new_error_traj[:,0] = reward['error_x']
new_error_traj[:,1] = reward['error_y']
new_error_traj[:,2] = reward['error_z']
past_traj_error.append(new_error_traj)
#reward process
reward['reward'] = -reward['reward']
if done==1:
reward['reward']-=20
# reward['reward'] = reward_scaling(reward['reward'])
O_t1 = torch.from_numpy(obs).cuda().float()
g_normalize_s1 = g_s.copy()
g_normalize_s1[:,0] = g_normalize_s1[:,0]/4.0
g_normalize_s1[:,1] = g_normalize_s1[:,1]/2.0
g_normalize_s1[:,2] = g_normalize_s1[:,2]/2.0
g_current1 = torch.from_numpy(g_normalize_s1.reshape(1,-1)).cuda().float()
# print("old1:",past_traj[-1])
g_normalize_past1 = past_traj[-1]
g_normalize_past1[:,0] = g_normalize_past1[:,0]/4.0
g_normalize_past1[:,1] = g_normalize_past1[:,1]/2.0
g_normalize_past1[:,2] = g_normalize_past1[:,2]/2.0
g_old1 = torch.from_numpy(g_normalize_past1.reshape(1,-1)).cuda().float()
g_normalize_past_c1 = past_corrected_goals[-1]
g_normalize_past_c1[:,0] = g_normalize_past_c1[:,0]
g_normalize_past_c1[:,1] = g_normalize_past_c1[:,1]
g_normalize_past_c1[:,2] = g_normalize_past_c1[:,2]
g_old_correct1 = torch.from_numpy(g_normalize_past_c1.reshape(1,-1)).cuda().float()
e_normalize_past1 = past_traj_error[-1]
e_old1 = torch.from_numpy(e_normalize_past1.reshape(1,-1)).cuda().float()
s_all1 = torch.cat((O_t1[None],g_current1[:,:3],g_old1[:,:3],g_old_correct1,e_old1),dim=1)
assert s_all1.shape[1]==12+3+3+3+3
s_all = s_all1
# prediction_error.append(self.policy._validate_prediction(O[t],A[t],obs))
O.append(obs)
reward_sum += reward['reward']
rewards.append(reward['reward'])
if done:
break
if reward_index%3==0 and reward_index!=0:
repeat_eval = True
reward_repeat.append(reward_sum/len(A))
if repeat_eval:
reward_sum_av = np.mean(np.array(reward_repeat))
reward_sum_std = np.std(np.array(reward_repeat))
logger_ppo.add_scalar('Episode reward', reward_sum_av, reward_index_log)
logger_ppo.add_scalar('Episode reward std', reward_sum_std, reward_index_log)
ppo_agent.save_network(reward_index_log)
reward_index_log+=1
reward_repeat = []
reward_index+=1
else:
self.env.wind_controller_x.publish(wind_condition_x)
self.env.wind_controller_y.publish(wind_condition_y)
for t in range(self.task_hor):
# if t>100:
# self.env.wind_controller_x.publish(0.2)
# self.env.wind_controller_y.publish(0.5) #for tesing the middle fault
# self.env.set_L(0.8)
# break
start = time.time()
#add ppo here
# print("i:",self.env.trajectory.get_i())
# print("s_all:", s_all)
a, a_logprob = ppo_agent.choose_action(s_all)
# print("a:",a)
#before added to goal, we need transform it to dimension [horizon,1,dim=3]
past_corrected_goals.append(a.reshape(1,3).copy())
# print(g_s)
past_traj.append(g_s.copy())
# print(past_traj)
action=a
# print(store_top_s)
A.append(action)
times.append(time.time() - start)
obs, reward, done, (goal, g_s) = self.env.step(A[t])
new_error_traj = np.zeros((1,3))
new_error_traj[:,0] = reward['error_x']
new_error_traj[:,1] = reward['error_y']
new_error_traj[:,2] = reward['error_z']
past_traj_error.append(new_error_traj)
#reward process
reward['reward'] = -reward['reward']
if done==1:
reward['reward']-=20
# reward['reward'] = reward_scaling(reward['reward'])
O_t1 = torch.from_numpy(obs).cuda().float()
g_normalize_s1 = g_s.copy()
g_normalize_s1[:,0] = g_normalize_s1[:,0]/4.0
g_normalize_s1[:,1] = g_normalize_s1[:,1]/2.0
g_normalize_s1[:,2] = g_normalize_s1[:,2]/2.0
g_current1 = torch.from_numpy(g_normalize_s1.reshape(1,-1)).cuda().float()
# print("old1:",past_traj[-1])
g_normalize_past1 = past_traj[-1]
g_normalize_past1[:,0] = g_normalize_past1[:,0]/4.0
g_normalize_past1[:,1] = g_normalize_past1[:,1]/2.0
g_normalize_past1[:,2] = g_normalize_past1[:,2]/2.0
g_old1 = torch.from_numpy(g_normalize_past1.reshape(1,-1)).cuda().float()
g_normalize_past_c1 = past_corrected_goals[-1]
g_normalize_past_c1[:,0] = g_normalize_past_c1[:,0]
g_normalize_past_c1[:,1] = g_normalize_past_c1[:,1]
g_normalize_past_c1[:,2] = g_normalize_past_c1[:,2]
g_old_correct1 = torch.from_numpy(g_normalize_past_c1.reshape(1,-1)).cuda().float()
e_normalize_past1 = past_traj_error[-1]
e_old1 = torch.from_numpy(e_normalize_past1.reshape(1,-1)).cuda().float()
s_all1 = torch.cat((O_t1[None],g_current1[:,:3],g_old1[:,:3],g_old_correct1,e_old1),dim=1)
assert s_all1.shape[1]==12+3+3+3+3
if done or t == self.task_hor-1:
dw = True
else:
dw = False
# print(goal)
# print("reward:",reward['reward'])
replay_buffer.store(s_all, a, a_logprob, reward['reward'], s_all1, done, dw)
# print("obs:", s_all)
# print("next_obs:",s_all1)
# print("action:",a)
# print("reward:",reward['reward'])
s_all = s_all1
total_steps+=1
if replay_buffer.count == args.batch_size:
ppo_agent.update(replay_buffer, total_steps)
replay_buffer.count = 0
O.append(obs)
reward_sum += reward['reward']
rewards.append(reward['reward'])
if done:
break
episode_n+=1
repeat_eval = False
print("Average action selection time: ", np.mean(times))
print("Rollout length: ", len(A))
print("Rollout reward: ", reward_sum)
self.logger.close()
def run_experiment_meta_online1_1(self, path):
"""
Correct actions
Perform meta experiment.
we load the offline meta model and without the online training, only one episode adaptation
"""
#222,50,8
torch.manual_seed(222)
torch.cuda.manual_seed_all(222)
np.random.seed(222)
train_iters = 1600
#ppo logger
log_path_ppo = os.path.join("/home/wawa/catkin_meta/src/MBRL_transport/log_PPO_model",strftime("%Y-%m-%d--%H:%M:%S", localtime()))
os.makedirs(log_path_ppo, exist_ok=True)
logger_ppo = SummaryWriter(logdir=log_path_ppo) # used for tensorboard
args = DotMap()
# if not use image, change dimension
args.with_image = False
args.state_dim = 24
args.action_dim = 3
args.max_action = 0.1
args.batch_size = 2048
args.mini_batch_size = 64
args.max_train_steps = train_iters * self.task_hor