verse-lib 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. verse/__init__.py +8 -0
  2. verse/agents/__init__.py +2 -0
  3. verse/agents/base_agent.py +93 -0
  4. verse/agents/example_agent/__init__.py +3 -0
  5. verse/agents/example_agent/ball_agent.py +43 -0
  6. verse/agents/example_agent/ballg_agent.py +42 -0
  7. verse/agents/example_agent/car_agent.py +254 -0
  8. verse/agents/example_agent/line_agent.py +40 -0
  9. verse/agents/example_agent/origin_agent.py +183 -0
  10. verse/agents/example_agent/prarm.json +184 -0
  11. verse/agents/example_agent/quadrotor_agent.py +249 -0
  12. verse/agents/example_agent/robot_agent.py +37 -0
  13. verse/agents/example_agent/sign_agent.py +15 -0
  14. verse/analysis/__init__.py +6 -0
  15. verse/analysis/analysis_tree.py +571 -0
  16. verse/analysis/dryvr.py +320 -0
  17. verse/analysis/dryvr_disc.py +269 -0
  18. verse/analysis/incremental.py +402 -0
  19. verse/analysis/mixmonotone.py +291 -0
  20. verse/analysis/parsed_wrap/__init__.py +3 -0
  21. verse/analysis/parsed_wrap/_cache.py +95 -0
  22. verse/analysis/parsed_wrap/bounded_angular.py +434 -0
  23. verse/analysis/parsed_wrap/bounded_map.py +53 -0
  24. verse/analysis/parsed_wrap/bounded_piecewise.py +292 -0
  25. verse/analysis/parsed_wrap/parser_wrapper.py +454 -0
  26. verse/analysis/parsed_wrap/sensor_parser.py +582 -0
  27. verse/analysis/parsed_wrap/wrapper_consts.py +29 -0
  28. verse/analysis/simulator.py +893 -0
  29. verse/analysis/verifier.py +1899 -0
  30. verse/automaton/__init__.py +3 -0
  31. verse/automaton/guard.py +1348 -0
  32. verse/automaton/hybrid_automaton.py +34 -0
  33. verse/automaton/hybrid_io_automaton.py +30 -0
  34. verse/automaton/reset.py +110 -0
  35. verse/map/__init__.py +5 -0
  36. verse/map/example_map/__init__.py +2 -0
  37. verse/map/example_map/intersection.py +127 -0
  38. verse/map/example_map/map_tacas.py +262 -0
  39. verse/map/example_map/simple_map.py +31 -0
  40. verse/map/example_map/simple_map2.py +188 -0
  41. verse/map/example_map/simple_map_3d.py +278 -0
  42. verse/map/lane.py +60 -0
  43. verse/map/lane_3d.py +78 -0
  44. verse/map/lane_map.py +120 -0
  45. verse/map/lane_map_3d.py +293 -0
  46. verse/map/lane_segment.py +324 -0
  47. verse/map/lane_segment_3d.py +638 -0
  48. verse/map/opendrive_parser.py +483 -0
  49. verse/parser/__init__.py +2 -0
  50. verse/parser/astunparser.py +989 -0
  51. verse/parser/parser.py +967 -0
  52. verse/plotter/__init__.py +23 -0
  53. verse/plotter/plotter2D.py +2864 -0
  54. verse/plotter/plotter2D_old.py +223 -0
  55. verse/plotter/plotter3D.py +147 -0
  56. verse/plotter/plotter3D_new.py +735 -0
  57. verse/plotter/plotterStar.py +105 -0
  58. verse/scenario/__init__.py +2 -0
  59. verse/scenario/scenario.py +595 -0
  60. verse/sensor/__init__.py +2 -0
  61. verse/sensor/base_sensor.py +135 -0
  62. verse/sensor/base_sensor_stars.py +159 -0
  63. verse/sensor/example_sensor/__init__.py +0 -0
  64. verse/sensor/example_sensor/craft_sensor.py +62 -0
  65. verse/sensor/example_sensor/craft_star_sensor.py +81 -0
  66. verse/sensor/example_sensor/quadrotor_sensor.py +62 -0
  67. verse/sensor/example_sensor/single_sensor.py +179 -0
  68. verse/sensor/example_sensor/thermo_sensor.py +62 -0
  69. verse/stars/__init__.py +3 -0
  70. verse/stars/reach_at_star.py +73 -0
  71. verse/stars/starset.py +889 -0
  72. verse/stars/startests.py +383 -0
  73. verse/utils/__init__.py +2 -0
  74. verse/utils/fixed_points.py +125 -0
  75. verse/utils/star_diams.py +171 -0
  76. verse/utils/star_manhattan.py +232 -0
  77. verse/utils/utils.py +437 -0
  78. verse_lib-2.0.0.dist-info/METADATA +337 -0
  79. verse_lib-2.0.0.dist-info/RECORD +82 -0
  80. verse_lib-2.0.0.dist-info/WHEEL +5 -0
  81. verse_lib-2.0.0.dist-info/licenses/Licence.txt +16 -0
  82. verse_lib-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,232 @@
