-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocLegPathQRCost.py
2470 lines (1863 loc) · 81.2 KB
/
SocLegPathQRCost.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
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 autograd.numpy as np
import matplotlib.pyplot as plt
import decimal
import copy
import math
import torch
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
from sklearn import preprocessing
import utility_legibility as legib
import utility_environ_descrip as resto
import pipeline_generate_paths as pipeline
import pdb
from LegiblePathQRCost import LegiblePathQRCost
import PathingExperiment as ex
from shapely.geometry import LineString
from shapely.geometry import Point
np.set_printoptions(suppress=True)
np.seterr(divide='raise')
MATH_EPSILON = 0 #.0000001
class SocLegPathQRCost(LegiblePathQRCost):
FLAG_DEBUG_J = False
FLAG_DEBUG_STAGE_AND_TERM = True
FLAG_COST_PATH_OVERALL = True
FLAG_OBS_FLAT_PENALTY = True
best_xs = None
best_us = None
"""Quadratic Regulator Instantaneous Cost for trajectory following."""
def __init__(self, exp, x_path, u_path):
self.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 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].
"""
LegiblePathQRCost.__init__(
self, exp, x_path, u_path
)
##### METHODS FOR ANGLE MATH - Should match SocLegPathQRCost
def get_heading_moving_between(self, p2, p1):
print("Get heading moving from " + str(p1) + " to " + str(p2))
print(p2)
print(p1)
# https://stackoverflow.com/questions/31735499/calculate-angle-clockwise-between-two-points
ang1 = np.arctan2(*p1[::-1])
ang2 = np.arctan2(*p2[::-1])
heading = np.rad2deg((ang1 - ang2) % (2 * np.pi))
print(heading)
# heading = self.get_minimum_rotation_to(heading)
# Heading is in degrees
return heading
def across_obstacle(self, x0, x1):
TABLE_RADIUS = self.exp.get_table_radius()
OBS_RADIUS = .1
GOAL_RADIUS = .15 #.05
tables = self.exp.get_tables()
goals = self.exp.get_goals()
observers = self.exp.get_observers()
l = LineString([x0, x1])
for t in tables:
ct = t.get_center()
p = Point(ct[0],ct[1])
c = p.buffer(TABLE_RADIUS).boundary
i = c.intersection(l)
if i is True:
print("TELEPORTED ACROSS: table " + str(ct))
return True
for o in observers:
ct = o.get_center()
p = Point(ct[0],ct[1])
c = p.buffer(OBS_RADIUS).boundary
i = c.intersection(l)
if i is True:
print("TELEPORTED ACROSS: o " + str(ct))
return True
for g in goals:
ct = g
p = Point(ct[0],ct[1])
c = p.buffer(GOAL_RADIUS).boundary
i = c.intersection(l)
if i is True:
print("TELEPORTED ACROSS: goal " + str(ct))
return True
return False
def get_closest_point_on_line(self, x, i, obst_center):
x1 = x
if i > 0:
x0 = self.x_path[i - 1]
else:
x0 = x
vec_line = x1 - x0
# the vector from the obstacle to the first line point
vec_ob_line = obst_center - x0
# calculate the projection normalized by length of arm segment
projection = (np.dot(vec_ob_line, vec_line) /
np.sum((vec_line)**2))
if projection < 0:
# then closest point is the start of the segment
closest = x0
elif projection > 1:
# then closest point is the end of the segment
closest = x1
else:
closest = x0 + projection * vec_line
print("ptclosest")
print(closest)
# calculate distance from obstacle vertex to the closest point
dist = np.abs(np.linalg.norm(obst_center - closest)) #np.sqrt(np.sum((obst_center - closest)**2))
print("Closest point dist")
print(dist)
return dist
# https://studywolf.wordpress.com/2016/11/24/full-body-obstacle-collision-avoidance/
def get_obstacle_penalty_given_obj(self, x_triplet, i, obst_center, obstacle_radius):
obstacle_radius = obstacle_radius # the physical obj size
obstacle_buffer = self.exp.get_obstacle_buffer() # the area in which the force will apply
rho_o = obstacle_radius + obstacle_buffer
x = x_triplet[:2]
# obst_dist is the distance between the point and the center of the obj
obst_dist = obst_center - x
obst_dist = np.abs(np.linalg.norm(obst_dist))
# obst_dist = self.get_closest_point_on_line(x, i, obst_center)
# rho is the distance between the object's edge and the pt
rho = obst_dist - obstacle_buffer #rho_o
# if rho is negative, we are inside the sphere
eta = 1.0
v = obst_center
closest = x
threshold = obstacle_radius + obstacle_buffer
# print("Are we in it?")
# print("dist, threshold, rho")
# print(obst_dist, threshold, rho)
Fpsp = 0
if rho < obstacle_radius:
# rho = rho
# vector component
# drhodx = (v - closest) / rho
d_rho_top = obst_center - x
d_rho_dx = d_rho_top / rho
# print("Rho says yes")
eta = 1.0
drhodx = (v - closest) / rho
Fpsp = (eta * (1.0/rho - 1.0/threshold) *
1.0/rho**2 * d_rho_dx)
# print("Fpsp")
# print(Fpsp)
# print(1.0/rho)
# print(1.0/threshold)
# print(1.0 / rho**2)
# print(drhodx)
# print("~~~~~")
else:
# print("rho says no")
pass
Fpsp = np.linalg.norm(Fpsp)
# print("obspenalty is: ")
# print(Fpsp)
if Fpsp < 0:
print("ALERT: REWARD FOR ENTERING OBSTACLE!")
if obst_dist < obstacle_radius:
print("Inside the actual obj")
print(x, obst_center)
print("Distance")
print(obst_dist, self.dist_between(obst_center, x))
if Fpsp == 0:
print("ALERT: no penalty")
elif obst_dist < obstacle_buffer + obstacle_radius:
print("Inside the overall force diagram")
print(x, obst_center)
print("Distance")
print(obst_dist, self.dist_between(obst_center, x))
if Fpsp == 0:
print("ALERT: no penalty")
else:
print("Not in an obstacle")
if Fpsp > 0:
print("ALERT: obstacle penalty when not in object")
if Fpsp > 0:
print("Penalty: " + str(Fpsp))
return 0.0
return Fpsp
# Citation for future paper
# https://studywolf.wordpress.com/2016/11/24/full-body-obstacle-collision-avoidance/
def get_obstacle_penalty(self, x, i, goal):
TABLE_RADIUS = self.exp.get_table_radius()
OBS_RADIUS = self.exp.get_observer_radius() #.2
GOAL_RADIUS = self.exp.get_goal_radius() #.3 #.05
tables = self.exp.get_tables()
goals = self.goals
observers = self.exp.get_observers()
obstacle_penalty = 0
for table in tables:
obstacle_penalty += self.get_obstacle_penalty_given_obj(x, i, table.get_center(), TABLE_RADIUS)
for obs in observers:
obstacle = obs.get_center()
obstacle_penalty += self.get_obstacle_penalty_given_obj(x, i, obs.get_center(), OBS_RADIUS)
for g in goals:
if not np.array_equal(g, goal):
obstacle = g
obstacle_penalty += self.get_obstacle_penalty_given_obj(x, i, g, GOAL_RADIUS)
# x1 = x
# if i > 0:
# x0 = self.x_path[i - 1]
# else:
# x0 = x
# if self.across_obstacle(x0, x1):
# obstacle_penalty += 1.0
# print("TELEPORT PENALTY APPLIED")
return obstacle_penalty
# TODO ADD TEST SUITE FOR THIS
def get_obstacle_penalty_v1(self, x, i, goal):
TABLE_RADIUS = self.exp.get_table_radius()
OBS_RADIUS = .2
GOAL_RADIUS = .3 #.05
tables = self.exp.get_tables()
goals = self.goals
observers = self.exp.get_observers()
x1 = x
if i > 0:
x0 = self.x_path[i - 1]
else:
x0 = x
obstacle_penalty = 0
for table in tables:
obstacle = table.get_center()
obs_dist = obstacle - x
obs_dist = np.abs(np.linalg.norm(obs_dist))
# Flip so edges lower cost than center
if obs_dist < TABLE_RADIUS:
obs_dist = TABLE_RADIUS - obs_dist
print("PENALTY: table obstacle dist for " + str(x) + " " + str(obs_dist))
print(str(table.get_center()))
# obstacle_penalty += (obs_dist)**2 * self.scale_obstacle
# OBSTACLE PENALTY NOW ALWAYS SCALED TO RANGE 0 -> 1
if self.FLAG_OBS_FLAT_PENALTY:
obstacle_penalty += 1.0
obstacle_penalty += np.abs(obs_dist / TABLE_RADIUS)
# np.inf #
for obs in observers:
obstacle = obs.get_center()
obs_dist = obstacle - x
obs_dist = np.abs(np.linalg.norm(obs_dist))
# Flip so edges lower cost than center
if obs_dist < OBS_RADIUS:
obs_dist = OBS_RADIUS - obs_dist
print("PENALTY: obs obstacle dist for " + str(x) + " " + str(obs_dist))
print(str(obs.get_center()))
# obstacle_penalty += (obs_dist)**2 * self.scale_obstacle
# OBSTACLE PENALTY NOW ALWAYS SCALED TO RANGE 0 -> 1
if self.FLAG_OBS_FLAT_PENALTY:
obstacle_penalty += 1.0
obstacle_penalty += np.abs(obs_dist / OBS_RADIUS) #**2
for g in goals:
if not np.array_equal(g, self.exp.get_target_goal()):
obstacle = g
obs_dist = obstacle - x
obs_dist = np.abs(np.linalg.norm(obs_dist))
# Flip so edges lower cost than center
if obs_dist < GOAL_RADIUS:
obs_dist = GOAL_RADIUS - obs_dist
print("PENALTY: goal obstacle dist for " + str(x) + " " + str(obs_dist))
print(str(g))
# obstacle_penalty += (obs_dist)**2 * self.scale_obstacle
# OBSTACLE PENALTY NOW ALWAYS SCALED TO RANGE 0 -> 1
if self.FLAG_OBS_FLAT_PENALTY:
obstacle_penalty += 1.0
obstacle_penalty += np.abs(obs_dist / GOAL_RADIUS) #**2
# else:
# print("inside final goal " + str(g))
if self.across_obstacle(x0, x1):
obstacle_penalty += 1.0
print("TELEPORT PENALTY APPLIED")
obstacle_penalty = obstacle_penalty * np.Inf
return obstacle_penalty
def get_angle_between_pts(self, p2, p1):
# https://stackoverflow.com/questions/31735499/calculate-angle-clockwise-between-two-points
ang1 = np.arctan2(*p1[::-1])
ang2 = np.arctan2(*p2[::-1])
heading = np.rad2deg((ang1 - ang2) % (2 * np.pi))
# Heading is in degrees
return heading
##### METHODS FOR ANGLE MATH
def get_angle_between(self, p2, p1):
# https://stackoverflow.com/questions/31735499/calculate-angle-clockwise-between-two-points
ang1 = np.arctan2(*p1[::-1])
ang2 = np.arctan2(*p2[::-1])
heading = np.rad2deg((ang1 - ang2) % (2 * np.pi))
heading = self.get_minimum_rotation_to(heading)
# Heading is in degrees
return heading
def get_min_rotate_angle_diff(self, x, y):
if np.abs(x - y) > 180:
return (360) - abs(x - y)
a = min((360) - abs(x - y), abs(x - y))
return abs(x - y)
def get_heading_look_from_x0_to_x1(self, x0, x1):
unit_vec = [x0[0] + 1.0, x0[1]]
heading = self.get_angle_between_triplet(x1, x0, unit_vec)
heading = heading % 360
print("Look from " + str(x0) + " to " + str(x1) + " == " + str(heading))
return heading
# ADA TODO
def angle_x1_x0(self, x_cur, x_prev):
x_cur_x, x_cur_y = x_cur
x_prev_x, x_prev_y = x_prev
# atan2 = -180 to 180, in radians
heading = np.arctan2(x_cur_y-x_prev_y, x_cur_x-x_prev_x)
heading = heading * (180.0/np.pi)
heading = (heading + 360) % 360
# This angle is counter clockwise from 0 at EAST
# 90 = NORTH
# 270 = SOUTH
return heading
def get_angle_to_look_at_point(self, robot_x1, robot_x0, look_at_pt):
# robot_x1 = robot_x[:2]
# robot_x0 = robot_x[2:]
prev_angle = self.angle_x1_x0(robot_x1, robot_x0)
prev_angle_rev = self.angle_x1_x0(robot_x0, robot_x1)
# prev_angle = self.get_heading_look_from_x0_to_x1(robot_x1, robot_x0)
goal_angle = self.angle_x1_x0(look_at_pt, robot_x1)
# target_shifted = look_at_pt - robot_x1
# angle = math.atan2(target_shifted[1], target_shifted[0])
# angle = angle * (180.0/np.pi)
# angle = (angle + 360) % 360
# # atan2 gives -180 to 180
# if angle < 0:
# angle = 360 - angle
print("Robot looking at " + str(prev_angle))
print("Opp: " + str(prev_angle_rev))
print("Angle to goal is " + str(goal_angle))
offset = np.abs(prev_angle - goal_angle)
print("OG offset " + str(offset))
if offset > 180:
offset = 360 - offset
print("final offset " + str(offset))
return offset
def inversely_proportional_to_distance(self, x):
if x == 0:
return np.Inf
return 1.0 / (x)
def get_relative_distance_k(self, x, goal=None, goals=None):
total_distance = 0.0
if goals is None:
goals = self.goals
if goal is None:
goal = self.target_goal
for g in goals:
dist = g - x
dist = np.abs(np.linalg.norm(dist))
total_distance += self.inversely_proportional_to_distance(dist)
target_goal_dist = np.abs(np.linalg.norm(goal - x))
tg_dist = self.inversely_proportional_to_distance(target_goal_dist)
# rel_dist = 1.0 - (tg_dist / total_distance)
rel_dist = (total_distance - tg_dist) / total_distance
return rel_dist
def get_relative_distance_k_sqr(self, x, goal=None, goals=None):
total_distance = 0.0
if goals is None:
goals = self.goals
if goal is None:
goal = self.target_goal
for g in goals:
dist = g - x
dist = np.abs(np.linalg.norm(dist))
total_distance += (self.inversely_proportional_to_distance(dist) ** 2)
target_goal_dist = np.abs(np.linalg.norm(goal - x))
tg_dist = self.inversely_proportional_to_distance(target_goal_dist)**2
# rel_dist = 1.0 - (tg_dist / total_distance)
rel_dist = (total_distance - tg_dist) / total_distance
return rel_dist
def get_minimum_rotation_to(self, angle):
if angle < 0:
angle = abs(angle)
if angle < 180:
return angle
else:
angle = 360 - angle
return angle
def get_relative_distance_k_v1(self, x, goal, goals):
max_distance = 0.0
for g in goals:
dist = g - x
dist = np.abs(np.linalg.norm(dist))
if dist > max_distance:
max_distance = dist
target_goal_dist = goal - x
tg_dist = np.abs(np.linalg.norm(target_goal_dist))
return 1 - (tg_dist / max_distance)
def unit_vector(self, vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def angle_between(self, v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = self.unit_vector(v1)
v2_u = self.unit_vector(v2)
print("unit vecs")
print(v1_u)
print(v2_u)
ang = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return ang
def inversely_proportional_to_angle(self, angle):
if angle == 0:
print("There's an infinity involved here")
return np.Inf
return 1.0 / (angle)
# def get_heading_stage_cost_debug(self, x, u, i, goal, visibility_coeff, force_mode=None, x_prev=None, pure_prob=False):
# all_goals = self.goals
# # If on first timestep and no angle yet, even prior on all
# if i is 0:
# return (1.0 / len(self.goals))
# x1 = x
# x0 = x - u
# robot_vector = x1 - x0
# target_vector = None
# all_goal_vectors = []
# for alt_goal in all_goals:
# goal_vector = alt_goal - x1
# if np.array_equal(alt_goal, goal):
# target_vector = goal_vector
# else:
# pass
# # print("no, mismatch of " + str(alt_goal) + " != " + str(goal))
# all_goal_vectors.append(goal_vector)
# all_goal_angles = []
# for gvec in all_goal_vectors:
# goal_angle = self.get_angle_between(robot_vector, gvec)
# all_goal_angles.append(goal_angle)
# target_angle = self.get_angle_between(robot_vector, target_vector)
# g_vals = []
# g_vals_if_infinity = []
# for j in range(len(all_goal_angles)):
# gval = self.inversely_proportional_to_angle(all_goal_angles[j])
# if self.exp.get_mode_type_heading() is 'sqr':
# gval = gval * gval
# # if self.exp.get_weighted_close_on() is True:
# # k = self.get_relative_distance_k(x1, goals[i], goals)
# # else:
# # k = 1.0
# # by default, evenly weight all goals
# k = 1.0
# g_vals.append(k * gval)
# g_vals_if_infinity.append((k, gval == np.Inf))
# target_val = self.inversely_proportional_to_angle(target_angle)
# return {'robot_vec': robot_vector, 'x0': x0, 'x1':x1, 'target_angle': target_angle, 'target_val': target_val, 'all_angles':all_goal_angles}
def get_angle_between_triplet(self, a_in, b_in, c_in):
# print(type(a), type(b), type(c))
a = copy.copy(a_in)
b = copy.copy(b_in)
c = copy.copy(c_in)
# Reminder atan2 does y then x, versus x y
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
ang = ang + 360 if ang < 0 else ang
# Alternate implementation for comparison
a = np.asarray(a)
b = np.asarray(b)
c = np.asarray(c)
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle = np.arccos(cosine_angle)
alt_check = np.degrees(angle)
if ang > 180:
ang = 360.0 - ang
print("\tsoc math check")
print("\t", a, b, c, str(ang) + " degrees", alt_check)
if np.abs(ang - alt_check) > 1.0:
print("ALERT: HEADING ANGLE MATH MAY BE INCONSISTENT")
return ang
def get_heading_of_pt_diff_p2_p1(self, p2, p1):
unit_vec = [p1[0] + 1.0, p1[1]]
heading = self.get_angle_between_triplet(p2, p1, unit_vec)
return heading
def get_legibility_heading_stage_cost_3d(self, x, u, i, goal, visibility_coeff, override=None):
# if len(x) > 2 and x[2] is None:
# return 1.0
P_oa = self.prob_heading(x, u, i, goal, visibility_coeff, override=override)
# cost = ((np.exp(1.0)) - (np.exp(P_oa)))
cost = ((1.0) - (P_oa))
return cost
def get_legibility_heading_stage_cost_from_pt_seq(self, x_cur, x_prev, i, goal, visibility_coeff, u=None, override=None):
# start = self.exp.get_start()
# k = self.exp.get_dist_scalar_k()
# print("mergh")
# print(k)
# print(np.abs((x_cur[0] - x_prev[0])), np.abs((x_cur[1] - x_prev[1])))
# # If the heading is not going anywhere, put max penalty
# if np.abs((x_cur[0] - x_prev[0])) < k and np.abs((x_cur[1] - x_prev[1])) < k:
# return 2.0
# print(np.abs((x_cur[0] - goal[0])), np.abs((x_cur[1] - goal[1])))
# # if we are on the goal, return max penalty
# if np.abs((x_cur[0] - goal[0])) < k and np.abs((x_cur[1] - goal[1])) < k:
# return 2.0
# Protection against the weird case of both ydiff and xdiff = 0
# which would be a discontinuity
# https://github.com/google/jax/discussions/15865
if np.array_equal(x_cur, x_prev):
return 2.0
# How do we handle getting to the goal early?
if np.array_equal(x_cur, goal):
return 2.0
P_oa = self.prob_heading_from_pt_seq(x_cur, x_prev, i, goal, visibility_coeff, u=u, override=override)
if (P_oa) < 0:
print("ALERT: P_oa too small")
elif (P_oa) > 1.0:
print("ALERT: P_oa too large")
# k = 5.0
# scalar = np.abs((P_oa) - 0.5) * k
cost = (1.0) - (P_oa)
cost = (P_oa)
# return (scalar) * ((cost))
return ((cost)) #+ (10.0)
def prob_heading_from_pt_seq(self, x_cur_in, x_prev_in, i_in, goal_in, visibility_coeff, u=None, override=None):
x_cur = x_cur_in
x_prev = x_prev_in
if len(x_cur) == 4:
x_cur = x_cur[2:]
if len(x_prev) == 4:
x_prev = x_prev[2:]
# 4.117876 -0.2 -6.848375
# g_away = np.asarray([7.41, -6.99]) # G_AWAY 0 angle
# g_me = np.asarray([3.79, -6.99]) # G_ME 180 angle
if np.array_equal(goal_in, [3.79, -6.99]) and self.dist_between(x_cur_in, goal_in) < .36:
return 1.0
# if np.array_equal(goal_in, [7.41, -6.99]) and goal_in dist_between(x_cur_in, goal_in) < .36:
# return 1.0
# if not np.array_equal(x_cur_in, x_prev):
# x_theta = self.get_heading_of_pt_diff_p2_p1(x_cur[:2], x_prev[:2])
# else:
# x_theta = None
# return (1.0 / len(self.goals))
# print("PRECALC heading angle")
# print(x_cur, x_prev, x_theta)
# x_triplet = [x_cur[0], x_cur[1], x_theta]
u_output = u
# heading_P_oa = self.prob_heading_3d(x_triplet, u_output, i_in, goal_in, visibility_coeff, override=override)
# Version that uses pt differences
heading_P_oa_4d = self.prob_heading_from_pt_seq_alt_4d(x_cur, x_prev, u_output, i_in, goal_in, visibility_coeff, override=override)
print("HEADCOMP: " + str(heading_P_oa_4d))
# print("HEADCOMP: " + str(heading_P_oa) + " vs " + str(heading_P_oa_4d))
# If you did nothing and stood in the same spot,
# then min probability, maximum penalty
return heading_P_oa_4d
# This function only takes size 3 vectors
def prob_heading_from_pt_seq_alt_4d(self, x_cur, x_prev, u_in, i_in, goal_in, visibility_coeff, override=None):
all_goals = self.goals
goal = goal_in[:2]
mode_dist = self.exp.get_mode_type_dist()
mode_heading = self.exp.get_mode_type_heading()
mode_blend = self.exp.get_mode_type_blend()
if override != None:
if 'mode_heading' in override.keys():
mode_heading = override['mode_heading']
print("OO: override to do heading mode")
if u_in is not None:
u = copy.copy(u_in)
else:
u = None
i = copy.copy(i_in)
if override is not None:
if 'mode_heading' in override:
mode_dist = override['mode_heading']
if not np.array_equal(goal[:2], self.exp.get_target_goal()[:2]):
print("WARNING: Goal and exp goal not the same in prob heading")
print(goal[:2], self.exp.get_target_goal()[:2])
# exit()
x_total = np.concatenate((x_cur, x_prev))
debug_dict = {'x': x_total, 'u': u, 'i':i, 'goal': goal, 'start': self.exp.get_start(), 'all_goals':self.exp.get_goals(), 'visibility_coeff': visibility_coeff, 'N': self.exp.get_N(), 'override': override, 'mode_heading': mode_heading}
print("HEADING EFFORT COST INPUTS")
print(debug_dict)
target_vector = None
all_goal_headings = []
target_index = -1
x = x_cur[:2]
x_prev = x_prev
all_effort_measures = []
for j in range(len(self.goals)):
# print("Goal angle diff for " + str(robot_theta) + " -> " + str(ghead))
# goal_angle_diff = self.get_min_rotate_angle_diff(robot_theta, ghead)
# print("goal angle diff " + str(goal_angle_diff))
# effort_made = (180.0 - goal_angle_diff)
# print("effort made " + str(effort_made))
alt_goal = all_goals[j]
# goal_vector = alt_goal - x_current
# all_goal_vectors.append(goal_vector)
if np.array_equal(alt_goal[:2], goal[:2]):
print("Yes, is target")
target_index = j
# effort_made = self.get_angle_between_triplet(x_prev, x, alt_goal)
angle_to_look = self.get_angle_to_look_at_point(x_cur, x_prev, alt_goal)
effort_made = (180.0 - angle_to_look)
if angle_to_look < 0:
print(goal_angle_diff)
print("eeek negative angle diff")
print("Angle to look at goal " + str(alt_goal) + " is " + str(angle_to_look))
print("Effort is " + str(effort_made))
# if (effort_made) > 180 or (effort_made) < 0:
# print("ALERT: Get angle between needs some work")
# # exit()
if mode_heading == 'sqr':
effort_made = effort_made**2
elif mode_heading == 'exp':
effort_made = np.exp(effort_made)
all_effort_measures.append(effort_made)
print("All effort measures")
print(all_effort_measures)
target_val = all_effort_measures[target_index]
total = sum(all_effort_measures)
num_goals = len(all_goals)
try:
all_probs = [x/total for x in all_effort_measures]
print(all_probs)
P_heading = ((target_val) / total)
except (ValueError, decimal.InvalidOperation, ZeroDivisionError):
print("Alert: Heading has divide by 0")
P_heading = (1.0 / num_goals)
P_heading = 0.0
P_oa = ((1.0/num_goals)*(1.0 - visibility_coeff)) + (((visibility_coeff) * P_heading))
return P_oa
# This function only takes size 3 vectors
def prob_heading_3d(self, x_triplet, u_in, i_in, goal_in, visibility_coeff, override=None):
all_goals = self.goals
goal = goal_in[:2]
mode_dist = self.exp.get_mode_type_dist()
mode_heading = self.exp.get_mode_type_heading()
mode_blend = self.exp.get_mode_type_blend()
if override != None:
if 'mode_heading' in override.keys():
mode_heading = override['mode_heading']
print("OO: override to do heading mode")
if u_in is not None:
u = copy.copy(u_in)
else:
u = None
i = copy.copy(i_in)
if override is not None:
if 'mode_heading' in override:
mode_dist = override['mode_heading']
x_current = x_triplet[:2]
debug_dict = {'x': x_triplet, 'u': u, 'i':i, 'goal': goal, 'start': self.exp.get_start(), 'all_goals':self.exp.get_goals(), 'visibility_coeff': visibility_coeff, 'N': self.exp.get_N(), 'override': override, 'mode_heading': mode_heading}
print("HEADING COST INPUTS")
print(debug_dict)
if x_triplet[2] == None:
print("Robot theta not yet set in theta solve mode, is that a problem?")
return (0.0)
else:
robot_theta = x_triplet[2]
if not np.array_equal(goal[:2], self.exp.get_target_goal()[:2]):
print("Goal and exp goal not the same in prob heading")
print(goal, self.exp.get_target_goal())
# exit()
# # if we are at the goal, we by definition are arriving correctly
# if self.dist_between(x_current, goal) < 1.1:
# P_heading = (1.0)
# num_goals = len(all_goals)
# P_oa = ((1.0/num_goals)*(1.0 - visibility_coeff)) + (((visibility_coeff) * P_heading))
# return P_oa
target_vector = None
all_goal_headings = []
target_index = -1
for j in range(len(all_goals)):
alt_goal = all_goals[j]
# goal_vector = alt_goal - x_current
# all_goal_vectors.append(goal_vector)
if np.array_equal(alt_goal[:2], goal[:2]):
print("Yes, is target")
target_index = j
else:
print("no, mismatch of " + str(alt_goal) + " != " + str(goal))
goal_heading = self.get_heading_of_pt_diff_p2_p1(alt_goal, x_current)
all_goal_headings.append(goal_heading)
print("All goal headings")
print(all_goal_headings)
all_effort_measures = []
all_offset_angles = []
for ghead in all_goal_headings:
print("Goal angle diff for " + str(robot_theta) + " -> " + str(ghead))
goal_angle_diff = self.get_min_rotate_angle_diff(robot_theta, ghead)
print("goal angle diff " + str(goal_angle_diff))
effort_made = (180.0 - goal_angle_diff)
print("effort made " + str(effort_made))
# effort_two = self.get_angle_between_triplet(a, b, c)
# if (effort_made) > 180 or (effort_made) < 0:
# print("ALERT: Get angle between needs some work")
# # exit()
if goal_angle_diff < 0:
print(goal_angle_diff)
print("eeek negative angle diff")
# exit()
if mode_heading is 'sqr':
effort_made = effort_made**2
all_offset_angles.append(goal_angle_diff)
all_effort_measures.append(effort_made)
print("All angle vectors to goals")
print(all_offset_angles)
print("All effort measures")
print(all_effort_measures)
target_val = all_effort_measures[target_index]
total = sum(all_effort_measures)
try:
all_probs = [x/total for x in all_effort_measures]
print(all_probs)
P_heading = (target_val) / total
except (ValueError, decimal.InvalidOperation):
print("Error! ...")
P_heading = (1.0 / len(all_probs))
num_goals = len(all_goals)
P_oa = ((1.0/num_goals)*(1.0 - visibility_coeff)) + (((visibility_coeff) * P_heading))
return P_oa
# def prob_heading_from_udiff(self, x, u, i, goal, visibility_coeff, force_mode=None, pure_prob=False):
# all_goals = self.goals
# x_current = x
# x1 = x
# x0 = x - u
# debug_dict = {'x': x, 'u': u, 'i':i, 'goal': goal, 'start': self.exp.get_start(), 'all_goals':self.exp.get_goals(), 'visibility_coeff': visibility_coeff, 'force_mode':force_mode, 'pure_prob':pure_prob, 'x0': x0}
# print("HEADING_Udiff COST INPUTS")
# print(debug_dict)
# if not np.array_equal(goal, self.exp.get_target_goal()):
# print("Goal and exp goal not the same in prob heading")