-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLegiblePathQRCost.py
More file actions
3005 lines (2274 loc) · 109 KB
/
LegiblePathQRCost.py
File metadata and controls
3005 lines (2274 loc) · 109 KB
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
import os
import sys
module_path = os.path.abspath(os.path.join('../ilqr'))
if module_path not in sys.path:
sys.path.append(module_path)
import copy
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import decimal
import copy
import time
from datetime import timedelta, datetime
import matplotlib.ticker as mtick
from matplotlib import cm
import matplotlib
from ilqr import iLQR
from ilqr.cost import Cost
from ilqr.cost import QRCost
from ilqr.cost import PathQRCost, AutoDiffCost, FiniteDiffCost
from ilqr.dynamics import constrain
from ilqr.examples.pendulum import InvertedPendulumDynamics
from ilqr.dynamics import BatchAutoDiffDynamics, tensor_constrain
from scipy.optimize import approx_fprime
import utility_legibility as legib
import utility_environ_descrip as resto
import pipeline_generate_paths as pipeline
import pdb
from random import randint
import pandas as pd
from matplotlib import colors
import matplotlib.colors as colors
from autograd import grad, elementwise_grad, jacobian, hessian
import PathingExperiment as ex
np.set_printoptions(suppress=True)
PREFIX_EXPORT = 'experiment_outputs/'
FLAG_SHOW_IMAGE_POPUP = False
goal_colors = ['#980000', '#e69138', '#f1c232', '#38761d', '#1155cc', '#9900ff']
# Base class for all of our legible pathing offshoots
class LegiblePathQRCost(FiniteDiffCost):
PREFIX_EXPORT = PREFIX_EXPORT
FLAG_DEBUG_J = False
FLAG_DEBUG_STAGE_AND_TERM = False
coeff_terminal = 10000.0
scale_term = 0.01 # 1/100
# scale_stage = 1.5
scale_stage = 2
scale_obstacle = 0
state_size = 3
action_size = 2
# The coefficients weigh how much your state error is worth to you vs
# the size of your controls. You can favor a solution that uses smaller
# controls by increasing R's coefficient.
# Q = 1.0 * np.eye(state_size)
# R = 200.0 * np.eye(action_size)
# Qf = np.identity(state_size) * 400.0
"""Quadratic Regulator Instantaneous Cost for trajectory following."""
def __init__(self, exp, x_path, u_path):
# print(exp,
# exp.get_Q(),
# exp.get_R(),
# exp.get_Qf(),
# x_path,
# u_path,
# exp.get_start(),
# exp.get_target_goal(),
# exp.get_goals(),
# exp.get_N(),
# exp.get_dt())
# print(exp.get_Q().shape,
# exp.get_R().shape,
# exp.get_Qf().shape)
self.legib_path_cost_make_self(
exp,
exp.get_Q(),
exp.get_R(),
exp.get_Qf(),
x_path,
u_path,
exp.get_start(),
exp.get_target_goal(),
exp.get_goals(),
exp.get_N(),
exp.get_dt(),
restaurant=exp.get_restaurant(),
file_id=exp.get_file_id()
)
def legib_path_cost_make_self(self, exp, Q, R, Qf, x_path, u_path, start, target_goal, goals, N, dt, restaurant=None, file_id=None, Q_terminal=None):
"""Constructs a QRCost.
Args:
Q: Quadratic state cost matrix [state_size, state_size].
R: Quadratic control cost matrix [action_size, action_size].
x_path: Goal state path [N+1, state_size].
u_path: Goal control path [N, action_size].
Q_terminal: Terminal quadratic state cost matrix
[state_size, state_size].
"""
self.exp = exp
self.Q = np.array(Q)
self.Qf = np.array(Qf)
self.R = np.array(R)
# self.R = np.eye(2)*10000
self.x_path = np.array(x_path)
self.start = np.array(start)
self.goals = goals
self.target_goal = target_goal
self.N = N
self.dt = dt
if file_id is None:
self.file_id = datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p")
else:
self.file_id = file_id
# Create a restaurant object for using those utilities, functions, and print functions
# dim gives the dimensions of the restaurant
if restaurant is None:
self.restaurant = resto.Restaurant(resto.TYPE_CUSTOM, tables=[], goals=goals, start=start, observers=[], dim=None)
else:
self.restaurant = restaurant
self.f_func = self.get_f()
state_size = self.Q.shape[0]
action_size = self.R.shape[0]
path_length = self.x_path.shape[0]
x_eps = .1 #05
u_eps = .05 #05
self._x_eps = x_eps
self._u_eps = u_eps
self._x_eps_hess = x_eps #np.sqrt(self._x_eps)
self._u_eps_hess = u_eps #np.sqrt(self._u_eps)
self._state_size = state_size
self._action_size = action_size
if Q_terminal is None:
self.Q_terminal = self.Q
else:
self.Q_terminal = np.array(Q_terminal)
if u_path is None:
self.u_path = np.zeros(path_length - 1, action_size)
else:
self.u_path = np.array(u_path)
assert self.Q.shape == self.Q_terminal.shape, "Q & Q_terminal mismatch"
assert self.Q.shape[0] == self.Q.shape[1], "Q must be square"
assert self.R.shape[0] == self.R.shape[1], "R must be square"
assert state_size == self.x_path.shape[1], "Q & x_path mismatch"
assert action_size == self.u_path.shape[1], "R & u_path mismatch"
assert path_length == self.u_path.shape[0] + 1, \
"x_path must be 1 longer than u_path"
# Precompute some common constants.
self._Q_plus_Q_T = self.Q + self.Q.T
self._R_plus_R_T = self.R + self.R.T
self._Q_plus_Q_T_terminal = self.Q_terminal + self.Q_terminal.T
FiniteDiffCost.__init__(
self,
self.l,
self.term_cost,
state_size,
action_size,
x_eps=x_eps,
u_eps=u_eps,
)
def get_target_goal(self):
return self.exp.get_target_goal()
def init_output_log(self, dash_folder):
n = 5
rand_id = ''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
output_path = Path(self.get_export_label(dash_folder) + '-' + str(rand_id) + '--output.txt')
f = open(output_path, "w")
f.write("")
f.close()
sys.stdout = open(output_path,'a')
def get_f(self):
f_label = self.exp.get_f_label()
print(f_label)
if f_label is ex.F_OG_LINEAR:
def f(i):
return self.N - i
elif f_label is ex.F_VIS_LIN:
def f(i):
pt = self.x_path[i]
restaurant = self.exp.get_restaurant()
observers = restaurant.get_observers()
visibility = legib.get_visibility_of_pt_w_observers_ilqr(pt, observers, normalized=True)
# Can I see this point from each observer who is targeted
return visibility
else:
def f(i):
return 1.0
return f
print("ERROR, NO KNOWN SOLVER, PLEASE ADD A VALID SOLVER TO EXP")
# How far away is the final step in the path from the goal?
def term_cost(self, x, i):
start = self.start
goal1 = self.target_goal
# Qf = self.Q_terminal
Qf = self.Qf
R = self.R
# x_diff = x - self.x_path[i]
x_diff = x - self.x_path[self.N]
squared_x_cost = .5 * x_diff.T.dot(Qf).dot(x_diff)
# squared_x_cost = squared_x_cost * squared_x_cost
scaler = 1.0 / self.exp.get_dt()
terminal_cost = squared_x_cost * scaler
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("term cost squared x cost")
print(squared_x_cost)
# We want to value this highly enough that we don't not end at the goal
# terminal_coeff = 100.0
coeff_terminal = self.exp.get_solver_coeff_terminal()
terminal_cost = terminal_cost * coeff_terminal
# Once we're at the goal, the terminal cost is 0
# Attempted fix for paths which do not hit the final mark
# if squared_x_cost > .001:
# terminal_cost *= 1000.0
return terminal_cost
# original version for plain path following
def l_og(self, x, u, i, terminal=False):
"""Instantaneous cost function.
Args:
x: Current state [state_size].
u: Current control [action_size]. None if terminal.
i: Current time step.
terminal: Compute terminal cost. Default: False.
Returns:
Instantaneous cost (scalar).
"""
Q = self.Q_terminal if terminal else self.Q
R = self.R
x_diff = x - self.x_path[i]
squared_x_cost = x_diff.T.dot(Q).dot(x_diff)
if terminal:
return squared_x_cost
u_diff = u - self.u_path[i]
return squared_x_cost + u_diff.T.dot(R).dot(u_diff)
# original version for plain path following
def l(self, x, u, i, terminal=False, just_term=False, just_stage=False):
"""Instantaneous cost function.
Args:
x: Current state [state_size].
u: Current control [action_size]. None if terminal.
i: Current time step.
terminal: Compute terminal cost. Default: False.
Returns:
Instantaneous cost (scalar).
"""
Q = self.Qf if terminal else self.Q
R = self.R
start = self.start
goal = self.target_goal
thresh = .0001
scale_term = self.exp.get_solver_scale_term() #0.01 # 1/100
scale_stage = self.exp.get_solver_scale_stage() #1.5
if just_term:
scale_stage = 0
if just_stage:
scale_term = 0
term_cost = 0 #self.term_cost(x, i)
x_diff = x - self.x_path[i]
u_diff = 0
if i < len(self.u_path):
u_diff = u - self.u_path[i]
if terminal or just_term: #abs(i - self.N) < thresh or
# TODO verify not a magic number
return scale_term * self.term_cost(x, i) # * 1000
else:
if self.FLAG_DEBUG_STAGE_AND_TERM:
# difference between this step and the end
print("x, N, x_end_of_path -> inputs and then term cost")
print(x, self.N, self.x_path[self.N])
# term_cost = self.term_cost(x, i)
print(term_cost)
term_cost = 0 #self.term_cost(x, i)
f_func = self.get_f()
f_value = f_func(i)
J = self.michelle_stage_cost(start, goal, x, u, i, terminal) * f_value
wt_legib = -1.0
wt_lam = .1
wt_control = 3.0
J = (wt_legib * J)
J += (wt_control * u_diff.T.dot(R).dot(u_diff))
J += (wt_lam * x_diff.T.dot(Q).dot(x_diff))
stage_costs = J
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("STAGE,\t TERM")
print(stage_costs, term_cost)
total = (scale_term * term_cost) + (scale_stage * stage_costs)
return float(total)
def f(self, t):
return 1.0 #self.N - t #1.0
def get_total_stage_cost(self, start, goal, x, u, i, terminal):
N = self.N
R = self.R
stage_costs = 0.0 #u_diff.T.dot(R).dot(u_diff)
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("u = " + str(u))
print("Getting stage cost")
for j in range(i):
u_diff = u - self.u_path[j]
stage_costs += (0.5 * u_diff.T.dot(R).dot(u_diff))
# f_func = self.get_f()
# f_value = f_func(i)
# stage_costs = self.michelle_stage_cost(start, goal, x, u, i, terminal) * f_value
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("total stage cost " + str(stage_costs))
return stage_costs
def michelle_stage_cost(self, start, goal, x, u, i, terminal=False):
Q = self.Q_terminal if terminal else self.Q
R = self.R
all_goals = self.goals
goal_diff = start - goal
start_diff = (start - np.array(x))
togoal_diff = (np.array(x) - goal)
u_diff = u - self.u_path[i]
x_diff = x - self.x_path[i]
if len(self.u_path) == 0:
return 0
a = (goal_diff.T).dot(Q).dot((goal_diff))
b = (start_diff.T).dot(Q).dot((start_diff))
c = (togoal_diff.T).dot(Q).dot((togoal_diff))
# (start-goal1)'*Q*(start-goal1) - (start-x)'*Q*(start-x) + - (x-goal1)'*Q*(x-goal1)
J_g1 = a - b - c
# J_g1 *= .5
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("For point at x -> " + str(x))
# print("Jg1 " + str(J_g1))
log_sum = 0.0
total_sum = 0.0
####### NOTE: J_g1 is an artefact, so is log_sum and total_sum, PARTS is now the only element that matters
parts = []
for alt_goal in all_goals:
# n = - ((start-x)'*Q*(start-x) + 5) - ((x-goal)'*Q*(x-goal)+10)
# d = (start-goal)'*Q*(start-goal)
# log_sum += (exp(n )/exp(d))* scale
diff_curr = start - x
diff_goal = x - alt_goal
diff_all = start - alt_goal
diff_curr = diff_curr.T
diff_goal = diff_goal.T
diff_all = diff_all.T
n = - (diff_curr.T).dot(Q).dot((diff_curr)) - ((diff_goal).T.dot(Q).dot(diff_goal))
d = (diff_all).T.dot(Q).dot(diff_all)
# this_goal = np.exp(n) / np.exp(d)
this_goal = n + d
# total_sum += this_goal
if goal != alt_goal:
log_sum += (-1 * this_goal)
parts.append(-1 * this_goal)
if self.FLAG_DEBUG_STAGE_AND_TERM:
# print("Value for alt target goal " + str(alt_goal))
print("This is the nontarget goal: " + str(alt_goal) + " -> " + str(this_goal))
else:
# print("Value for our target goal " + str(goal))
# J_g1 = this_goal
log_sum += this_goal
parts.append(this_goal)
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("This is the target goal " + str(alt_goal) + " -> " + str(this_goal))
# print(n + d)
# print("log sum")
# print(log_sum)
# ratio = J_g1 / (J_g1 + np.log(log_sum))
# print("ratio " + str(ratio))
# the log on the log sum actually just cancels out the exp
# J = np.log(J_g1) - np.log(log_sum)
# alt_goal_multiplier = 5.0
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("Jg1, total")
print(J_g1, total_sum)
print(J_g1, parts)
# J = J_g1 - (np.log(total_sum))
J = J_g1 + log_sum
# J = -1.0 * J
if self.FLAG_DEBUG_STAGE_AND_TERM:
print("overall J " + str(J))
J = sum(parts)
# # We want the path to be smooth, so we incentivize small and distributed u
return J
def combine_hex_values(self, d):
d_items = sorted(d.items())
tot_weight = sum(d.values())
red = int(sum([int(k[:2], 16)*v for k, v in d_items])/tot_weight)
green = int(sum([int(k[2:4], 16)*v for k, v in d_items])/tot_weight)
blue = int(sum([int(k[4:6], 16)*v for k, v in d_items])/tot_weight)
zpad = lambda x: x if len(x)==2 else '0' + x
return zpad(hex(red)[2:]) + zpad(hex(green)[2:]) + zpad(hex(blue)[2:])
def path_following_stage_cost(self, start, goal, x, u, i, terminal=False):
Q = self.Q_terminal if terminal else self.Q
R = self.R
# Q = np.eye(2) * 1
# R = np.eye(2) * 1000
all_goals = self.goals
goal_diff = start - goal
start_diff = (start - np.array(x))
togoal_diff = (np.array(x) - goal)
if len(self.u_path) == 0:
return 0
a = np.abs(goal_diff.T).dot(Q).dot((goal_diff))
b = np.abs(start_diff.T).dot(Q).dot((start_diff))
c = (togoal_diff.T).dot(Q).dot((togoal_diff))
# (start-goal1)'*Q*(start-goal1) - (start-x)'*Q*(start-x) + - (x-goal1)'*Q*(x-goal1)
J_g1 = c
J_g1 *= .5
return J_g1
def goal_efficiency_through_point(self, start, x, goal, terminal=False):
Q = self.Q_terminal if terminal else self.Q
goal_diff = start - goal
start_diff = (start - np.array(x))
togoal_diff = (np.array(x) - goal)
a = (goal_diff.T).dot(Q).dot((goal_diff))
b = (start_diff.T).dot(Q).dot((start_diff))
c = (togoal_diff.T).dot(Q).dot((togoal_diff))
return (a + b) / c
# TODO switch this to be logs
def goal_efficiency_through_point_relative(self, start, x, goal, terminal=False):
all_goals = self.goals
this_goal = self.goal_efficiency_through_point(start, x, goal)
goals_total = 0.0
for alt_goal in all_goals:
sub_goal = self.goal_efficiency_through_point(start, x, alt_goal)
goals_total += np.exp(sub_goal)
ratio = this_goal / np.log(goals_total)
# print(ratio)
return ratio
# return np.log(this_goal) - np.log(goals_total)
# return decimal.Decimal(this_goal / goals_total)
# return np.log(this_goal) - np.log(goals_total)
# https://github.com/HIPS/autograd/blob/1bb5cbc21d2aa06e0c61654a9cc6f38c174dacc0/autograd/differential_operators.py#L93
# Discussion of hessian construction with autograd
def l_x(self, x, u, i, terminal=False):
"""Partial derivative of cost function with respect to x.
Args:
x: Current state [state_size].
u: Current control [action_size]. None if terminal.
i: Current time step.
terminal: Compute terminal cost. Default: False.
Returns:
dl/dx [state_size].
"""
if terminal:
return approx_fprime(x, lambda x: self._l_terminal(x, i),
self._x_eps)
print("Calculating L_x")
val = grad(lambda x: self._l(x, u, i))
print("(x), val")
print(x, val)
val = val(x)
# if np.nan in val:
# val = approx_fprime(x, lambda x: self._l(x, u, i), self._x_eps)
if self.FLAG_DEBUG_J:
print("J_x at " + str(x) + "," + str(u) + "," + str(i))
# print(val, val_old)
return val
def l_u(self, x, u, i, terminal=False):
"""Partial derivative of cost function with respect to u.
Args:
x: Current state [state_size].
u: Current control [action_size]. None if terminal.
i: Current time step.
terminal: Compute terminal cost. Default: False.
Returns:
dl/du [action_size].
"""
if terminal:
# Not a function of u, so the derivative is zero.
return np.zeros(self._action_size)
# val_old = approx_fprime(u, lambda u: self._l(x, u, i), self._u_eps)
# val = val_old
val = grad(lambda u: self._l(x, u, i))
val = val(u)
# if np.nan in val:
# val = approx_fprime(u, lambda u: self._l(x, u, i), self._x_eps)
if self.FLAG_DEBUG_J:
print("J_u at " + str(x) + "," + str(u) + "," + str(i))
print(val)
# print(val, val_old)
return val
# def l_xx(self, x_in, u_in, i_in, terminal=False):
# """Second partial derivative of cost function with respect to x.
# Args:
# x: Current state [state_size].
# u: Current control [action_size]. None if terminal.
# i: Current time step.
# terminal: Compute terminal cost. Default: False.
# Returns:
# d^2l/dx^2 [state_size, state_size].
# """
# eps = self._x_eps_hess
# # Q_old = np.vstack([
# # approx_fprime(x, lambda x: self.l_x(x, u, i, terminal)[m], eps)
# # for m in range(self._state_size)
# # ])
# # print("L_xx computation")
# # grad_est = jacobian(self.l_x)
# # print("grad est")
# # Q = grad_est[x_in, u_in, i_in]
# Q = hessian(self.l)(x_in, u_in, i_in)
# # grad_est = grad_est(x_in)
# # Q = np.vstack([
# # grad_est[0],
# # grad_est[1],
# # grad_est[2],
# # grad_est[3]
# # ])
# # # for m in range(self._state_size)
# # Q = Q_old
# if self.FLAG_DEBUG_J:
# print("J_xx at " + str(x) + "," + str(u) + "," + str(i))
# print(Q)
# # print(Q, Q_old)
# return Q
# def l_ux(self, x_in, u_in, i_in, terminal=False):
# """Second partial derivative of cost function with respect to u and x.
# Args:
# x: Current state [state_size].
# u: Current control [action_size]. None if terminal.
# i: Current time step.
# terminal: Compute terminal cost. Default: False.
# Returns:
# d^2l/dudx [action_size, state_size].
# """
# if terminal:
# # Not a function of u, so the derivative is zero.
# return np.zeros((self._action_size, self._state_size))
# eps = self._x_eps_hess
# # Q_old = np.vstack([
# # approx_fprime(x, lambda x: self.l_u(x, u, i)[m], eps)
# # for m in range(self._action_size)
# # ])
# # Q = np.vstack([
# # grad(lambda x: self._l_u(x, u, i, terminal)[m])
# # # approx_fprime(x, lambda x: self.l_x(x, u, i, terminal)[m], eps)
# # for m in range(self._state_size)
# # ])
# # Q = Q_old
# grad_est = elementwise_grad(lambda x: self.l_u(x, u_in, i_in, terminal))(x_in)
# Q = np.vstack([
# grad_est[0],
# grad_est[1],
# grad_est[2],
# grad_est[3]
# ])
# if self.FLAG_DEBUG_J:
# print("J_ux at " + str(x) + "," + str(u) + "," + str(i))
# print(Q)
# # print(Q, Q_old)
# return Q
# def l_uu(self, x_in, u_in, i_in, terminal=False):
# """Second partial derivative of cost function with respect to u.
# Args:
# x: Current state [state_size].
# u: Current control [action_size]. None if terminal.
# i: Current time step.
# terminal: Compute terminal cost. Default: False.
# Returns:
# d^2l/du^2 [action_size, action_size].
# """
# if terminal:
# # Not a function of u, so the derivative is zero.
# return np.zeros((self._action_size, self._action_size))
# eps = self._u_eps_hess
# # Q_old = np.vstack([
# # approx_fprime(u, lambda u: self.l_u(x, u, i)[m], eps)
# # for m in range(self._action_size)
# # ])
# # Q = np.vstack([
# # grad(lambda u: self._l_u(x, u, i, terminal)[m])
# # # approx_fprime(x, lambda x: self.l_x(x, u, i, terminal)[m], eps)
# # for m in range(self._state_size)
# # ])
# grad_est = elementwise_grad(lambda u: self.l_u(x_in, u, i_in, terminal))(u_in)
# Q = np.vstack([
# grad_est[0],
# grad_est[1],
# grad_est[2],
# grad_est[3]
# ])
# # Q = Q_old
# if self.FLAG_DEBUG_J:
# print("J_uu at " + str(x) + "," + str(u) + "," + str(i))
# print(Q)
# # print(Q, Q_old)
# return Q
def hex_to_rgb(self, value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def rgb_to_hex(self, rgb):
value = '%02x%02x%02x' % rgb
value = '#' + str(value)
return value
def mean_color(self, color1, color2):
rgb1 = self.hex_to_rgb(color1)
rgb2 = self.hex_to_rgb(color2)
avg = lambda x, y: round((x+y))
new_rgb = ()
for i in range(len(rgb1)):
new_rgb += (avg(rgb1[i], rgb2[i]),)
return self.rgb_to_hex(new_rgb)
def get_window_dimensions_for_envir(self, start, goals, pts, observers=None):
xmin, ymin = start
xmax, ymax = start
all_points = copy.copy(goals)
all_points.append(start)
all_points.extend(pts)
if observers != None:
for obs in observers:
all_points.append(obs.get_center())
for pt in all_points:
x, y = pt[0], pt[1]
if x < xmin:
xmin = x
if y < ymin:
ymin = y
if x > xmax:
xmax = x
if y > ymax:
ymax = y
xwidth = xmax - xmin
yheight = ymax - ymin
xbuffer = .1 * xwidth
ybuffer = .1 * yheight
# The closer to 1 it is, the closer they are to equal
ratio = np.abs(xmin - xmax) / np.abs(ymin - ymax)
# x much more than y
if ratio > 4:
stretch = np.abs(ymin - ymax) / np.abs(xmin - xmax)
add_buff = np.abs(xmin - xmax) - np.abs(ymin - ymax)
add_buff = add_buff / 2.0
ymin = ymin - add_buff
ymax = ymax + add_buff
# # y much more than x
# elif radio < (1/4.0):
if xbuffer < .3:
xbuffer = .5
if ybuffer < .3:
ybuffer = .5
return xmin - xbuffer, xmax + xbuffer, ymin - ybuffer, ymax + ybuffer
def get_export_label(self, dash_folder=None):
note = self.exp.get_fn_note()
if dash_folder is not None:
folder_name = dash_folder + "/" + self.file_id + note + "/"
else:
folder_name = PREFIX_EXPORT + self.file_id + note + "/"
overall_name = folder_name + self.file_id + self.exp.get_fn_notes_ada()
try:
os.mkdir(Path(folder_name))
except:
print("FILE ALREADY EXISTS " + self.file_id)
return overall_name
def get_prob_of_path_to_goal(self, verts, us, goal, label):
prob_list = []
start = self.start
u = None
terminal = False
if len(verts) != self.N + 1:
print("points in path does not match the solve N")
resto_envir = self.restaurant
goals = self.goals
for i in range(len(verts)):
# print(str(i) + " out of " + str(len(verts)))
x_input = verts[i]
x = x_input[:2]
if len(x_input) == 4:
x_prev = x_input[2:]
print(x)
print(x_prev)
if i < len(us):
u = us[i - 1]
else:
u = [0, 0]
aud = resto_envir.get_observers()
bin_visibility = legib.get_visibility_of_pt_w_observers_ilqr(x, aud, normalized=True)
if bin_visibility > 0:
bin_visibility = 1.0
if label == 'dist_exp':
p = self.prob_distance(start, goal, x, u, i, terminal, bin_visibility, override={'mode_heading':None, 'mode_dist':'exp', 'mode_blend':None})
elif label == 'dist_exp_nn':
p = self.cost_nextbest_distance(start, goal, x, u, i, terminal, True, override={'mode_heading':None, 'mode_dist':'exp', 'mode_blend':None}, num=2)
elif label == 'dist_sqr':
p = self.prob_distance(start, goal, x, u, i, terminal, bin_visibility, override={'mode_heading':None, 'mode_dist':'sqr', 'mode_blend':None})
elif label == 'dist_lin':
p = self.prob_distance(start, goal, x, u, i, terminal, bin_visibility, override={'mode_heading':None, 'mode_dist':'lin', 'mode_blend':None})
elif label == 'head_sqr':
if len(x_input) == 4:
p = self.prob_heading_from_pt_seq(x, x_prev, i, goal, bin_visibility, override={'mode_heading':'sqr', 'mode_dist':None, 'mode_blend':None})
else:
p = self.prob_heading(x, u, i, goal, bin_visibility, override={'mode_heading':'sqr', 'mode_dist':None, 'mode_blend':None})
elif label == 'head_lin':
if len(x_input) == 4:
p = self.prob_heading_from_pt_seq(x, x_prev, i, goal, bin_visibility, override={'mode_heading':'lin', 'mode_dist':None, 'mode_blend':None})
else:
p = self.prob_heading(x, u, i, goal, bin_visibility, override={'mode_heading':'lin', 'mode_dist':None, 'mode_blend':None})
else:
print(label)
prob_list.append(p)
return prob_list
def get_legibility_of_path_to_goal(self, verts, us, goal):
ls, scs, tcs, vs = [], [], [], []
start = self.start
u = None
terminal = False
if len(verts) != self.N + 1:
print("points in path does not match the solve N")
resto_envir = self.restaurant
goals = self.goals
l_components = {}
l_components['total_legib'] = []
l_components['total_lam'] = []
l_components['total_heading'] = []
l_components['total_obstacle'] = []
for i in range(len(verts)):
# print(str(i) + " out of " + str(len(verts)))
x = verts[i]
aud = resto_envir.get_observers()
l = legib.f_legibility_ilqr(resto_envir, goal, goals, verts[:i], aud)
if i < len(us):
j = i
# j = us[i] #len(us) - 1
u = us[j]
sc = self.l(x, u, j, just_stage=True) #self.get_total_stage_cost(start, goal, x, u, j, terminal)
tc = self.l(x, u, j, just_term=True)
scs.append(sc)
l_legib = self.l(x, u, j, just_stage=True, test_component='legib')
l_lam = self.l(x, u, j, just_stage=True, test_component='lam')
l_head = self.l(x, u, j, just_stage=True, test_component='head')
l_obs = self.l(x, u, j, just_stage=True, test_component='obs')
l_components['total_legib'].append(l_legib)
l_components['total_lam'].append(l_lam)
l_components['total_heading'].append(l_head)
l_components['total_obstacle'].append(l_obs)
tcs.append(tc)
# tc = float(self.term_cost(x, i))
ls.append(l)
x = verts[-1]
N = self.exp.get_N()
last_term = self.l(x, None, N, terminal=True)
# TODO: alter this if we want to show vis from multiple observers
for obs in self.exp.get_restaurant().get_observers():
vis_log = []
for i in range(len(verts)):
x = verts[i]
v = legib.get_visibility_of_pt_w_observers_ilqr(x, [obs], normalized=True)
vis_log.append(v)
vs.append(vis_log)
print("~~~~~FINAL COLLATE")
total_legib = l_components['total_legib']
total_lam = l_components['total_lam']
total_heading = l_components['total_heading']
total_obstacle = l_components['total_obstacle']
print("TOTAL LEGIB")
print(sum(total_legib))
print("TOTAL LAM")
print(sum(total_lam))
print("TOTAL HEADING")
print(sum(total_heading))
print("TOTAL OBSTACLE")
print(sum(total_obstacle))
print("LAST TERM COST")
print(last_term)
return ls, scs, tcs, vs
def get_debug_text(self, elapsed_time):
debug_text_a = "stage scale: " + str(self.exp.get_solver_scale_stage()) + " "
debug_text_b = "term scale: " + str(self.exp.get_solver_scale_term()) + " "
debug_text_c = "\n "
debug_text_d = "obstacle scale: " + str(self.exp.get_solver_scale_obstacle()) + " " # + "\n"
debug_text_e = "dt: " + str(self.exp.get_dt()) + " "
debug_text_f = "N: " + str(self.exp.get_N()) # + "\n"