forked from expeditionary-robotics/informative-path-planning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipp_library.py
1959 lines (1631 loc) · 90.6 KB
/
ipp_library.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 matplotlib import pyplot as plt
import matplotlib
from matplotlib.colors import LogNorm
from matplotlib import cm
from sklearn import mixture
from IPython.display import display
from scipy.stats import multivariate_normal
import numpy as np
import scipy as sp
import math
import os
import GPy as GPy
import dubins
import time
from itertools import chain
import pdb
import logging
logger = logging.getLogger('robot')
'''
This library file aggregates a number of classes that are useful for performing the informative path planning (IPP) problem. Detailed documentation is provided for each of the classes inline.
Maintainers: Genevieve Flaspohler and Victoria Preston
License: MIT
'''
# MIN_COLOR = 3.0
# MAX_COLOR = 7.5
MIN_COLOR = -25.
MAX_COLOR = 25.
class GPModel:
'''The GPModel class, which is a wrapper on top of GPy.'''
def __init__(self, ranges, lengthscale, variance, noise = 0.0001, dimension = 2, kernel = 'rbf'):
'''Initialize a GP regression model with given kernel parameters.
Inputs:
ranges (list of floats) the bounds of the world
lengthscale (float) the lengthscale parameter of kernel
variance (float) the variance parameter of kernel
noise (float) the sensor noise parameter of kernel
dimension (float) the dimension of the environment; only 2D supported
kernel (string) the type of kernel; only 'rbf' supported now
'''
# Model parameterization (noise, lengthscale, variance)
self.noise = noise
self.lengthscale = lengthscale
self.variance = variance
self.ranges = ranges
# The Gaussian dataset; start with null set
self.xvals = None
self.zvals = None
# The dimension of the evironment
if dimension == 2:
self.dim = dimension
else:
raise ValueError('Environment must have dimension 2 \'rbf\'')
if kernel == 'rbf':
self.kern = GPy.kern.RBF(input_dim = self.dim, lengthscale = lengthscale, variance = variance)
else:
raise ValueError('Kernel type must by \'rbf\'')
# Intitally, before any data is created,
self.model = None
self.temp_model = None
def predict_value(self, xvals, TEMP = False):
''' Public method returns the mean and variance predictions at a set of input locations.
Inputs:
xvals (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2
Returns:
mean (float array): an nparray of floats representing predictive mean, with dimension NUM_PTS x 1
var (float array): an nparray of floats representing predictive variance, with dimension NUM_PTS x 1
'''
assert(xvals.shape[0] >= 1)
assert(xvals.shape[1] == self.dim)
n_points, input_dim = xvals.shape
if TEMP:
# With no observations, predict 0 mean everywhere and prior variance
if self.temp_model == None:
return np.zeros((n_points, 1)), np.ones((n_points, 1)) * self.variance
# Else, return the predicted values
mean, var = self.temp_model.predict(xvals, full_cov = False, include_likelihood = True)
return mean, var
# With no observations, predict 0 mean everywhere and prior variance
if self.model == None:
return np.zeros((n_points, 1)), np.ones((n_points, 1)) * self.variance
# Else, return the predicted values
mean, var = self.model.predict(xvals, full_cov = False, include_likelihood = True)
return mean, var
def add_data_and_temp_model(self, xvals, zvals):
''' Public method that adds data to a temporay GP model and returns that model
Inputs:
xvals (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2
zvals (float array): an nparray of floats representing sensor observations, with dimension NUM_PTS x 1
'''
if self.xvals is None:
xvals = xvals
else:
xvals = np.vstack([self.xvals, xvals])
if self.zvals is None:
zvals = zvals
else:
zvals = np.vstack([self.zvals, zvals])
# Create a temporary model
self.temp_model = GPy.models.GPRegression(np.array(xvals), np.array(zvals), self.kern)
def add_data(self, xvals, zvals):
''' Public method that adds data to an the GP model.
Inputs:
xvals (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2
zvals (float array): an nparray of floats representing sensor observations, with dimension NUM_PTS x 1
'''
if self.xvals is None:
self.xvals = xvals
else:
self.xvals = np.vstack([self.xvals, xvals])
if self.zvals is None:
self.zvals = zvals
else:
self.zvals = np.vstack([self.zvals, zvals])
# If the model hasn't been created yet (can't be created until we have data), create GPy model
if self.model == None:
self.model = GPy.models.GPRegression(np.array(self.xvals), np.array(self.zvals), self.kern)
# Else add to the exisiting model
else:
self.model.set_XY(X = np.array(self.xvals), Y = np.array(self.zvals))
def load_kernel(self, kernel_file = 'kernel_model.npy'):
''' Public method that loads kernel parameters from file.
Inputs:
kernel_file (string): a filename string with the location of the kernel parameters
'''
# Read pre-trained kernel parameters from file, if avaliable and no training data is provided
if os.path.isfile(kernel_file):
print("Loading kernel parameters from file")
logger.info("Loading kernel parameters from file")
self.kern[:] = np.load(kernel_file)
else:
raise ValueError("Failed to load kernel. Kernel parameter file not found.")
return
def train_kernel(self, xvals = None, zvals = None, kernel_file = 'kernel_model.npy'):
''' Public method that optmizes kernel parameters based on input data and saves to files.
Inputs:
xvals (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2
zvals (float array): an nparray of floats representing sensor observations, with dimension NUM_PTS x 1
kernel_file (string): a filename string with the location to save the kernel parameters
Outputs:
nothing is returned, but a kernel file is created.
'''
# Read pre-trained kernel parameters from file, if available and no
# training data is provided
# if xvals is not None and zvals is not None:
# if self.xvals is None:
# self.xvals = xvals
# else:
# self.xvals = np.vstack([self.xvals, xvals])
# if self.zvals is None:
# self.zvals = zvals
# else:
# self.zvals = np.vstack([self.zvals, zvals])
if self.xvals is not None and self.zvals is not None:
xvals = self.xvals[::5]
zvals = self.zvals[::5]
print("Optimizing kernel parameters given data")
logger.info("Optimizing kernel parameters given data")
# Initilaize a GP model (used only for optmizing kernel hyperparamters)
self.m = GPy.models.GPRegression(np.array(xvals), np.array(zvals), self.kern)
self.m.initialize_parameter()
# Constrain the hyperparameters during optmization
self.m.constrain_positive('')
self.m['Gaussian_noise.variance'].constrain_fixed(self.noise)
# Train the kernel hyperparameters
self.m.optimize_restarts(num_restarts = 2, messages = True)
# Save the hyperparemters to file
np.save(kernel_file, self.kern[:])
self.lengthscale = self.kern.lengthscale
self.variance = self.kern.variance
else:
raise ValueError("Failed to train kernel. No training data provided.")
class Environment:
'''The Environment class, which represents a retangular Gaussian world.
'''
def __init__(self, ranges, NUM_PTS, variance, lengthscale, noise = 0.0001,
visualize = True, seed = None, dim = 2, model = None):
''' Initialize a random Gaussian environment using the input kernel,
assuming zero mean function.
Input:
ranges (tuple of floats): a tuple representing the max/min of 2D
rectangular domain i.e. (-10, 10, -50, 50)
NUM_PTS (int): the number of points in each dimension to sample for
initialization, resulting in a sample grid of size NUM_PTS x NUM_PTS
variance (float): the variance parameter of the kernel
lengthscale (float): the lengthscale parameter of the kernel
noise (float): the sensor noise parameter of the kernel
visualize (boolean): flag to plot the surface of the environment
seed (int): an integer seed for the random draws. If set to \'None\',
no seed is used
'''
# Save the parmeters of GP model
self.variance = variance
self.lengthscale = lengthscale
self.dim = dim
self.noise = noise
logger.info('Environment seed: {}'.format(seed))
# Expect ranges to be a 4-tuple consisting of x1min, x1max, x2min, and x2max
self.x1min = float(ranges[0])
self.x1max = float(ranges[1])
self.x2min = float(ranges[2])
self.x2max = float(ranges[3])
if model is not None:
self.GP = model
# Plot the surface mesh and scatter plot representation of the samples points
if visualize == True:
# Generate a set of observations from robot model with which to make contour plots
x1vals = np.linspace(ranges[0], ranges[1], 40)
x2vals = np.linspace(ranges[2], ranges[3], 40)
x1, x2 = np.meshgrid(x1vals, x2vals, sparse = False, indexing = 'xy') # dimension: NUM_PTS x NUM_PTS
data = np.vstack([x1.ravel(), x2.ravel()]).T
observations, var = self.GP.predict_value(data)
fig2, ax2 = plt.subplots(figsize=(8, 6))
ax2.set_xlim(ranges[0:2])
ax2.set_ylim(ranges[2:])
ax2.set_title('Countour Plot of the True World Model')
plot = ax2.contourf(x1, x2, observations.reshape(x1.shape), cmap = 'viridis', vmin = MIN_COLOR, vmax = MAX_COLOR, levels=np.linspace(MIN_COLOR, MAX_COLOR, 15))
scatter = ax2.scatter(self.GP.xvals[:, 0], self.GP.xvals[:, 1], c = self.GP.zvals.ravel(), s = 4.0, cmap = 'viridis')
maxind = np.argmax(self.GP.zvals)
ax2.scatter(self.GP.xvals[maxind, 0], self.GP.xvals[maxind,1], color = 'k', marker = '*', s = 500)
fig2.colorbar(plot, ax=ax2)
fig2.savefig('./figures/world_model_countour.png')
#plt.show()
plt.close()
else:
# Generate a set of discrete grid points, uniformly spread across the environment
x1 = np.linspace(self.x1min, self.x1max, NUM_PTS)
x2 = np.linspace(self.x2min, self.x2max, NUM_PTS)
# dimension: NUM_PTS x NUM_PTS
x1vals, x2vals = np.meshgrid(x1, x2, sparse = False, indexing = 'xy')
# dimension: NUM_PTS*NUM_PTS x 2
data = np.vstack([x1vals.ravel(), x2vals.ravel()]).T
bb = ((ranges[1] - ranges[0])*0.05, (ranges[3] - ranges[2]) * 0.05)
ranges = (ranges[0] + bb[0], ranges[1] - bb[0], ranges[2] + bb[1], ranges[3] - bb[1])
# Initialize maxima arbitrarily to violate boundary constraints
maxima = [self.x1min, self.x2min]
# Continue to generate random environments until the global maximia
# lives within the boundary constraints
while maxima[0] < ranges[0] or maxima[0] > ranges[1] or \
maxima[1] < ranges[2] or maxima[1] > ranges[3]:
print("Current environment in violation of boundary constraint. Regenerating!")
logger.warning("Current environment in violation of boundary constraint. Regenerating!")
# Intialize a GP model of the environment
self.GP = GPModel(ranges = ranges, lengthscale = lengthscale, variance = variance)
# Take an initial sample in the GP prior, conditioned on no other data
# This is done to
xsamples = np.reshape(np.array(data[0, :]), (1, dim)) # dimension: 1 x 2
mean, var = self.GP.predict_value(xsamples)
if seed is not None:
np.random.seed(seed)
seed += 1
zsamples = np.random.normal(loc = 0, scale = np.sqrt(var))
zsamples = np.reshape(zsamples, (1,1)) # dimension: 1 x 1
# Add initial sample data point to the GP model
self.GP.add_data(xsamples, zsamples)
# Iterate through the rest of the grid sequentially and sample a z values,
# conditioned on previous samples
for index, point in enumerate(data[1:, :]):
# Get a new sample point
xs = np.reshape(np.array(point), (1, dim))
# Compute the predicted mean and variance
mean, var = self.GP.predict_value(xs)
# Sample a new observation, given the mean and variance
if seed is not None:
np.random.seed(seed)
seed += 1
zs = np.random.normal(loc = mean, scale = np.sqrt(var))
# Add new sample point to the GP model
zsamples = np.vstack([zsamples, np.reshape(zs, (1, 1))])
xsamples = np.vstack([xsamples, np.reshape(xs, (1, dim))])
self.GP.add_data(np.reshape(xs, (1, dim)), np.reshape(zs, (1, 1)))
maxima = self.GP.xvals[np.argmax(self.GP.zvals), :]
# Plot the surface mesh and scatter plot representation of the samples points
if visualize == True:
# the 3D surface
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection = '3d')
ax.set_title('Surface of the Simulated Environment')
surf = ax.plot_surface(x1vals, x2vals, zsamples.reshape(x1vals.shape), cmap = cm.coolwarm, linewidth = 1)
if not os.path.exists('./figures'):
os.makedirs('./figures')
fig.savefig('./figures/world_model_surface.png')
# the contour map
fig2 = plt.figure(figsize=(8, 6))
ax2 = fig2.add_subplot(111)
ax2.set_title('Countour Plot of the Simulated Environment')
plot = ax2.contourf(x1vals, x2vals, zsamples.reshape(x1vals.shape), cmap = 'viridis', vmin = MIN_COLOR, vmax = MAX_COLOR, levels=np.linspace(MIN_COLOR, MAX_COLOR, 15))
scatter = ax2.scatter(data[:, 0], data[:, 1], c = zsamples.ravel(), s = 4.0, cmap = 'viridis')
maxind = np.argmax(zsamples)
ax2.scatter(xsamples[maxind, 0], xsamples[maxind,1], color = 'k', marker = '*', s = 500)
fig2.colorbar(plot, ax=ax2)
fig2.savefig('./figures/world_model_countour.png')
#plt.show()
plt.close()
print("Environment initialized with bounds X1: (", self.x1min, ",", self.x1max, ") X2:(", self.x2min, ",", self.x2max, ")")
logger.info("Environment initialized with bounds X1: ({}, {}) X2: ({}, {})".format(self.x1min, self.x1max, self.x2min, self.x2max))
def sample_value(self, xvals):
''' The public interface to the Environment class. Returns a noisy sample of the true value of environment at a set of point.
Input:
xvals (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2
Returns:
mean (float array): an nparray of floats representing predictive mean, with dimension NUM_PTS x 1
'''
assert(xvals.shape[0] >= 1)
assert(xvals.shape[1] == self.dim)
mean, var = self.GP.predict_value(xvals)
return mean + np.random.normal(loc = 0, scale = np.sqrt(self.noise))
'''The Path_Generator class which creates naive point-to-point straightline paths'''
class Path_Generator:
def __init__(self, frontier_size, horizon_length, turning_radius, sample_step, extent):
''' Initialize a path generator
Input:
frontier_size (int) the number of points on the frontier we should consider for navigation
horizon_length (float) distance between the vehicle and the horizon to consider
turning_radius (float) the feasible turning radius for the vehicle
sample_step (float) the unit length along the path from which to draw a sample
extent (list of floats) the world boundaries
'''
# the parameters for the dubin trajectory
self.fs = frontier_size
self.hl = horizon_length
self.tr = turning_radius
self.ss = sample_step
self.extent = extent
# Global variables
self.goals = [] #The frontier coordinates
self.samples = {} #The sample points which form the paths
self.cp = (0,0,0) #The current pose of the vehicle
def generate_frontier_points(self):
'''From the frontier_size and horizon_length, generate the frontier points to goal'''
angle = np.linspace(-2.35,2.35,self.fs) #fix the possibilities to 75% of the unit circle, ignoring points directly behind the vehicle
goals = []
for a in angle:
# x = self.hl*np.cos(self.cp[2]+a)+self.cp[0]
# y = self.hl*np.sin(self.cp[2]+a)+self.cp[1]
x = self.hl*np.cos(self.cp[2]+a)+self.cp[0]
if x >= self.extent[1]-3*self.tr:
x = self.extent[1]-3*self.tr
y = (x-self.cp[0])*np.sin(self.cp[2]+a)+self.cp[1]
elif x <= self.extent[0]+3*self.tr:
x = self.extent[0]+3*self.tr
y = (x-self.cp[0])*np.sin(self.cp[2]+a)+self.cp[1]
else:
y = self.hl*np.sin(self.cp[2]+a)+self.cp[1]
if y >= self.extent[3]-3*self.tr:
y = self.extent[3]-3*self.tr
x = (y-self.cp[1])*-np.cos(self.cp[2]+a)+self.cp[0]
elif y <= self.extent[2]+3*self.tr:
y = self.extent[2]+3*self.tr
x = (y-self.cp[1])*-np.cos(self.cp[2]+a)+self.cp[0]
p = self.cp[2]+a
if np.linalg.norm([self.cp[0]-x, self.cp[1]-y]) <= self.tr:
pass
elif x > self.extent[1]-3*self.tr or x < self.extent[0]+3*self.tr:
pass
elif y > self.extent[3]-3*self.tr or y < self.extent[2]+3*self.tr:
pass
else:
goals.append((x,y,p))
self.goals = goals
return self.goals
def make_sample_paths(self):
'''Connect the current_pose to the goal places'''
cp = np.array(self.cp)
coords = {}
for i,goal in enumerate(self.goals):
g = np.array(goal)
distance = np.sqrt((cp[0]-g[0])**2 + (cp[1]-g[1])**2)
samples = int(round(distance/self.ss))
# Don't include the start location but do include the end point
for j in range(0,samples):
x = cp[0]+((j+1)*self.ss)*np.cos(g[2])
y = cp[1]+((j+1)*self.ss)*np.sin(g[2])
a = g[2]
try:
coords[i].append((x,y,a))
except:
coords[i] = []
coords[i].append((x,y,a))
self.samples = coords
return self.samples
def get_path_set(self, current_pose):
'''Primary interface for getting list of path sample points for evaluation
Input:
current_pose (tuple of x, y, z, a which are floats) current location of the robot in world coordinates
Output:
paths (dictionary of frontier keys and sample points)
'''
self.cp = current_pose
self.generate_frontier_points()
paths = self.make_sample_paths()
return paths
def get_frontier_points(self):
''' Method to access the goal points'''
return self.goals
def get_sample_points(self):
return self.samples
class Dubins_Path_Generator(Path_Generator):
'''
The Dubins_Path_Generator class, which inherits from the Path_Generator class. Replaces the make_sample_paths
method with paths generated using the dubins library
'''
def buffered_paths(self):
coords = {}
for i,goal in enumerate(self.goals):
path = dubins.shortest_path(self.cp, goal, self.tr)
configurations, _ = path.sample_many(self.ss)
configurations.append(goal)
temp = []
for config in configurations:
if config[0] > self.extent[0] and config[0] < self.extent[1] and config[1] > self.extent[2] and config[1] < self.extent[3]:
temp.append(config)
else:
temp = []
break
if len(temp) < 2:
pass
else:
coords[i] = temp
if len(coords) == 0:
pdb.set_trace()
return coords
def make_sample_paths(self):
'''Connect the current_pose to the goal places'''
coords = self.buffered_paths()
if len(coords) == 0:
print('no viable path')
self.samples = coords
return coords
class Dubins_EqualPath_Generator(Path_Generator):
'''
The Dubins_EqualPath_Generator class which inherits from Path_Generator. Modifies Dubin Curve paths so that all
options have an equal number of sampling points
'''
def make_sample_paths(self):
'''Connect the current_pose to the goal places'''
coords = {}
for i,goal in enumerate(self.goals):
g = (goal[0],goal[1],self.cp[2])
path = dubins.shortest_path(self.cp, goal, self.tr)
configurations, _ = path.sample_many(self.ss)
coords[i] = [config for config in configurations if config[0] > self.extent[0] and config[0] < self.extent[1] and config[1] > self.extent[2] and config[1] < self.extent[3]]
# find the "shortest" path in sample space
current_min = 1000
for key,path in coords.items():
if len(path) < current_min and len(path) > 1:
current_min = len(path)
# limit all paths to the shortest path in sample space
# NOTE! for edge cases nar borders, this limits the paths significantly
for key,path in coords.items():
if len(path) > current_min:
path = path[0:current_min]
coords[key]=path
class MCTS:
'''Class that establishes a MCTS for nonmyopic planning'''
def __init__(self, computation_budget, belief, initial_pose, rollout_length, frontier_size, path_generator, aquisition_function, f_rew, time, aq_param = None):
'''Initialize with constraints for the planning, including whether there is a budget or planning horizon
Inputs:
computation_budget (float) number of seconds to run the tree building procedure
belief (GP model) current belief of the vehicle
initial_pose (tuple of floats) location of the vehicle in world coordinates
rollout_length (int) number of actions to rollout after selecting a child (tree depth)
frontier_size (int) number of options for each action in the tree (tree breadth)
path_generator (string) how action sets should be developed
aquisition_function (function) the criteria to make decisions
f_rew (string) the name of the function used to make decisions
time (float) time in the global world used for aquisition weighting
'''
# Parameterization for the search
self.comp_budget = computation_budget
self.GP = belief
self.cp = initial_pose
self.rl = rollout_length
self.fs = frontier_size
self.path_generator = path_generator
self.aquisition_function = aquisition_function
self.f_rew = f_rew
self.t = time
# The tree
self.tree = None
# Elements which are relevant for some acquisition functions
self.params = None
self.max_val = None
self.max_locs = None
self.current_max = aq_param
def choose_trajectory(self, t):
''' Main function loop which makes the tree and selects the best child
Output:
path to take, cost of that path
'''
# initialize tree
self.tree = self.initialize_tree()
i = 0 #iteration count
# randonly sample the world for entropy search function
if self.f_rew == 'mes' or self.f_rew == 'maxs-mes':
self.max_val, self.max_locs, self.target = sample_max_vals(self.GP, t = t)
time_start = time.time()
# while we still have time to compute, generate the tree
while time.time() - time_start < self.comp_budget:
i += 1
current_node = self.tree_policy()
sequence = self.rollout_policy(current_node)
reward = self.get_reward(sequence)
self.update_tree(reward, sequence)
# get the best action to take with most promising futures
best_sequence, best_val, all_vals = self.get_best_child()
print("Number of rollouts:", i, "\t Size of tree:", len(self.tree))
logger.info("Number of rollouts: {} \t Size of tree: {}".format(i, len(self.tree)))
paths = self.path_generator.get_path_set(self.cp)
return self.tree[best_sequence][0], best_val, paths, all_vals, self.max_locs, self.max_val
def initialize_tree(self):
'''Creates a tree instance, which is a dictionary, that keeps track of the nodes in the world
Output:
tree (dictionary) an initial tree
'''
tree = {}
# root of the tree is current location of the vehicle
tree['root'] = (self.cp, 0) #(pose, number of queries)
actions = self.path_generator.get_path_set(self.cp)
for action, samples in actions.items():
cost = np.sqrt((self.cp[0]-samples[-1][0])**2 + (self.cp[1]-samples[-1][1])**2)
tree['child '+ str(action)] = (samples, cost, 0, 0) #(samples, cost, reward, number of times queried)
return tree
def tree_policy(self):
'''Implements the UCB policy to select the child to expand and forward simulate. From Arora paper, the following is defined:
avg_r - average reward of all rollouts that have passed through node n
c_p - some arbitrary constant, they use 0.1
N - number of times parent has been evaluated
n - number of times that node has been evaluated
the formula: avg_r + c_p * np.sqrt(2*np.log(N)/n)
'''
leaf_eval = {}
# TODO: check initialization, when everything is zero. appears to be throwing error
actions = self.path_generator.get_path_set(self.cp)
for i, val in actions.items():
try:
node = 'child '+ str(i)
leaf_eval[node] = self.tree[node][2] + 0.1*np.sqrt(2*(np.log(self.tree['root'][1]))/self.tree[node][3])
except:
pass
return max(leaf_eval, key=leaf_eval.get)
def rollout_policy(self, node):
'''Select random actions to expand the child node
Input:
node (the name of the child node that is to be expanded)
Output:
sequence (list of names of nodes that make the sequence in the tree)
'''
sequence = [node] #include the child node
#TODO use the cost metric to signal action termination, for now using horizon
for i in xrange(self.rl):
actions = self.path_generator.get_path_set(self.tree[node][0][-1]) #plan from the last point in the sample
if len(actions) == 0:
print('No actions were viably generated')
try:
try:
a = np.random.randint(0,len(actions)-1) #choose a random path
except:
if len(actions) != 0:
a = 0
keys = actions.keys()
# print keys
if len(keys) <= 1:
#print 'few paths available!'
pass
#TODO add cost metrics
self.tree[node + ' child ' + str(keys[a])] = (actions[keys[a]], 0, 0, 0) #add random path to the tree
node = node + ' child ' + str(keys[a])
sequence.append(node)
except:
print('rolling back')
sequence.remove(node)
try:
node = sequence[-1]
except:
print("Empty sequence", sequence, node)
logger.warning('Bad sequence')
return sequence
def get_reward(self, sequence):
'''Evaluate the sequence to get the reward, defined by the percentage of entropy reduction.
Input:
sequence (list of strings) names of the nodes in the tree
Outut:
reward value from the aquisition function of choice
'''
sim_world = self.GP
samples = []
obs = []
for seq in sequence:
samples.append(self.tree[seq][0])
obs = list(chain.from_iterable(samples))
if self.f_rew == 'mes' or self.f_rew == 'maxs-mes':
return self.aquisition_function(time = self.t, xvals = obs, robot_model = sim_world, param = (self.max_val, self.max_locs, self.target))
elif self.f_rew == 'exp_improve':
return self.aquisition_function(time=self.t, xvals = obs, robot_model = sim_world, param = [self.current_max])
else:
return self.aquisition_function(time=self.t, xvals = obs, robot_model = sim_world)
def update_tree(self, reward, sequence):
'''Propogate the reward for the sequence
Input:
reward (float) the reward or utility value of the sequence
sequence (list of strings) the names of nodes that form the sequence
'''
#TODO update costs as well
self.tree['root'] = (self.tree['root'][0], self.tree['root'][1]+1)
for seq in sequence:
samples, cost, rew, queries = self.tree[seq]
queries += 1
n = queries
rew = ((n-1)*rew+reward)/n
self.tree[seq] = (samples, cost, rew, queries)
def get_best_child(self):
'''Query the tree for the best child in the actions
Output:
(string, float) node name of the best child, the cost of that child
'''
best = -float('inf')
best_child = None
value = {}
for i in xrange(self.fs):
try:
r = self.tree['child '+ str(i)][2]
value[i] = r
#if r > best and len(self.tree['child '+ str(i)][0]) > 1:
if r > best:
best = r
best_child = 'child '+ str(i)
except:
pass
return best_child, best, value
class Robot(object):
''' The Robot class, which includes the vehicles current model of the world and IPP algorithms.'''
def __init__(self, sample_world, start_loc = (0.0, 0.0, 0.0), extent = (-10., 10., -10., 10.),
kernel_file = None, kernel_dataset = None, prior_dataset = None, init_lengthscale = 10.0,
init_variance = 100.0, noise = 0.05, path_generator = 'default', frontier_size = 6,
horizon_length = 5, turning_radius = 1, sample_step = 0.5, evaluation = None,
f_rew = 'mean', create_animation = False, learn_params = False):
''' Initialize the robot class with a GP model, initial location, path sets, and prior dataset
Inputs:
sample_world (method) a function handle that takes a set of locations as input and returns a set of observations
start_loc (tuple of floats) the location of the robot initially in 2-D space e.g. (0.0, 0.0, 0.0)
extent (tuple of floats): a tuple representing the max/min of 2D rectangular domain i.e. (-10, 10, -50, 50)
kernel_file (string) a filename specifying the location of the stored kernel values
kernel_dataset (tuple of nparrays) a tuple (xvals, zvals), where xvals is a Npoint x 2 nparray of type float and zvals is a Npoint x 1 nparray of type float
prior_dataset (tuple of nparrays) a tuple (xvals, zvals), where xvals is a Npoint x 2 nparray of type float and zvals is a Npoint x 1 nparray of type float
init_lengthscale (float) lengthscale param of kernel
init_variance (float) variance param of kernel
noise (float) the sensor noise parameter of kernel
path_generator (string): one of default, dubins, or equal_dubins. Robot path parameterization.
frontier_size (int): the number of paths in the generated path set
horizon_length (float): the length of the paths generated by the robot
turning_radius (float): the turning radius (in units of distance) of the robot
sample_set (float): the step size (in units of distance) between sequential samples on a trajectory
evaluation (Evaluation object): an evaluation object for performance metric compuation
f_rew (string): the reward function. One of {hotspot_info, mean, info_gain, exp_info, mes}
create_animation (boolean): save the generate world model and trajectory to file at each timestep
'''
# Parameterization for the robot
self.ranges = extent
self.create_animation = create_animation
self.eval = evaluation
self.loc = start_loc
self.sample_world = sample_world
self.f_rew = f_rew
self.fs = frontier_size
self.maxes = []
self.current_max = -1000
self.current_max_loc = [0,0]
self.max_locs = None
self.max_val = None
self.learn_params = learn_params
self.target = None
if f_rew == 'hotspot_info':
self.aquisition_function = hotspot_info_UCB
elif f_rew == 'mean':
self.aquisition_function = mean_UCB
elif f_rew == 'info_gain':
self.aquisition_function = info_gain
elif f_rew == 'mes':
self.aquisition_function = mves
elif f_rew == 'maxs-mes':
self.aquisition_function = mves_maximal_set
elif f_rew == 'exp_improve':
self.aquisition_function = exp_improvement
else:
raise ValueError('Only \'hotspot_info\' and \'mean\' and \'info_gain\' and \'mes\' and \'exp_improve\' reward fucntions supported.')
# Initialize the robot's GP model with the initial kernel parameters
self.GP = GPModel(ranges = extent, lengthscale = init_lengthscale, variance = init_variance)
# If both a kernel training dataset and a prior dataset are provided, train the kernel using both
if kernel_dataset is not None and prior_dataset is not None:
data = np.vstack([prior_dataset[0], kernel_dataset[0]])
observations = np.vstack([prior_dataset[1], kernel_dataset[1]])
self.GP.train_kernel(data, observations, kernel_file)
# Train the kernel using the provided kernel dataset
elif kernel_dataset is not None:
self.GP.train_kernel(kernel_dataset[0], kernel_dataset[1], kernel_file)
# If a kernel file is provided, load the kernel parameters
elif kernel_file is not None:
self.GP.load_kernel()
# No kernel information was provided, so the kernel will be initialized with provided values
else:
pass
# Incorporate the prior dataset into the model
if prior_dataset is not None:
self.GP.add_data(prior_dataset[0], prior_dataset[1])
# The path generation class for the robot
path_options = {'default':Path_Generator(frontier_size, horizon_length, turning_radius, sample_step, self.ranges),
'dubins': Dubins_Path_Generator(frontier_size, horizon_length, turning_radius, sample_step, self.ranges),
'equal_dubins': Dubins_EqualPath_Generator(frontier_size, horizon_length, turning_radius, sample_step, self.ranges)}
self.path_generator = path_options[path_generator]
def choose_trajectory(self, t):
''' Select the best trajectory avaliable to the robot at the current pose, according to the aquisition function.
Input:
t (int > 0): the current planning iteration (value of a point can change with algortihm progress)
Output:
either None or the (best path, best path value, all paths, all values, the max_locs for some functions)
'''
value = {}
param = None
max_locs = max_vals = None
if self.f_rew == 'mes' or self.f_rew == 'maxs-mes':
self.max_val, self.max_locs, self.target = sample_max_vals(self.GP, t = t)
paths = self.path_generator.get_path_set(self.loc)
for path, points in paths.items():
if self.f_rew == 'mes' or self.f_rew == 'maxs-mes':
param = (self.max_val, self.max_locs, self.target)
elif self.f_rew == 'exp_improve':
if len(self.maxes) == 0:
param = [self.current_max]
else:
param = self.maxes
value[path] = self.aquisition_function(time = t, xvals = points, robot_model = self.GP, param = param)
try:
return paths[max(value, key = value.get)], value[max(value, key = value.get)], paths, value, self.max_locs
except:
return None
def collect_observations(self, xobs):
''' Gather noisy samples of the environment and updates the robot's GP model.
Input:
xobs (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2 '''
zobs = self.sample_world(xobs)
self.GP.add_data(xobs, zobs)
for z, x in zip (zobs, xobs):
if z[0] > self.current_max:
self.current_max = z[0]
self.current_max_loc = [x[0],x[1]]
def predict_max(self):
# If no observations have been collected, return default value
if self.GP.xvals is None:
return np.array([0., 0.]).reshape(1,2), 0.
''' First option, return the max value observed so far '''
#return self.GP.xvals[np.argmax(self.GP.zvals), :], np.max(self.GP.zvals)
''' Second option: generate a set of predictions from model and return max '''
# Generate a set of observations from robot model with which to predict mean
x1vals = np.linspace(self.ranges[0], self.ranges[1], 30)
x2vals = np.linspace(self.ranges[2], self.ranges[3], 30)
x1, x2 = np.meshgrid(x1vals, x2vals, sparse = False, indexing = 'xy')
data = np.vstack([x1.ravel(), x2.ravel()]).T
observations, var = self.GP.predict_value(data)
return data[np.argmax(observations), :], np.max(observations)
def planner(self, T):
''' Gather noisy samples of the environment and updates the robot's GP model
Input:
T (int > 0): the length of the planning horization (number of planning iterations)'''
self.trajectory = []
for t in xrange(T):
# Select the best trajectory according to the robot's aquisition function
print("[", t, "] Current Location: ", self.loc)
logger.info("[{}] Current Location: {}".format(t, self.loc))
best_path, best_val, all_paths, all_values, max_locs = self.choose_trajectory(t = t)
# Given this choice, update the evaluation metrics
# TODO: fix this
pred_loc, pred_val = self.predict_max()
print("Current predicted max and value: \t", pred_loc, "\t", pred_val)
logger.info("Current predicted max and value: {} \t {}".format(pred_loc, pred_val))
try:
self.eval.update_metrics(len(self.trajectory), self.GP, all_paths, best_path, \
value = best_val, max_loc = pred_loc, max_val = pred_val, params = [self.current_max, self.current_max_loc, self.max_val, self.max_locs])
except:
max_locs = [[-1, -1], [-1, -1]]
max_val = [-1,-1]
self.eval.update_metrics(len(self.trajectory), self.GP, all_paths, best_path, \
value = best_val, max_loc = pred_loc, max_val = pred_val, params = [self.current_max, self.current_max_loc, max_val, max_locs])
if best_path == None:
break
data = np.array(best_path)
x1 = data[:,0]
x2 = data[:,1]
xlocs = np.vstack([x1, x2]).T
if len(best_path) != 1:
self.collect_observations(xlocs)
if t < T/3 and self.learn_params == True:
self.GP.train_kernel()
self.trajectory.append(best_path)
if self.create_animation:
self.visualize_trajectory(screen = False, filename = t, best_path = best_path,
maxes = max_locs, all_paths = all_paths, all_vals = all_values)
# if len(best_path) == 1:
# self.loc = (best_path[-1][0], best_path[-1][1], best_path[-1][2]-0.45)
# else:
self.loc = best_path[-1]
np.savetxt('./figures/' + self.f_rew+ '/robot_model.csv', (self.GP.xvals[:, 0], self.GP.xvals[:, 1], self.GP.zvals[:, 0]))
def visualize_trajectory(self, screen = True, filename = 'SUMMARY', best_path = None,
maxes = None, all_paths = None, all_vals = None):
''' Visualize the set of paths chosen by the robot
Inputs:
screen (boolean): determines whether the figure is plotted to the screen or saved to file
filename (string): substring for the last part of the filename i.e. '0', '1', ...
best_path (path object)
maxes (list of locations)
all_paths (list of path objects)
all_vals (list of all path rewards)
T (string or int): string append to the figure filename
'''
# Generate a set of observations from robot model with which to make contour plots
x1vals = np.linspace(self.ranges[0], self.ranges[1], 100)
x2vals = np.linspace(self.ranges[2], self.ranges[3], 100)
x1, x2 = np.meshgrid(x1vals, x2vals, sparse = False, indexing = 'xy')
data = np.vstack([x1.ravel(), x2.ravel()]).T
observations, var = self.GP.predict_value(data)
# Plot the current robot model of the world
fig, ax = plt.subplots(figsize=(8, 6))
ax.set_xlim(self.ranges[0:2])
ax.set_ylim(self.ranges[2:])
plot = ax.contourf(x1, x2, observations.reshape(x1.shape), cmap = 'viridis', vmin = MIN_COLOR, vmax = MAX_COLOR, levels=np.linspace(MIN_COLOR, MAX_COLOR, 15))
if self.GP.xvals is not None:
scatter = ax.scatter(self.GP.xvals[:, 0], self.GP.xvals[:, 1], c='k', s = 20.0, cmap = 'viridis')
color = iter(plt.cm.cool(np.linspace(0,1,len(self.trajectory))))
# Plot the current trajectory
for i, path in enumerate(self.trajectory):
c = next(color)
f = np.array(path)
plt.plot(f[:,0], f[:,1], c=c, marker='*')
# If available, plot the current set of options available to robot, colored
# by their value (red: low, yellow: high)
if all_paths is not None:
all_vals = [x for x in all_vals.values()]
path_color = iter(plt.cm.autumn(np.linspace(0, max(all_vals),len(all_vals))/ max(all_vals)))
path_order = np.argsort(all_vals)
for index in path_order:
c = next(path_color)
points = all_paths[all_paths.keys()[index]]
f = np.array(points)
plt.plot(f[:,0], f[:,1], c = c, marker='.')
# If available, plot the selected path in green
if best_path is not None:
f = np.array(best_path)
plt.plot(f[:,0], f[:,1], c = 'g', marker='*')