1
+ import numpy as np
2
+ import scipy.optimize as sop
3
+ from scipy.optimize import LinearConstraint
4
+ from scipy.optimize import Bounds
5
+ from verse.stars import StarSet
6
+
7
+ def star_manhattan_distance(center, basis, C, g):
8
+ #order of x: [x1, x2, ..., y1, y2, ..., z1, z2, ..., b1, b2, ..., a11, a12, ..., a21, a22, ...]
9
+
10
+ # x1 = c1 + a11*v11 + a12*v21 + ...
11
+ # x2 = c2 + a12*v12 + a12*v22 + ...
12
+
13
+ # y1 = c1 + a21*v11 + a22*v12 + ...
14
+ # y2 = c2 + a21*v12 + a22*v22 + ...
15
+
16
+ #define N; large number for now
17
+ N = 1048575
18
+
19
+ #definitions
20
+ dimension = len(center) #number of dimensions for the set
21
+ num_vec = len(basis) #numver of vectors in the basis
22
+ num_cons = len(g)
23
+ x_len = dimension*4 + num_vec*2 #length of x, the vector of decision variables
24
+
25
+
26
+ #define c to minimize c @ x
27
+ c = np.zeros(x_len)
28
+ #set the z's to -1
29
+ z_start = dimension*2
30
+ for i in range(dimension):
31
+ c[i + z_start] = -1
32
+ #dimension*2 because z's start after x and y
33
+
34
+ #define integrality
35
+ integrality = np.zeros(x_len)
36
+ b_start = dimension*3
37
+ for i in range(dimension):
38
+ integrality[i + b_start] = 1 #integrality of b is 1; rest is 0
39
+
40
+ #create the A matrix
41
+ xy_cons = dimension*2
42
+ abs_cons = dimension*4
43
+ a_cons = len(C)*2
44
+ A = np.zeros((xy_cons + abs_cons + a_cons, x_len),dtype=float)
45
+
46
+ #define the constraints for the points
47
+ #constraints for xy
48
+ #in the form: x - a*v - ... = c
49
+ alpha_start = dimension*4
50
+ for i in range(xy_cons):
51
+ for j in range(x_len):
52
+ if i == j:
53
+ A[i,j] = 1
54
+ #for each dimension, the corresponding basis element is set
55
+ alpha_start_index = int(j - alpha_start - (np.floor(i/dimension))*num_vec)
56
+ if(alpha_start_index >= 0 and alpha_start_index < num_vec):
57
+ A[i,j] = -1*basis[alpha_start_index][i%dimension]
58
+
59
+
60
+ #each dimension has 4 constraints
61
+ for i in range(dimension):
62
+ #first constraint
63
+ A[z_start + i*4, i] = 1 #x
64
+ A[z_start + i*4, i + dimension] = -1 #y
65
+ A[z_start + i*4, i + dimension*2] = -1 #z
66
+ A[z_start + i*4, i + dimension*3] = N #b
67
+
68
+ #second constraint
69
+ A[z_start + i*4 + 1, i] = -1 #x
70
+ A[z_start + i*4 + 1, i + dimension] = 1 #y
71
+ A[z_start + i*4 + 1, i + dimension*2] = -1 #z
72
+ A[z_start + i*4 + 1, i + dimension*3] = -1*N #b
73
+
74
+ #third constraint
75
+ A[z_start + i*4 + 2, i] = 1 #x
76
+ A[z_start + i*4 + 2, i + dimension] = -1 #y
77
+ A[z_start + i*4 + 2, i + dimension*2] = -1 #z
78
+
79
+ #fourth constraint
80
+ A[z_start + i*4 + 3, i] = -1 #x
81
+ A[z_start + i*4 + 3, i + dimension] = 1 #y
82
+ A[z_start + i*4 + 3, i + dimension*2] = -1 #z
83
+
84
+
85
+ #alpha constraints
86
+ min_a_row = dimension*2 + dimension*4
87
+ min_a_col = dimension*4
88
+
89
+ for i in range(2):
90
+ for j in range(num_cons):
91
+ for k in range(num_vec):
92
+ A[min_a_row + i*num_cons + j, min_a_col + i*num_vec + k] = C[j][k]
93
+
94
+
95
+ #upper bound and lower bound
96
+ bu = np.zeros(xy_cons + abs_cons + a_cons)
97
+ bl = np.zeros(xy_cons + abs_cons + a_cons)
98
+
99
+ #x and y constraints; must equal center, so both upper and lower bound are set
100
+ for i in range(dimension):
101
+ bl[i] = center[i]
102
+ bl[i + dimension] = center[i]
103
+
104
+ bu[i] = center[i]
105
+ bu[i + dimension] = center[i]
106
+
107
+ #z constraints
108
+ #ask about -z
109
+ for i in range(dimension):
110
+ #upper constraint
111
+ bu[z_start + i*4 + 0] = np.inf #x
112
+ bu[z_start + i*4 + 1] = np.inf #y
113
+ bu[z_start + i*4 + 2] = 0 #z
114
+ bu[z_start + i*4 + 3] = 0 #b
115
+
116
+ bl[z_start + i*4 + 0] = 0 #x
117
+ bl[z_start + i*4 + 1] = -1*N #y
118
+ bl[z_start + i*4 + 2] = -1*np.inf #z
119
+ bl[z_start + i*4 + 3] = -1*np.inf #b
120
+
121
+
122
+ min_row = dimension*2 + dimension*4
123
+ for i in range(min_row, xy_cons + abs_cons + a_cons):
124
+ index = i - min_row
125
+ bu[i] = g[index % num_cons]
126
+ bl[i] = -1*np.inf
127
+
128
+
129
+ lower = -1*np.inf*np.ones(x_len)
130
+ upper = np.inf*np.ones(x_len)
131
+
132
+ for i in range(dimension):
133
+ lower[b_start + i] = 0
134
+ upper[b_start + i] = 1
135
+
136
+ constraints = LinearConstraint(A, bl, bu)
137
+ bounds = Bounds(lb = lower, ub = upper)
138
+ result = sop.milp(c=c, integrality=integrality, constraints=constraints, bounds=bounds)
139
+ if result.status != 0:
140
+ print("diam_failed")
141
+ return 0, 0
142
+
143
+ return -1*result.fun, 1
144
+
145
+
146
+
147
+ '''
148
+ center = [0,0]
149
+ basis = [[1,0],[0,1]]
150
+ C = np.array([[1,1],[1,-1],[-1,-1],[-1,1]])
151
+ g = [4,4,0,0]
152
+
153
+ star = StarSet(center, basis, C, g)
154
+ star.plot()
155
+
156
+ print(star_manhattan_distance(center, basis, C, g))
157
+
158
+ center = [0,0]
159
+ basis = [[1,0],[0,1]]
160
+ C = np.array([[1,0],[0,1],[-1,0],[0,-1],[1,1]])
161
+ g = [4,4,0,0,4]
162
+
163
+ star = StarSet(center, basis, C, g)
164
+ star.plot()
165
+
166
+ print(star_manhattan_distance(center, basis, C, g))
167
+
168
+
169
+ #3d
170
+
171
+
172
+
173
+ center = [0, 0, 0, 0, 0.1, 0.1]
174
+ basis = [[ 0.99974, -0, -0.005, 0, 0, 0],
175
+ [ 0, 0.9997, 0.00002, 0, 0, 0 ],
176
+ [ 0.0868, -0.00004, 0.74803, 0, 0, 0 ],
177
+ [ 0.00004, 0.08678, 0.00066, 0.74776, 0, 0 ],
178
+ [ 0, 0, 0, 0, 1, 0 ],
179
+ [ 0, 0, 0, 0, 0, 1 ]]
180
+ C = np.array([[ 1, 0, 0, 0, 0, 0],
181
+ [ 0, 1, 0, 0, 0, 0],
182
+ [ 0, 0, 1, 0, 0, 0],
183
+ [ 0, 0, 0, 1, 0, 0],
184
+ [ 0, 0, 0, 0, 1, 0],
185
+ [ 0, 0, 0, 0, 0, 1],
186
+ [-1, -0, -0, -0, -0, -0],
187
+ [-0, -1, -0, -0, -0, -0],
188
+ [-0, -0, -1, -0, -0, -0],
189
+ [-0, -0, -0, -1, -0, -0],
190
+ [-0, -0, -0, -0, -1, -0],
191
+ [-0, -0, -0, -0, -0, -1]])
192
+ g = [-875, -375, 0, 0, 0, 0, 925, 425, 0, 0, 0, 0]
193
+
194
+ star = StarSet(center, basis, C, g)
195
+ star.plot()
196
+
197
+ print(star_manhattan_distance(center, basis, C, g))
198
+ '''
199
+
200
+ # center = [0,0,0]
201
+ # basis = [[1,0,0],[0,1,0], [0,0,1]]
202
+ # C = np.array([[1,0,0],[0,1,0],[0,0,1],[-1,0,0],[0,-1,0],[0,0,-1]])
203
+ # g = [0.96117,0,0,-0.96117,0,0]
204
+
205
+ # star = StarSet(center, basis, C, g)
206
+ # star.plot()
207
+
208
+ # print(star_manhattan_distance(center, basis, C, g))
209
+
210
+
211
+
212
+
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
verse/utils/utils.py ADDED
@@ -0,0 +1,437 @@
1
+ import copy
2
+ import importlib
3
+ import itertools
4
+ from typing import Any, Tuple, Dict, Callable, List, Optional, Type, TypeVar, Union, Sequence
5
+
6
+ import numpy as np
7
+
8
+ # Useful types
9
+ Vector = Union[np.ndarray, Sequence[float]]
10
+ Matrix = Union[np.ndarray, Sequence[Sequence[float]]]
11
+ Interval = Union[
12
+ np.ndarray,
13
+ Tuple[Vector, Vector],
14
+ Tuple[Matrix, Matrix],
15
+ Tuple[float, float],
16
+ List[Vector],
17
+ List[Matrix],
18
+ List[float],
19
+ ]
20
+
21
+
22
+ def to_serializable(arg: Union[np.ndarray, List]) -> List:
23
+ if isinstance(arg, np.ndarray):
24
+ return arg.tolist()
25
+ return arg
26
+
27
+
28
+ def do_every(duration: float, timer: float) -> bool:
29
+ return duration < timer
30
+
31
+
32
+ def lmap(v: float, x: Interval, y: Interval) -> float:
33
+ """Linear map of value v with range x to desired range y."""
34
+ return y[0] + (v - x[0]) * (y[1] - y[0]) / (x[1] - x[0])
35
+
36
+
37
+ def get_class_path(cls: Callable) -> str:
38
+ return cls.__module__ + "." + cls.__qualname__
39
+
40
+
41
+ def class_from_path(path: str) -> Callable:
42
+ module_name, class_name = path.rsplit(".", 1)
43
+ class_object = getattr(importlib.import_module(module_name), class_name)
44
+ return class_object
45
+
46
+
47
+ def constrain(x: float, a: float, b: float) -> np.ndarray:
48
+ return np.clip(x, a, b)
49
+
50
+
51
+ def not_zero(x: float, eps: float = 1e-2) -> float:
52
+ if abs(x) > eps:
53
+ return x
54
+ elif x >= 0:
55
+ return eps
56
+ else:
57
+ return -eps
58
+
59
+
60
+ def wrap_to_pi(x: float) -> float:
61
+ return ((x + np.pi) % (2 * np.pi)) - np.pi
62
+
63
+
64
+ def point_in_rectangle(point: Vector, rect_min: Vector, rect_max: Vector) -> bool:
65
+ """
66
+ Check if a point is inside a rectangle
67
+
68
+ :param point: a point (x, y)
69
+ :param rect_min: x_min, y_min
70
+ :param rect_max: x_max, y_max
71
+ """
72
+ return rect_min[0] <= point[0] <= rect_max[0] and rect_min[1] <= point[1] <= rect_max[1]
73
+
74
+
75
+ def point_in_rotated_rectangle(
76
+ point: np.ndarray, center: np.ndarray, length: float, width: float, angle: float
77
+ ) -> bool:
78
+ """
79
+ Check if a point is inside a rotated rectangle
80
+
81
+ :param point: a point
82
+ :param center: rectangle center
83
+ :param length: rectangle length
84
+ :param width: rectangle width
85
+ :param angle: rectangle angle [rad]
86
+ :return: is the point inside the rectangle
87
+ """
88
+ c, s = np.cos(angle), np.sin(angle)
89
+ r = np.array([[c, -s], [s, c]])
90
+ ru = r.dot(point - center)
91
+ return point_in_rectangle(ru, (-length / 2, -width / 2), (length / 2, width / 2))
92
+
93
+
94
+ def point_in_ellipse(
95
+ point: Vector, center: Vector, angle: float, length: float, width: float
96
+ ) -> bool:
97
+ """
98
+ Check if a point is inside an ellipse
99
+
100
+ :param point: a point
101
+ :param center: ellipse center
102
+ :param angle: ellipse main axis angle
103
+ :param length: ellipse big axis
104
+ :param width: ellipse small axis
105
+ :return: is the point inside the ellipse
106
+ """
107
+ c, s = np.cos(angle), np.sin(angle)
108
+ r = np.matrix([[c, -s], [s, c]])
109
+ ru = r.dot(point - center)
110
+ return np.sum(np.square(ru / np.array([length, width]))) < 1
111
+
112
+
113
+ def rotated_rectangles_intersect(
114
+ rect1: Tuple[Vector, float, float, float], rect2: Tuple[Vector, float, float, float]
115
+ ) -> bool:
116
+ """
117
+ Do two rotated rectangles intersect?
118
+
119
+ :param rect1: (center, length, width, angle)
120
+ :param rect2: (center, length, width, angle)
121
+ :return: do they?
122
+ """
123
+ return has_corner_inside(rect1, rect2) or has_corner_inside(rect2, rect1)
124
+
125
+
126
+ def rect_corners(
127
+ center: np.ndarray,
128
+ length: float,
129
+ width: float,
130
+ angle: float,
131
+ include_midpoints: bool = False,
132
+ include_center: bool = False,
133
+ ) -> List[np.ndarray]:
134
+ """
135
+ Returns the positions of the corners of a rectangle.
136
+ :param center: the rectangle center
137
+ :param length: the rectangle length
138
+ :param width: the rectangle width
139
+ :param angle: the rectangle angle
140
+ :param include_midpoints: include middle of edges
141
+ :param include_center: include the center of the rect
142
+ :return: a list of positions
143
+ """
144
+ center = np.array(center)
145
+ half_l = np.array([length / 2, 0])
146
+ half_w = np.array([0, width / 2])
147
+ corners = [-half_l - half_w, -half_l + half_w, +half_l + half_w, +half_l - half_w]
148
+ if include_center:
149
+ corners += [[0, 0]]
150
+ if include_midpoints:
151
+ corners += [-half_l, half_l, -half_w, half_w]
152
+
153
+ c, s = np.cos(angle), np.sin(angle)
154
+ rotation = np.array([[c, -s], [s, c]])
155
+ return (rotation @ np.array(corners).T).T + np.tile(center, (len(corners), 1))
156
+
157
+
158
+ def has_corner_inside(
159
+ rect1: Tuple[Vector, float, float, float], rect2: Tuple[Vector, float, float, float]
160
+ ) -> bool:
161
+ """
162
+ Check if rect1 has a corner inside rect2
163
+
164
+ :param rect1: (center, length, width, angle)
165
+ :param rect2: (center, length, width, angle)
166
+ """
167
+ return any(
168
+ [
169
+ point_in_rotated_rectangle(p1, *rect2)
170
+ for p1 in rect_corners(*rect1, include_midpoints=True, include_center=True)
171
+ ]
172
+ )
173
+
174
+
175
+ def project_polygon(polygon: Vector, axis: Vector) -> Tuple[float, float]:
176
+ min_p, max_p = None, None
177
+ for p in polygon:
178
+ projected = p.dot(axis)
179
+ if min_p is None or projected < min_p:
180
+ min_p = projected
181
+ if max_p is None or projected > max_p:
182
+ max_p = projected
183
+ return min_p, max_p
184
+
185
+
186
+ def interval_distance(min_a: float, max_a: float, min_b: float, max_b: float):
187
+ """
188
+ Calculate the distance between [minA, maxA] and [minB, maxB]
189
+ The distance will be negative if the intervals overlap
190
+ """
191
+ return min_b - max_a if min_a < min_b else min_a - max_b
192
+
193
+
194
+ def are_polygons_intersecting(
195
+ a: Vector, b: Vector, displacement_a: Vector, displacement_b: Vector
196
+ ) -> Tuple[bool, bool, Optional[np.ndarray]]:
197
+ """
198
+ Checks if the two polygons are intersecting.
199
+
200
+ See https://www.codeproject.com/Articles/15573/2D-Polygon-Collision-Detection
201
+
202
+ :param a: polygon A, as a list of [x, y] points
203
+ :param b: polygon B, as a list of [x, y] points
204
+ :param displacement_a: velocity of the polygon A
205
+ :param displacement_b: velocity of the polygon B
206
+ :return: are intersecting, will intersect, translation vector
207
+ """
208
+ intersecting = will_intersect = True
209
+ min_distance = np.inf
210
+ translation, translation_axis = None, None
211
+ for polygon in [a, b]:
212
+ for p1, p2 in zip(polygon, polygon[1:]):
213
+ normal = np.array([-p2[1] + p1[1], p2[0] - p1[0]])
214
+ normal /= np.linalg.norm(normal)
215
+ min_a, max_a = project_polygon(a, normal)
216
+ min_b, max_b = project_polygon(b, normal)
217
+
218
+ if interval_distance(min_a, max_a, min_b, max_b) > 0:
219
+ intersecting = False
220
+
221
+ velocity_projection = normal.dot(displacement_a - displacement_b)
222
+ if velocity_projection < 0:
223
+ min_a += velocity_projection
224
+ else:
225
+ max_a += velocity_projection
226
+
227
+ distance = interval_distance(min_a, max_a, min_b, max_b)
228
+ if distance > 0:
229
+ will_intersect = False
230
+ if not intersecting and not will_intersect:
231
+ break
232
+ if abs(distance) < min_distance:
233
+ min_distance = abs(distance)
234
+ d = a[:-1].mean(axis=0) - b[:-1].mean(axis=0) # center difference
235
+ translation_axis = normal if d.dot(normal) > 0 else -normal
236
+
237
+ if will_intersect:
238
+ translation = min_distance * translation_axis
239
+ return intersecting, will_intersect, translation
240
+
241
+
242
+ def confidence_ellipsoid(
243
+ data: Dict[str, np.ndarray],
244
+ lambda_: float = 1e-5,
245
+ delta: float = 0.1,
246
+ sigma: float = 0.1,
247
+ param_bound: float = 1.0,
248
+ ) -> Tuple[np.ndarray, np.ndarray, float]:
249
+ """
250
+ Compute a confidence ellipsoid over the parameter theta, where y = theta^T phi
251
+
252
+ :param data: a dictionary {"features": [phi_0,...,phi_N], "outputs": [y_0,...,y_N]}
253
+ :param lambda_: l2 regularization parameter
254
+ :param delta: confidence level
255
+ :param sigma: noise covariance
256
+ :param param_bound: an upper-bound on the parameter norm
257
+ :return: estimated theta, Gramian matrix G_N_lambda, radius beta_N
258
+ """
259
+ phi = np.array(data["features"])
260
+ y = np.array(data["outputs"])
261
+ g_n_lambda = 1 / sigma * np.transpose(phi) @ phi + lambda_ * np.identity(phi.shape[-1])
262
+ theta_n_lambda = np.linalg.inv(g_n_lambda) @ np.transpose(phi) @ y / sigma
263
+ d = theta_n_lambda.shape[0]
264
+ beta_n = (
265
+ np.sqrt(2 * np.log(np.sqrt(np.linalg.det(g_n_lambda) / lambda_**d) / delta))
266
+ + np.sqrt(lambda_ * d) * param_bound
267
+ )
268
+ return theta_n_lambda, g_n_lambda, beta_n
269
+
270
+
271
+ def confidence_polytope(
272
+ data: dict, parameter_box: np.ndarray
273
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, float]:
274
+ """
275
+ Compute a confidence polytope over the parameter theta, where y = theta^T phi
276
+
277
+ :param data: a dictionary {"features": [phi_0,...,phi_N], "outputs": [y_0,...,y_N]}
278
+ :param parameter_box: a box [theta_min, theta_max] containing the parameter theta
279
+ :return: estimated theta, polytope vertices, Gramian matrix G_N_lambda, radius beta_N
280
+ """
281
+ param_bound = np.amax(np.abs(parameter_box))
282
+ theta_n_lambda, g_n_lambda, beta_n = confidence_ellipsoid(data, param_bound=param_bound)
283
+
284
+ values, pp = np.linalg.eig(g_n_lambda)
285
+ radius_matrix = np.sqrt(beta_n) * np.linalg.inv(pp) @ np.diag(np.sqrt(1 / values))
286
+ h = np.array(list(itertools.product([-1, 1], repeat=theta_n_lambda.shape[0])))
287
+ d_theta = np.array([radius_matrix @ h_k for h_k in h])
288
+
289
+ # Clip the parameter and confidence region within the prior parameter box.
290
+ theta_n_lambda = np.clip(theta_n_lambda, parameter_box[0], parameter_box[1])
291
+ for k, _ in enumerate(d_theta):
292
+ d_theta[k] = np.clip(
293
+ d_theta[k], parameter_box[0] - theta_n_lambda, parameter_box[1] - theta_n_lambda
294
+ )
295
+ return theta_n_lambda, d_theta, g_n_lambda, beta_n
296
+
297
+
298
+ def is_valid_observation(
299
+ y: np.ndarray,
300
+ phi: np.ndarray,
301
+ theta: np.ndarray,
302
+ gramian: np.ndarray,
303
+ beta: float,
304
+ sigma: float = 0.1,
305
+ ) -> bool:
306
+ """
307
+ Check if a new observation (phi, y) is valid according to a confidence ellipsoid on theta.
308
+
309
+ :param y: observation
310
+ :param phi: feature
311
+ :param theta: estimated parameter
312
+ :param gramian: Gramian matrix
313
+ :param beta: ellipsoid radius
314
+ :param sigma: noise covariance
315
+ :return: validity of the observation
316
+ """
317
+ y_hat = np.tensordot(theta, phi, axes=[0, 0])
318
+ error = np.linalg.norm(y - y_hat)
319
+ eig_phi, _ = np.linalg.eig(phi.transpose() @ phi)
320
+ eig_g, _ = np.linalg.eig(gramian)
321
+ error_bound = np.sqrt(np.amax(eig_phi) / np.amin(eig_g)) * beta + sigma
322
+ return error < error_bound
323
+
324
+
325
+ def is_consistent_dataset(data: dict, parameter_box: np.ndarray = None) -> bool:
326
+ """
327
+ Check whether a dataset {phi_n, y_n} is consistent
328
+
329
+ The last observation should be in the confidence ellipsoid obtained by the N-1 first observations.
330
+
331
+ :param data: a dictionary {"features": [phi_0,...,phi_N], "outputs": [y_0,...,y_N]}
332
+ :param parameter_box: a box [theta_min, theta_max] containing the parameter theta
333
+ :return: consistency of the dataset
334
+ """
335
+ train_set = copy.deepcopy(data)
336
+ y, phi = train_set["outputs"].pop(-1), train_set["features"].pop(-1)
337
+ y, phi = np.array(y)[..., np.newaxis], np.array(phi)[..., np.newaxis]
338
+ if train_set["outputs"] and train_set["features"]:
339
+ theta, _, gramian, beta = confidence_polytope(train_set, parameter_box=parameter_box)
340
+ return is_valid_observation(y, phi, theta, gramian, beta)
341
+ else:
342
+ return True
343
+
344
+
345
+ def near_split(x, num_bins=None, size_bins=None):
346
+ """
347
+ Split a number into several bins with near-even distribution.
348
+
349
+ You can either set the number of bins, or their size.
350
+ The sum of bins always equals the total.
351
+ :param x: number to split
352
+ :param num_bins: number of bins
353
+ :param size_bins: size of bins
354
+ :return: list of bin sizes
355
+ """
356
+ if num_bins:
357
+ quotient, remainder = divmod(x, num_bins)
358
+ return [quotient + 1] * remainder + [quotient] * (num_bins - remainder)
359
+ elif size_bins:
360
+ return near_split(x, num_bins=int(np.ceil(x / size_bins)))
361
+
362
+
363
+ def distance_to_circle(center, radius, direction):
364
+ scaling = radius * np.ones((2, 1))
365
+ a = np.linalg.norm(direction / scaling) ** 2
366
+ b = -2 * np.dot(np.transpose(center), direction / np.square(scaling))
367
+ c = np.linalg.norm(center / scaling) ** 2 - 1
368
+ root_inf, root_sup = solve_trinom(a, b, c)
369
+ if root_inf and root_inf > 0:
370
+ distance = root_inf
371
+ elif root_sup and root_sup > 0:
372
+ distance = 0
373
+ else:
374
+ distance = np.infty
375
+ return distance
376
+
377
+
378
+ def distance_to_rect(line: Tuple[np.ndarray, np.ndarray], rect: List[np.ndarray]):
379
+ """
380
+ Compute the intersection between a line segment and a rectangle.
381
+
382
+ See https://math.stackexchange.com/a/2788041.
383
+ :param line: a line segment [R, Q]
384
+ :param rect: a rectangle [A, B, C, D]
385
+ :return: the distance between R and the intersection of the segment RQ with the rectangle ABCD
386
+ """
387
+ r, q = line
388
+ a, b, c, d = rect
389
+ u = b - a
390
+ v = d - a
391
+ u, v = u / np.linalg.norm(u), v / np.linalg.norm(v)
392
+ rqu = (q - r) @ u
393
+ rqv = (q - r) @ v
394
+ interval_1 = [(a - r) @ u / rqu, (b - r) @ u / rqu]
395
+ interval_2 = [(a - r) @ v / rqv, (d - r) @ v / rqv]
396
+ interval_1 = interval_1 if rqu >= 0 else list(reversed(interval_1))
397
+ interval_2 = interval_2 if rqv >= 0 else list(reversed(interval_2))
398
+ if (
399
+ interval_distance(*interval_1, *interval_2) <= 0
400
+ and interval_distance(0, 1, *interval_1) <= 0
401
+ and interval_distance(0, 1, *interval_2) <= 0
402
+ ):
403
+ return max(interval_1[0], interval_2[0]) * np.linalg.norm(q - r)
404
+ else:
405
+ return np.inf
406
+
407
+
408
+ def solve_trinom(a, b, c):
409
+ delta = b**2 - 4 * a * c
410
+ if delta >= 0:
411
+ return (-b - np.sqrt(delta)) / (2 * a), (-b + np.sqrt(delta)) / (2 * a)
412
+ else:
413
+ return None, None
414
+
415
+
416
+ def sample_rect(rect: List[List[float]], seed=None) -> List[float]:
417
+ # point = []
418
+ # for i in range(len(rect[0])):
419
+ if seed is not None:
420
+ np.random.seed(seed)
421
+ res = np.random.uniform(rect[0], rect[1]).tolist()
422
+ return res
423
+
424
+
425
+ T = TypeVar("T")
426
+
427
+
428
+ def dedup(l: List[T], f: Callable[[T], Any] = (lambda a: a)) -> List[T]:
429
+ o = []
430
+ dl = [(i, f(i)) for i in l]
431
+ for i, k in dl:
432
+ for _, k_ in o:
433
+ if k == k_:
434
+ break
435
+ else:
436
+ o.append((i, k))
437
+ return [i for i, _ in o]