-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReachAvoid_CaseStudy.py
2705 lines (2449 loc) · 97.7 KB
/
ReachAvoid_CaseStudy.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
# %% [markdown]
# Top
#
# %%
# %%
# Value Iteration for PIMDP Reachability Checking
# Jesse Jiang
# Import classes
import numpy as np
# Import Aziz Phase Space Planning Helper
from psp import *
import csv
# Define state parameters
gridSize = 10
stateLength = 0.15
footLength = 0.14
angleSize = 15
angleLength = 360/angleSize
numStates = int(gridSize ** 2 * angleLength)*2
footSpace = 0.1
stepLength = 0.3
# Class for PIMDP state
class State:
# Constructor Method
def __init__(self, id, actions, lower, upper, stateType):
# Set state ID
self.id = id
# Possible actions
self.actions = actions
self.targets = [0]*len(actions)
# Lower transition bounds for each action
# Dictionary format for each action, {nextState:transitionProb}
self.lower = [lower[x] for x in range(len(actions))]
# Upper transition bounds for each action
self.upper = [upper[x] for x in range(len(actions))]
# Accepting = 'a', Rejecting = 'r', Uncertain = 'u'
self.stateType = stateType
# Initial probability of satisfying specification
# 1 if accepting, 0 if rejecting or uncertain
if stateType == 'a':
self.psat = 1
else:
self.psat = 0
# State parameters
self.center = []
# GP Parameters
self.zminState = 0
self.zmaxState = 0
self.zUncertaintyState = 0
self.dmin = [0]*len(actions)
self.dmax = [0]*len(actions)
self.zmin = [0]*len(actions)
self.zmax = [0]*len(actions)
self.zave = [0]*len(actions)
self.thetamin = [0]*len(actions)
self.thetamax = [0]*len(actions)
self.zUncertainty = [np.array([[0]])]*len(actions)
# Return state id
def getID(self):
return self.id
# Append a new action
def append(self, action, lower, upper):
self.actions.append(action)
self.lower.append(lower)
self.upper.append(upper)
# Remove an action
def remove(self, action):
idx = self.actions.index(action)
self.actions.pop(idx)
self.lower.pop(idx)
self.upper.pop(idx)
self.targets.pop(idx)
self.dmin.pop(idx)
self.dmax.pop(idx)
self.zmin.pop(idx)
self.zmax.pop(idx)
self.thetamin.pop(idx)
self.thetamax.pop(idx)
# Return probability of satisfying specification
def getPSat(self):
return self.psat
# Return set of actions
def getActions(self):
return self.actions
# Return lower transition probabilities for an action
def getLower(self, action):
idx = self.actions.index(action)
return self.lower[idx]
# Return upper transition probabilities for an action
def getUpper(self, action):
idx = self.actions.index(action)
return self.upper[idx]
# Return next states for a given action
def getNext(self, action):
idx = self.actions.index(action)
return self.lower[idx].keys()
# Set state type
def setStateType(self, stateType):
self.stateType = stateType
# Update transition probability
def update(self, action, lower, upper):
idx = self.actions.index(action)
self.lower[idx] = lower
self.upper[idx] = upper
# Set probability of satisfying specification
def setPSat(self, psat):
self.psat = psat
# Set optimal control action
def setOptAct(self, action):
self.optimalAction = action
# Set center point
def setCenter(self,center):
self.center = center
# Set target region for each action
def setTarget(self,action,target):
idx = self.actions.index(action)
self.targets[idx]=target
# Get state type
def getStateType(self):
return self.stateType
# Print info
def getInfo(self):
print("State ID: " + str(self.id))
for action in self.actions:
idx = self.actions.index(action)
print("Action " + action + "\nLower Transitions: ")
print(self.lower[idx])
print("Upper Transitions: ")
print(self.upper[idx])
print("\n")
# Get optimal control action
def getOptAct(self):
return self.optimalAction
# Get target region for each action
def getTarget(self,action):
idx = self.actions.index(action)
return self.targets[idx]
# Get center for state
def getCenter(self):
return self.center
# Class for PIMDP State Space
class StateSpace:
# Constructor Method
def __init__(self, states):
# Initialize state
self.states = states
# Initialize state IDs
self.ids = []
for state in states:
self.ids.append(state.getID())
# Initialize set of all actions
self.actions = []
self.lowers = []
self.uppers = []
self.psats = []
self.minOrder = 0
self.maxOrder = 0
# Append State
def append(self, state):
self.states.append(state)
self.ids.append(state.getID())
# Remove State
def remove(self, state):
self.states.remove(state)
self.ids.remove(state.getID())
# Find all feasible actions
def findActions(self):
# Loop through all states
self.actions=[]
for state in self.states:
# get actions
tempActions = state.getActions()
for action in tempActions:
# append new actions
if action not in self.actions:
self.actions.append(action)
# Find number of uncertain states
def countUncertain(self):
self.numUncertain = 0
for state in self.states:
if state.getStateType() == 'u':
self.numUncertain = self.numUncertain + 1
# Construct Lower and Upper Transition Probability Matrix
def constructTransitions(self):
self.lowers = []
self.uppers = []
# Create one transition matrix for each action
for action in self.actions:
tempLower = np.zeros([len(self.states),len(self.states)])
tempUpper = np.zeros([len(self.states),len(self.states)])
# Loop through states
for state in self.states:
id = state.getID()
# Append transition probabilities if applicable
if action in state.getActions():
next = state.getNext(action)
lower = state.getLower(action)
upper = state.getUpper(action)
for ns in next:
tempLower[ns,id] = lower.get(ns)
tempUpper[ns,id] = upper.get(ns)
self.lowers.append(tempLower)
self.uppers.append(tempUpper)
# Construct vector of PSats
def getPSats(self):
self.psats=np.empty([len(self.states),1])
# Loop through states and append PSats
for state in range(len(self.states)):
self.psats[state] = self.states[state].getPSat()
# Construct list of optimal actions
def getOptActs(self):
self.optActs=[]
# Loop through states and append PSats
for state in self.states:
self.optActs.append(state.getOptAct())
# Order states
def orderStates(self):
self.getPSats()
# Return states ordered from lowest PSat to highest
return np.argsort(self.psats,axis=0)
# Construct minimizing transition matrix based on state ordering
def orderMinTransitions(self):
self.orderedTransitions = []
# Sort states from lowest to highest PSat
self.order = self.orderStates()
self.minOrder = self.order
# Loop through each transition matrix
for act in range(len(self.actions)):
lower = self.lowers[act]
upper = self.uppers[act]
tempMat = np.zeros([len(self.states),len(self.states)])
# Loop through each row
for col in range(len(self.states)):
# Loop through each potential ordering
self.remainder = 0
# Identify potential transition states
if not self.actions[act] in self.states[col].getActions():
tempMat[:,col]=0
else:
ids = np.fromiter(self.states[col].getNext(self.actions[act]),dtype=int)
orig_indices = np.squeeze(self.order.argsort(axis=0))
ndx = orig_indices[np.searchsorted(np.squeeze(self.order[orig_indices]), ids)]
for i in np.sort(ndx):
self.remainder = 0
# Add appropriate lower and upper probabilities
probs = np.sum(upper[self.order[0:i],col]) + np.sum(lower[self.order[i+1:],col])
# Check if remainder is a valid probability
diff = 1-probs
if ((diff<=upper[self.order[i],col]) and (diff>=lower[self.order[i],col])):
self.remainder = diff
break
# Assign final transition probabilities
tempMat[self.order[0:i],col] = upper[self.order[0:i],col]
tempMat[self.order[i+1:],col] = lower[self.order[i+1:],col]
tempMat[self.order[i],col] = self.remainder
# Construct final matrix for given action
self.orderedTransitions.append(tempMat)
# Construct minimizing transition matrix based on predetermined state ordering
def orderMinTransitionsSimple(self,order):
self.orderedTransitions = []
# Sort states from lowest to highest PSat
self.order = order
# Loop through each transition matrix
for act in range(len(self.actions)):
lower = self.lowers[act]
upper = self.uppers[act]
tempMat = np.zeros([len(self.states),len(self.states)])
# Loop through each row
for col in range(len(self.states)):
# Loop through each potential ordering
self.remainder = 0
# Identify potential transition states
if not self.actions[act] in self.states[col].getActions():
tempMat[:,col]=0
else:
ids = np.fromiter(self.states[col].getNext(self.actions[act]),dtype=int)
orig_indices = np.squeeze(self.order.argsort(axis=0))
ndx = orig_indices[np.searchsorted(np.squeeze(self.order[orig_indices]), ids)]
for i in np.sort(ndx):
self.remainder = 0
# Add appropriate lower and upper probabilities
probs = np.sum(upper[self.order[0:i],col]) + np.sum(lower[self.order[i+1:],col])
# Check if remainder is a valid probability
diff = 1-probs
if ((diff<=upper[self.order[i],col]) and (diff>=lower[self.order[i],col])):
self.remainder = diff
break
# Assign final transition probabilities
tempMat[self.order[0:i],col] = upper[self.order[0:i],col]
tempMat[self.order[i+1:],col] = lower[self.order[i+1:],col]
tempMat[self.order[i],col] = self.remainder
# Construct final matrix for given action
self.orderedTransitions.append(tempMat)
# Construct maximizing transition matrix based on state ordering
def orderMaxTransitions(self):
self.orderedTransitions = []
# Sort states from lowest to highest PSat
self.order = self.orderStates()
self.order = self.order[::-1]
self.maxOrder = self.order
# Loop through each transition matrix
for act in range(len(self.actions)):
lower = self.lowers[act]
upper = self.uppers[act]
tempMat = np.zeros([len(self.states),len(self.states)])
# Loop through each row
for col in range(len(self.states)):
# Loop through each potential ordering
self.remainder = 0
# Identify potential transition states
if not self.actions[act] in self.states[col].getActions():
tempMat[:,col]=0
else:
ids = np.fromiter(self.states[col].getNext(self.actions[act]),dtype=int)
orig_indices = np.squeeze(self.order.argsort(axis=0))
ndx = orig_indices[np.searchsorted(np.squeeze(self.order[orig_indices]), ids)]
for i in np.sort(ndx):
self.remainder = 0
# Add appropriate lower and upper probabilities
probs = np.sum(upper[self.order[0:i],col]) + np.sum(lower[self.order[i+1:],col])
# Check if remainder is a valid probability
diff = 1-probs
if ((diff<=upper[self.order[i],col]) and (diff>=lower[self.order[i],col])):
self.remainder = diff
break
# Assign final transition probabilities
tempMat[self.order[0:i],col] = upper[self.order[0:i],col]
tempMat[self.order[i+1:],col] = lower[self.order[i+1:],col]
tempMat[self.order[i],col] = self.remainder
# Construct final matrix for given action
self.orderedTransitions.append(tempMat)
# Construct maximizing transition matrix based on predetermined state ordering
def orderMaxTransitionsSimple(self,order):
self.orderedTransitions = []
# Sort states from lowest to highest PSat
self.order = order
# Loop through each transition matrix
for act in range(len(self.actions)):
lower = self.lowers[act]
upper = self.uppers[act]
tempMat = np.zeros([len(self.states),len(self.states)])
# Loop through each row
for col in range(len(self.states)):
# Loop through each potential ordering
self.remainder = 0
# Identify potential transition states
if not self.actions[act] in self.states[col].getActions():
tempMat[:,col]=0
else:
ids = np.fromiter(self.states[col].getNext(self.actions[act]),dtype=int)
orig_indices = np.squeeze(self.order.argsort(axis=0))
ndx = orig_indices[np.searchsorted(np.squeeze(self.order[orig_indices]), ids)]
for i in np.sort(ndx):
self.remainder = 0
# Add appropriate lower and upper probabilities
probs = np.sum(upper[self.order[0:i],col]) + np.sum(lower[self.order[i+1:],col])
# Check if remainder is a valid probability
diff = 1-probs
if ((diff<=upper[self.order[i],col]) and (diff>=lower[self.order[i],col])):
self.remainder = diff
break
# Assign final transition probabilities
tempMat[self.order[0:i],col] = upper[self.order[0:i],col]
tempMat[self.order[i+1:],col] = lower[self.order[i+1:],col]
tempMat[self.order[i],col] = self.remainder
# Construct final matrix for given action
self.orderedTransitions.append(tempMat)
# Perform a single iteration of algorithm
def iterate(self):
pTrans = np.zeros((len(self.states),len(self.actions)))
# Do matrix-vector multiplication for each action
for act in range(len(self.actions)):
pTrans[:,act] = np.squeeze(np.transpose(self.orderedTransitions[act]) @ self.psats)
# Maximize PSat for each state
i=0
for state in self.states:
# Find valid actions
idx = []
for act in state.getActions():
idx.append(self.actions.index(act))
val = np.amax(pTrans[i,idx],axis=0)
state.setPSat(np.amax(pTrans[i,idx],axis=0))
idx = np.nonzero(pTrans[i,idx]==val)[0]
acts = []
for j in idx:
acts.append(state.getActions()[j])
state.setOptAct(acts)
i=i+1
return self.psats
# Repeat value iteration until condition is met
def valueIterationMin(self):
# Find all available actions
self.findActions()
print("Find Actions")
# Construct upper and lower transition matrices
self.constructTransitions()
print("Construct Transitions")
# Get initial PSats
self.getPSats()
print("Get PSats")
i = 0
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Construct ordered transition matrix
self.orderMinTransitions()
print("Order Min Transitions")
# Perform iteration
self.iterate()
self.getPSats()
i=i+1
# While probabilities are not steady state
print("Begin Loop")
while(np.amax(np.abs(oldPsats-self.psats))>0.05):
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Iterate
self.orderMinTransitions()
self.iterate()
self.getPSats()
i=i+1
print(np.amax(np.abs(oldPsats-self.psats)))
print("End Loop")
# Once probabilities are set, get optimal actions for each state
self.getOptActs()
#print("Optimal Actions: ")
#print(self.optActs)
# Simplified value iteration using precomputed state ordering
def valueIterationMinSimple(self):
# Find all available actions
self.findActions()
print("Find Actions")
# Construct upper and lower transition matrices
self.constructTransitions()
print("Construct Transitions")
# Get initial PSats
self.getPSats()
print("Get PSats")
i = 0
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Construct ordered transition matrix
self.orderMinTransitionsSimple(self.minOrder)
print("Order Min Transitions")
# Perform iteration
self.iterate()
self.getPSats()
i=i+1
# While probabilities are not steady state
print("Begin Loop")
while(np.amax(np.abs(oldPsats-self.psats))>0.05):
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Iterate
#self.orderMinTransitions()
self.iterate()
self.getPSats()
i=i+1
print(np.amax(np.abs(oldPsats-self.psats)))
print("End Loop")
# Once probabilities are set, get optimal actions for each state
self.getOptActs()
#print("Optimal Actions: ")
#print(self.optActs)
# Repeat value iteration until condition is met
def valueIterationMax(self):
# Find all available actions
self.findActions()
# Construct upper and lower transition matrices
self.constructTransitions()
# Get initial PSats
self.getPSats()
i = 0
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Construct ordered transition matrix
self.orderMaxTransitions()
# Perform iteration
self.iterate()
self.getPSats()
i=i+1
# While probabilities are not steady state
while(np.amax(np.abs(oldPsats-self.psats))>0.01):
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Iterate
self.orderMaxTransitions()
self.iterate()
self.getPSats()
i=i+1
# Once probabilities are set, get optimal actions for each state
self.getOptActs()
#print("Optimal Actions: ")
#print(self.optActs)
# Simplified value iteration using precomputed state ordering
def valueIterationMaxSimple(self):
# Find all available actions
self.findActions()
# Construct upper and lower transition matrices
self.constructTransitions()
# Get initial PSats
self.getPSats()
i = 0
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Construct ordered transition matrix
self.orderMaxTransitionsSimple(self.maxOrder)
# Perform iteration
self.iterate()
self.getPSats()
i=i+1
# While probabilities are not steady state
while(np.amax(np.abs(oldPsats-self.psats))>0.01):
#print("Iteration " + str(i))
#print(self.psats)
oldPsats = self.psats
# Iterate
#self.orderMaxTransitions()
self.iterate()
self.getPSats()
i=i+1
# Once probabilities are set, get optimal actions for each state
self.getOptActs()
#print("Optimal Actions: ")
#print(self.optActs)
# Print states
def getInfo(self):
print("State Space\n")
for state in self.states:
state.getInfo()
# %% [markdown]
# True GP Terrain
# %%
# Gaussian Process Setup for True Terrain Dynamics
import math
class GaussianProcessTrueTerrain:
# Constructor Method
def __init__(self):
# Initialize variance such that all known g(x) are within one standard deviation
self.variance = 0.025**2
# Initialize length
self.l = 0.1
# Initialize Data Points
self.pos = np.empty((2,0))
self.val = np.empty((1,0))
self.ZZ = []
# Add Data Samples
def append(self,pos,val):
# Append coordinate position
self.pos = pos
# Append g(x) value
self.val = val
# Construct Correlation Matrix
def correlation(self, X1, X2):
# Initialize correlation matrix
K = np.zeros((X1.shape[1], X2.shape[1]))
# Loop through all matrix entries
for i in np.arange(X1.shape[1]):
for j in np.arange(X2.shape[1]):
K[i,j] = self.variance*math.exp(-(np.linalg.norm(X1[:,i]-X2[:,j])**2)/(2*self.l**2))
return K
# Calculate correlations
def train(self):
self.ZZ = np.linalg.inv(self.correlation(self.pos,self.pos))
# Calculate predicted mean at a point
def calcMean(self,pos):
# edge case with no samples
if self.pos.shape[1] == 0:
return np.array([[0]])
return self.correlation(pos,self.pos)@[email protected]
# Calculate predicted variance at a point
def calcVariance(self, pos):
# edge case with no samples
if self.pos.shape[1] == 0:
return np.array([[self.variance]])
return self.correlation(pos,pos)-self.correlation(pos,self.pos)@[email protected](self.pos,pos)
# %%
# %%
# Sparse Gaussian Process
# Code adapted from Martin Krasser
import jax.numpy as jnp
import jax.scipy as jsp
from jax import random, jit, value_and_grad
from jax.config import config
from scipy.optimize import minimize
config.update("jax_enable_x64", True)
# SGP for Terrain Setup
class SparseGaussianProcessTerrain:
# Constructor Method
def __init__(self):
# Initialize variance such that all known g(x) are within one standard deviation
self.variance = 0.025 ** 2
# Initialize length
self.l = 0.1
# Initialize Data Points
self.pos = np.empty((2,0))
self.val = np.empty((1,0))
# Initialize stochastic noise variance
self.noiseVariance = 0.01 ** 2
self.noiseStd = 0.01
self.ZZ = []
# Initialize number of inducing variables
self.m = 25
self.theta_opt = []
# Add Data Samples
def append(self,pos,val):
# Append coordinate position
self.pos = pos
# Append g(x) value
self.val = val
def calcMean(self,pos):
# edge case with no samples
if self.pos.shape[1] == 0:
return np.array([[0]])
f_test, f_test_cov = q_T(pos.T, self.theta_opt, self.X_m_opt, self.mu_m_opt, self.A_m_opt, self.K_mm_inv)
return f_test
def calcVariance(self,pos):
# edge case with no samples
if self.pos.shape[1] == 0:
return np.array([[self.variance]])
f_test, f_test_cov = q_T(pos.T, self.theta_opt, self.X_m_opt, self.mu_m_opt, self.A_m_opt, self.K_mm_inv)
f_test_cov = np.where(f_test_cov<0,0,f_test_cov)
f_test_var = np.diag(f_test_cov)
f_test_std = np.sqrt(f_test_var)
return f_test_std
def correlation(self, X1, X2):
# Initialize correlation matrix
K = np.zeros((X1.shape[1], X2.shape[1]))
# Loop through all matrix entries
for i in np.arange(X1.shape[1]):
for j in np.arange(X2.shape[1]):
K[i,j] = self.variance*math.exp(-(np.linalg.norm(X1[:,i]-X2[:,j])**2)/(2*self.l**2))
return K
def train(self):
# Optimized kernel parameters and inducing inputs
#self.theta_opt, self.X_m_opt = opt(self.pos,self.val,self.m,self.noiseStd)
self.X_m_opt = opt_T(self.pos,self.val,self.m,self.noiseStd)
self.mu_m_opt, self.A_m_opt, self.K_mm_inv = phi_opt_T(self.theta_opt, self.X_m_opt, self.pos.T, self.val.T, self.noiseStd)
# %% [markdown]
#
# Sparse GP Terrain
#
# %%
# %%
# Sparse Gaussian Process Methods for Terrain
# Kernel hyperparameters (length,standard deviation)
theta_fixed_T = jnp.array([0.1,0.1])
def kernel_T(X1, X2, theta):
"""
Isotropic squared exponential kernel.
Args:
X1: Array of m points (m, d).
X2: Array of n points (n, d).
theta: kernel parameters (2,)
"""
sqdist = jnp.sum(X1 ** 2, 1).reshape(-1,1) + jnp.sum(X2 ** 2, 1) - 2 * jnp.dot(X1, X2.T)
return theta[1] ** 2 * jnp.exp(-0.5 / theta[0] ** 2 * sqdist)
def kernel_diag_T(d, theta):
"""
Isotropic squared exponential kernel (computes diagonal elements only).
"""
return jnp.full(shape=d, fill_value=theta[0] ** 2)
def jitter(d, value=1e-6):
return jnp.eye(d) * value
def softplus(X):
return jnp.log(1 + jnp.exp(X))
def softplus_inv(X):
return jnp.log(jnp.exp(X) - 1)
def pack_params(theta, X_m):
return jnp.concatenate([softplus_inv(theta), X_m.ravel()])
def unpack_params_T(params):
return softplus(params[:2]), jnp.array(params[2:].reshape(-1, 2))
def nlb_fn_T(X, y, sigma_y):
n = X.shape[0]
def nlb(params):
"""
Negative lower bound on log marginal likelihood.
Args:
params: kernel parameters `theta` and inducing inputs `X_m`
"""
theta, X_m = unpack_params_T(params)
K_mm = kernel_T(X_m, X_m, theta) + jitter(X_m.shape[0])
K_mn = kernel_T(X_m, X, theta)
L = jnp.linalg.cholesky(K_mm) # m x m
A = jsp.linalg.solve_triangular(L, K_mn, lower=True) / sigma_y # m x n
AAT = A @ A.T # m x m
B = jnp.eye(X_m.shape[0]) + AAT # m x m
LB = jnp.linalg.cholesky(B) # m x m
c = jsp.linalg.solve_triangular(LB, A.dot(y), lower=True) / sigma_y # m x 1
# Equation (13)
lb = - n / 2 * jnp.log(2 * jnp.pi)
lb -= jnp.sum(jnp.log(jnp.diag(LB)))
lb -= n / 2 * jnp.log(sigma_y ** 2)
lb -= 0.5 / sigma_y ** 2 * y.T.dot(y)
lb += 0.5 * c.T.dot(c)
lb -= 0.5 / sigma_y ** 2 * jnp.sum(kernel_diag_T(n, theta))
lb += 0.5 * jnp.trace(AAT)
return -lb[0, 0]
# nlb_grad returns the negative lower bound and
# its gradient w.r.t. params i.e. theta and X_m.
nlb_grad = jit(value_and_grad(nlb))
def nlb_grad_wrapper(params):
value, grads = nlb_grad(params)
# scipy.optimize.minimize cannot handle
# JAX DeviceArray directly. a conversion
# to Numpy ndarray is needed.
return np.array(value), np.array(grads)
return nlb_grad_wrapper
# Run optimization
def opt_T(pos,val,m,noiseStd):
# Initialize inducing inputs
indices = jnp.floor(jnp.linspace(0,pos.shape[1]-1,m)).astype(int)
X_m = jnp.array(pos.T[indices,:])
res = minimize(fun=nlb_fn_T(pos.T, val.T, noiseStd),
x0=pack_params(theta_fixed_T, X_m),
method='L-BFGS-B',
jac=True)
# Optimized kernel parameters and inducing inputs
theta_opt, X_m_opt = unpack_params_T(res.x)
return X_m_opt
@jit
def phi_opt_T(theta, X_m, X, y, sigma_y):
theta = theta_fixed_T
"""Optimize mu_m and A_m using Equations (11) and (12)."""
precision = (1.0 / sigma_y ** 2)
K_mm = kernel_T(X_m, X_m, theta) + jitter(X_m.shape[0])
K_mm_inv = jnp.linalg.inv(K_mm)
K_nm = kernel_T(X, X_m, theta)
K_mn = K_nm.T
Sigma = jnp.linalg.inv(K_mm + precision * K_mn @ K_nm)
mu_m = precision * (K_mm @ Sigma @ K_mn).dot(y)
A_m = K_mm @ Sigma @ K_mm
return mu_m, A_m, K_mm_inv
@jit
def q_T(X_test, theta, X_m, mu_m, A_m, K_mm_inv):
"""
Approximate posterior.
Computes mean and covariance of latent
function values at test inputs X_test.
"""
theta = theta_fixed_T
K_ss = kernel_T(X_test, X_test, theta)
K_sm = kernel_T(X_test, X_m, theta)
K_ms = K_sm.T
f_q = (K_sm @ K_mm_inv).dot(mu_m)
f_q_cov = K_ss - K_sm @ K_mm_inv @ K_ms + K_sm @ K_mm_inv @ A_m @ K_mm_inv @ K_ms
return f_q, f_q_cov
# %%
# %%
# Sparse Gaussian Process for Model Error
# Code adapted from Martin Krasser
noiseStd = 2.5
# Compensate for yaw error with nonzero mean
meanYawError = 7.5
class SparseGaussianProcessModel:
# Constructor Method
def __init__(self):
# Initialize variance such that all known g(x) are within one standard deviation
self.variance = meanYawError ** 2
# Initialize length
self.l = [1,5,0.1,0.5]
# Initialize Data Points
self.pos = np.empty((3,0))
self.val = np.empty((1,0))
# Initialize stochastic noise variance
self.noiseVariance = noiseStd ** 2
self.noiseStd = noiseStd
self.ZZ = []
# Initialize number of inducing variables
self.m = 25
self.theta_opt = []
# Add Data Samples
def append(self,pos,val):
# Append coordinate position
self.pos = pos
# Append g(x) value
self.val = val
def calcMean(self,pos):
# edge case with no samples
if self.pos.shape[1] == 0:
return np.array([[0]])
f_test, f_test_cov = q_M(pos.T, self.theta_opt, self.X_m_opt, self.mu_m_opt, self.A_m_opt, self.K_mm_inv)
if math.isnan(f_test):
return 0
if f_test>meanYawError:
f_test=meanYawError
elif f_test <-meanYawError:
f_test=-meanYawError
return f_test
def calcVariance(self,pos):
# edge case with no samples
if self.pos.shape[1] == 0:
return np.array([[self.variance]])
f_test, f_test_cov = q_M(pos.T, self.theta_opt, self.X_m_opt, self.mu_m_opt, self.A_m_opt, self.K_mm_inv)
f_test_cov = np.where(f_test_cov<0,0,f_test_cov)
f_test_var = np.diag(f_test_cov)
f_test_std = np.sqrt(f_test_var)
#print(f_test_var)
return f_test_std
def correlation(self, X1, X2):
# Initialize correlation matrix
# K = np.zeros((X1.shape[1], X2.shape[1]))
# # Loop through all matrix entries
# for i in np.arange(X1.shape[1]):
# for j in np.arange(X2.shape[1]):
# diff = np.mod(X1[:,i]-X2[:,j],180)
# if diff[1]>180:
# diff[1]=360-diff[1]
# K[i,j] = self.variance*math.exp(-0.5*(diff@make_diag(self.l)@diff))
theta_fixed = jnp.array([0.2,15,0.1,5])
return np.array(kernel_M(X1.T,X2.T,theta_fixed))
def train(self):
# Optimized kernel parameters and inducing inputs
#self.theta_opt, self.X_m_opt = opt(self.pos,self.val,self.m,self.noiseStd)
self.X_m_opt = opt_M(self.pos,self.val,self.m,self.noiseStd)
self.mu_m_opt, self.A_m_opt, self.K_mm_inv = phi_opt_M(self.theta_opt, self.X_m_opt, self.pos.T, self.val.T, self.noiseStd)
# %% [markdown]
#
# Sparse GP Model Error
#
# %%
# Sparse Gaussian Process Methods for Model Error GP
# Kernel hyperparameters (length,standard deviation)
# d, theta, z, foot
theta_fixed_M = jnp.array([1,15,0.1,0.5,meanYawError])
def kernel_M(X1, X2, theta):
"""
Anisotropic squared exponential kernel.
Args:
X1: Array of m points (m, d).
X2: Array of n points (n, d).
theta: kernel parameters (5,)
"""
sqdist0 = ((X1[:,0] ** 2).reshape(-1,1) + (X2[:,0] ** 2).reshape(1,-1) - 2 * X1[:,0].reshape(-1,1)@X2[:,0].reshape(1,-1))/(theta[0]**2)
sqdist1 = ((X1[:,1] ** 2).reshape(-1,1) + (X2[:,1] ** 2).reshape(1,-1) - 2 * X1[:,1].reshape(-1,1)@X2[:,1].reshape(1,-1))
sqdist1 = jnp.where(sqdist1>180**2,(360-jnp.sqrt(sqdist1))**2,sqdist1)
sqdist1 = sqdist1/(theta[1]**2)
sqdist2 = ((X1[:,2] ** 2).reshape(-1,1) + (X2[:,2] ** 2).reshape(1,-1) - 2 * X1[:,2].reshape(-1,1)@X2[:,2].reshape(1,-1))/(theta[2]**2)
sqdist3 = ((X1[:,3] ** 2).reshape(-1,1) + (X2[:,3] ** 2).reshape(1,-1) - 2 * X1[:,3].reshape(-1,1)@X2[:,3].reshape(1,-1))/(theta[3]**2)
return theta[1] ** 2 * jnp.exp(-0.5 * (sqdist0+sqdist1+sqdist2+sqdist3))
def kernel_diag_M(d, theta):
"""
Isotropic squared exponential kernel (computes diagonal elements only).
"""
return jnp.full(shape=d, fill_value=theta[0:-1] ** 2)
# Create diagonal matrix of length parameters
def make_diag(theta):
return jnp.diag(1.0/(theta[0:-1]**2))
def unpack_params_M(params):
return softplus(params[:5]), jnp.array(params[5:].reshape(-1, 4))
def nlb_fn_M(X, y, sigma_y):
n = X.shape[1]
def nlb(params):
"""
Negative lower bound on log marginal likelihood.
Args:
params: kernel parameters `theta` and inducing inputs `X_m`
"""