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,320 @@
1
+ import random, numpy as np
2
+ from typing import List, Tuple
3
+ from scipy import spatial
4
+
5
+ _TRUE_MIN_CONST = -10
6
+ _EPSILON = 1.0e-6
7
+ _SMALL_EPSILON = 1e-10
8
+ SIMTRACENUM = 10
9
+
10
+ PW = "PW"
11
+ GLOBAL = "GLOBAL"
12
+
13
+
14
+ def all_sensitivities_calc(training_traces: np.ndarray, initial_radii: np.ndarray):
15
+ num_traces: int
16
+ trace_len: int
17
+ ndims: int
18
+ num_traces, trace_len, ndims = training_traces.shape
19
+ normalizing_initial_set_radii: np.array = initial_radii.copy()
20
+ y_points: np.array = np.zeros((normalizing_initial_set_radii.shape[0], trace_len - 1))
21
+ normalizing_initial_set_radii[np.where(normalizing_initial_set_radii == 0)] = 1.0
22
+ for cur_dim_ind in range(1, ndims):
23
+ # keyi: move out of loop
24
+ normalized_initial_points: np.array = (
25
+ training_traces[:, 0, 1:] / normalizing_initial_set_radii
26
+ )
27
+ initial_distances = (
28
+ spatial.distance.pdist(normalized_initial_points, "chebyshev") + _SMALL_EPSILON
29
+ )
30
+ for cur_time_ind in range(1, trace_len):
31
+ y_points[cur_dim_ind - 1, cur_time_ind - 1] = np.max(
32
+ (
33
+ spatial.distance.pdist(
34
+ np.reshape(
35
+ training_traces[:, cur_time_ind, cur_dim_ind],
36
+ (training_traces.shape[0], 1),
37
+ ),
38
+ "chebyshev",
39
+ )
40
+ / normalizing_initial_set_radii[cur_dim_ind - 1]
41
+ )
42
+ / initial_distances
43
+ )
44
+ return y_points
45
+
46
+
47
+ def get_reachtube_segment(
48
+ training_traces: np.ndarray, initial_radii: np.ndarray, method="PWGlobal"
49
+ ) -> np.array:
50
+ num_traces: int = training_traces.shape[0]
51
+ ndims: int = training_traces.shape[2] # This includes time
52
+ trace_len: int = training_traces.shape[1]
53
+ center_trace: np.ndarray = training_traces[0, :, :]
54
+ trace_initial_time = center_trace[0, 0]
55
+ x_points: np.ndarray = center_trace[:, 0] - trace_initial_time
56
+ assert np.all(training_traces[0, :, 0] == training_traces[1:, :, 0])
57
+ y_points: np.ndarray = all_sensitivities_calc(training_traces, initial_radii)
58
+ points: np.ndarray = np.zeros((ndims - 1, trace_len, 2))
59
+ points[np.where(initial_radii != 0), 0, 1] = 1.0
60
+ points[:, :, 0] = np.reshape(x_points, (1, x_points.shape[0]))
61
+ points[:, 1:, 1] = y_points
62
+ normalizing_initial_set_radii: np.ndarray = initial_radii.copy()
63
+ normalizing_initial_set_radii[np.where(normalizing_initial_set_radii == 0)] = 1.0
64
+ df: np.ndarray = np.zeros((trace_len, ndims))
65
+ if method == "PW":
66
+ df[:, 1:] = np.transpose(
67
+ points[:, :, 1]
68
+ * np.reshape(normalizing_initial_set_radii, (normalizing_initial_set_radii.size, 1))
69
+ )
70
+ elif method == "PWGlobal":
71
+ # replace zeros with epsilons
72
+ # points[np.where(points[:, 0, 1] == 0), 0, 1] = 1.0e-100
73
+ # to fit exponentials make y axis log of sensitivity
74
+ points[:, :, 1] = np.maximum(points[:, :, 1], _EPSILON)
75
+ points[:, :, 1] = np.log(points[:, :, 1])
76
+ for dim_ind in range(1, ndims):
77
+ new_min = min(np.min(points[dim_ind - 1, 1:, 1]) + _TRUE_MIN_CONST, -10)
78
+ if initial_radii[dim_ind - 1] == 0:
79
+ # exclude initial set, then add true minimum points
80
+ new_points: np.ndarray = np.vstack(
81
+ (
82
+ np.array((points[dim_ind - 1, 1, 0], new_min)),
83
+ np.array((points[dim_ind - 1, -1, 0], new_min)),
84
+ )
85
+ )
86
+ else:
87
+ # start from zero, then add true minimum points
88
+ new_points: np.ndarray = np.vstack(
89
+ (
90
+ points[dim_ind - 1, 0, :],
91
+ np.array((points[dim_ind - 1, 0, 0], new_min)),
92
+ np.array((points[dim_ind - 1, -1, 0], new_min)),
93
+ )
94
+ )
95
+ df[0, dim_ind] = initial_radii[dim_ind - 1]
96
+ # Tuple order is start_time, end_time, slope, y-intercept
97
+ cur_dim_points = np.concatenate((points[dim_ind - 1, 1:, :], new_points), axis=0)
98
+ cur_hull: spatial.ConvexHull = spatial.ConvexHull(cur_dim_points)
99
+ linear_separators: List[Tuple[float, float, float, float, int, int]] = []
100
+ vert_inds = list(zip(cur_hull.vertices[:-1], cur_hull.vertices[1:]))
101
+ vert_inds.append((cur_hull.vertices[-1], cur_hull.vertices[0]))
102
+ for end_ind, start_ind in vert_inds:
103
+ if (
104
+ cur_dim_points[start_ind, 1] != new_min
105
+ and cur_dim_points[end_ind, 1] != new_min
106
+ ):
107
+ slope = (cur_dim_points[end_ind, 1] - cur_dim_points[start_ind, 1]) / (
108
+ cur_dim_points[end_ind, 0] - cur_dim_points[start_ind, 0]
109
+ )
110
+ y_intercept = (
111
+ cur_dim_points[start_ind, 1] - cur_dim_points[start_ind, 0] * slope
112
+ )
113
+ start_time = cur_dim_points[start_ind, 0]
114
+ end_time = cur_dim_points[end_ind, 0]
115
+ assert start_time < end_time
116
+ if start_time == 0:
117
+ linear_separators.append(
118
+ (start_time, end_time, slope, y_intercept, 0, end_ind + 1)
119
+ )
120
+ else:
121
+ linear_separators.append(
122
+ (start_time, end_time, slope, y_intercept, start_ind + 1, end_ind + 1)
123
+ )
124
+ linear_separators.sort()
125
+ prev_val = 0
126
+ prev_ind = 1 if initial_radii[dim_ind - 1] == 0 else 0
127
+ for linear_separator in linear_separators:
128
+ _, _, slope, y_intercept, start_ind, end_ind = linear_separator
129
+ assert prev_ind == start_ind
130
+ assert start_ind < end_ind
131
+ segment_t = center_trace[start_ind : end_ind + 1, 0]
132
+ segment_df = (
133
+ normalizing_initial_set_radii[dim_ind - 1]
134
+ * np.exp(y_intercept)
135
+ * np.exp(slope * segment_t)
136
+ )
137
+ segment_df[0] = max(segment_df[0], prev_val)
138
+ df[start_ind : end_ind + 1, dim_ind] = segment_df
139
+ prev_val = segment_df[-1]
140
+ prev_ind = end_ind
141
+ else:
142
+ print("Discrepancy computation method,", method, ", is not supported!")
143
+ raise ValueError
144
+ assert np.all(df >= 0)
145
+ reachtube_segment: np.ndarray = np.zeros((trace_len - 1, 2, ndims))
146
+ reachtube_segment[:, 0, :] = np.minimum(
147
+ center_trace[1:, :] - df[1:, :], center_trace[:-1, :] - df[:-1, :]
148
+ )
149
+ reachtube_segment[:, 1, :] = np.maximum(
150
+ center_trace[1:, :] + df[1:, :], center_trace[:-1, :] + df[:-1, :]
151
+ )
152
+ # assert 100% training accuracy (all trajectories are contained)
153
+ for trace_ind in range(training_traces.shape[0]):
154
+ if not (
155
+ np.all(reachtube_segment[:, 0, :] <= training_traces[trace_ind, 1:, :])
156
+ and np.all(reachtube_segment[:, 1, :] >= training_traces[trace_ind, 1:, :])
157
+ ):
158
+ # assert np.any(
159
+ # np.abs(training_traces[trace_ind, 0, 1:] - center_trace[0, 1:]) > initial_radii
160
+ # )
161
+ # print(
162
+ # f"Warning: Trace #{trace_ind}",
163
+ # "of this initial set is sampled outside of the initial set because of floating point error and is not contained in the initial set",
164
+ # )
165
+ pass
166
+ return reachtube_segment
167
+
168
+
169
+ def calcCenterPoint(lower, upper):
170
+ """
171
+ Calculate the center point between the lower and upper bound
172
+ The function only supports list since we assue initial set is always list
173
+
174
+ Args:
175
+ lower (list): lowerbound.
176
+ upper (list): upperbound.
177
+
178
+ Returns:
179
+ delta (list of float)
180
+
181
+ """
182
+
183
+ # Convert list into float in case they are int
184
+ lower = [float(val) for val in lower]
185
+ upper = [float(val) for val in upper]
186
+ assert len(lower) == len(upper), "Center Point List Range Error"
187
+ return [(upper[i] + lower[i]) / 2 for i in range(len(upper))]
188
+
189
+
190
+ def calcDelta(lower, upper):
191
+ """
192
+ Calculate the delta value between the lower and upper bound
193
+ The function only supports list since we assue initial set is always list
194
+
195
+ Args:
196
+ lower (list): lowerbound.
197
+ upper (list): upperbound.
198
+
199
+ Returns:
200
+ delta (list of float)
201
+
202
+ """
203
+ # Convert list into float in case they are int
204
+ lower = [float(val) for val in lower]
205
+ upper = [float(val) for val in upper]
206
+
207
+ assert len(lower) == len(upper), "Delta calc List Range Error"
208
+ return [(upper[i] - lower[i]) / 2 for i in range(len(upper))]
209
+
210
+
211
+ def randomPoint(lower, upper, seed=None):
212
+ """
213
+ Pick a random point between lower and upper bound
214
+ This function supports both int or list
215
+
216
+ Args:
217
+ lower (list or int or float): lower bound.
218
+ upper (list or int or float): upper bound.
219
+
220
+ Returns:
221
+ random point (either float or list of float)
222
+
223
+ """
224
+ if seed is not None:
225
+ random.seed(seed)
226
+
227
+ if isinstance(lower, int) or isinstance(lower, float):
228
+ return random.uniform(lower, upper)
229
+
230
+ if isinstance(lower, list):
231
+ assert len(lower) == len(upper), "Random Point List Range Error"
232
+
233
+ return [random.uniform(lower[i], upper[i]) for i in range(len(lower))]
234
+
235
+
236
+ def trimTraces(traces):
237
+ """
238
+ trim all traces to the same length
239
+
240
+ Args:
241
+ traces (list): list of traces generated by simulator
242
+ Returns:
243
+ traces (list) after trim to the same length
244
+
245
+ """
246
+
247
+ trace_len = min(len(trace) for trace in traces)
248
+ return [trace[:trace_len] for trace in traces]
249
+
250
+
251
+ def calc_bloated_tube(
252
+ mode_label,
253
+ initial_set,
254
+ time_horizon,
255
+ time_step,
256
+ sim_func,
257
+ bloating_method,
258
+ kvalue,
259
+ sim_trace_num,
260
+ guard_checker=None,
261
+ guard_str="",
262
+ lane_map=None,
263
+ ):
264
+ """
265
+ This function calculate the reach tube for single given mode
266
+
267
+ Args:
268
+ mode_label (str): mode name
269
+ initial_set (list): a list contains upper and lower bound of the initial set
270
+ time_horizon (float): time horizon to simulate
271
+ sim_func (function): simulation function
272
+ bloating_method (str): determine the bloating method for reach tube, either GLOBAL or PW
273
+ sim_trace_num (int): number of simulations used to calculate the discrepancy
274
+ kvalue (list): list of float used when bloating method set to PW
275
+ guard_checker (verse.core.guard.Guard or None): guard check object
276
+ guard_str (str): guard string
277
+
278
+ Returns:
279
+ Bloated reach tube
280
+
281
+ """
282
+ # print(initial_set)
283
+ # random.seed(4)
284
+ cur_center = calcCenterPoint(initial_set[0], initial_set[1])
285
+ cur_delta = calcDelta(initial_set[0], initial_set[1])
286
+ traces = [sim_func(mode_label, cur_center, time_horizon, time_step, lane_map)]
287
+ # Simulate SIMTRACENUM times to learn the sensitivity
288
+ for i in range(sim_trace_num):
289
+ new_init_point = randomPoint(initial_set[0], initial_set[1], i)
290
+ traces.append(sim_func(mode_label, new_init_point, time_horizon, time_step, lane_map))
291
+
292
+ # Trim the trace to the same length
293
+ traces = trimTraces(traces)
294
+ if guard_checker is not None:
295
+ # pre truncated traces to get better bloat result
296
+ max_idx = -1
297
+ for trace in traces:
298
+ ret_idx = guard_checker.guard_sim_trace_time(trace, guard_str)
299
+ max_idx = max(max_idx, ret_idx + 1)
300
+ for i in range(len(traces)):
301
+ traces[i] = traces[i][:max_idx]
302
+
303
+ # The major
304
+ if bloating_method == GLOBAL:
305
+ cur_reach_tube: np.ndarray = get_reachtube_segment(
306
+ np.array(traces), np.array(cur_delta), "PWGlobal"
307
+ )
308
+ # cur_reach_tube: np.ndarray = ReachabilityEngine.get_reachtube_segment_wrapper(np.array(traces), np.array(cur_delta))
309
+ elif bloating_method == PW:
310
+ cur_reach_tube: np.ndarray = get_reachtube_segment(
311
+ np.array(traces), np.array(cur_delta), "PW"
312
+ )
313
+ # cur_reach_tube: np.ndarray = ReachabilityEngine.get_reachtube_segment_wrapper(np.array(traces), np.array(cur_delta))
314
+ else:
315
+ raise ValueError("Unsupported bloating method '" + bloating_method + "'")
316
+ final_tube = np.zeros((cur_reach_tube.shape[0] * 2, cur_reach_tube.shape[2]))
317
+ final_tube[0::2, :] = cur_reach_tube[:, 0, :]
318
+ final_tube[1::2, :] = cur_reach_tube[:, 1, :]
319
+ # print(final_tube.tolist()[-2], final_tube.tolist()[-1])
320
+ return final_tube
@@ -0,0 +1,269 @@
1
+ import random, numpy as np
2
+ from typing import List, Tuple
3
+ from scipy import spatial
4
+
5
+ _TRUE_MIN_CONST = -10
6
+ _EPSILON = 1.0e-6
7
+ _SMALL_EPSILON = 1e-10
8
+ SIMTRACENUM = 10
9
+
10
+ PW = "PW"
11
+ GLOBAL = "GLOBAL"
12
+
13
+ def all_sensitivities_calc(training_traces: np.ndarray, initial_radii: np.ndarray):
14
+ num_traces: int
15
+ trace_len: int
16
+ ndims: int
17
+ num_traces, trace_len, ndims = training_traces.shape
18
+ normalizing_initial_set_radii: np.array = initial_radii.copy()
19
+ y_points: np.array = np.zeros(
20
+ (normalizing_initial_set_radii.shape[0], trace_len - 1))
21
+ normalizing_initial_set_radii[np.where(
22
+ normalizing_initial_set_radii < 1e-10)] = 1.0
23
+ for cur_dim_ind in range(1, ndims):
24
+ # keyi: move out of loop
25
+ normalized_initial_points: np.array = training_traces[:,
26
+ 0, 1:] / normalizing_initial_set_radii
27
+ initial_distances = spatial.distance.pdist(
28
+ normalized_initial_points, 'chebyshev') + _SMALL_EPSILON
29
+ for cur_time_ind in range(1, trace_len):
30
+ y_points[cur_dim_ind - 1, cur_time_ind - 1] = np.max((spatial.distance.pdist(
31
+ np.reshape(training_traces[:, cur_time_ind, cur_dim_ind],
32
+ (training_traces.shape[0], 1)), 'chebychev'
33
+ ) / normalizing_initial_set_radii[cur_dim_ind - 1]) / initial_distances)
34
+ return y_points
35
+
36
+ def get_reachtube_segment(training_traces: np.ndarray, initial_radii: np.ndarray, method='PWGlobal') -> np.array:
37
+ num_traces: int = training_traces.shape[0]
38
+ ndims: int = training_traces.shape[2] # This includes time
39
+ trace_len: int = training_traces.shape[1]
40
+ center_trace: np.ndarray = training_traces[0, :, :]
41
+ trace_initial_time = center_trace[0, 0]
42
+ x_points: np.ndarray = center_trace[:, 0] - trace_initial_time
43
+ assert np.all(training_traces[0, :, 0] == training_traces[1:, :, 0])
44
+ y_points: np.ndarray = all_sensitivities_calc(training_traces, initial_radii)
45
+ points: np.ndarray = np.zeros((ndims - 1, trace_len, 2))
46
+ points[np.where(initial_radii != 0), 0, 1] = 1.0
47
+ points[:, :, 0] = np.reshape(x_points, (1, x_points.shape[0]))
48
+ points[:, 1:, 1] = y_points
49
+ normalizing_initial_set_radii: np.ndarray = initial_radii.copy()
50
+ normalizing_initial_set_radii[np.where(normalizing_initial_set_radii == 0)] = 1.0
51
+ df: np.ndarray = np.zeros((trace_len, ndims))
52
+ if method == 'PW':
53
+ df[:, 1:] = np.transpose(
54
+ points[:, :, 1] * np.reshape(normalizing_initial_set_radii, (normalizing_initial_set_radii.size, 1)))
55
+ elif method == 'PWGlobal':
56
+ # replace zeros with epsilons
57
+ # points[np.where(points[:, 0, 1] == 0), 0, 1] = 1.0e-100
58
+ # to fit exponentials make y axis log of sensitivity
59
+ points[:, :, 1] = np.maximum(points[:, :, 1], _EPSILON)
60
+ points[:, :, 1] = np.log(points[:, :, 1])
61
+ for dim_ind in range(1, ndims):
62
+ new_min = min(np.min(points[dim_ind - 1, 1:, 1]) + _TRUE_MIN_CONST, -10)
63
+ if initial_radii[dim_ind - 1] == 0:
64
+ # exclude initial set, then add true minimum points
65
+ new_points: np.ndarray = np.vstack(
66
+ (np.array((points[dim_ind - 1, 1, 0], new_min)), np.array((points[dim_ind - 1, -1, 0], new_min))))
67
+ else:
68
+ # start from zero, then add true minimum points
69
+ new_points: np.ndarray = np.vstack((points[dim_ind - 1, 0, :],
70
+ np.array((points[dim_ind - 1, 0, 0], new_min)),
71
+ np.array((points[dim_ind - 1, -1, 0], new_min))))
72
+ df[0, dim_ind] = initial_radii[dim_ind - 1]
73
+ # Tuple order is start_time, end_time, slope, y-intercept
74
+ cur_dim_points = np.concatenate(
75
+ (points[dim_ind - 1, 1:, :], new_points), axis=0)
76
+ cur_hull: spatial.ConvexHull = spatial.ConvexHull(
77
+ cur_dim_points)
78
+ linear_separators: List[Tuple[float,
79
+ float, float, float, int, int]] = []
80
+ vert_inds = list(
81
+ zip(cur_hull.vertices[:-1], cur_hull.vertices[1:]))
82
+ vert_inds.append((cur_hull.vertices[-1], cur_hull.vertices[0]))
83
+ for end_ind, start_ind in vert_inds:
84
+ if cur_dim_points[start_ind, 1] != new_min and cur_dim_points[end_ind, 1] != new_min:
85
+ slope = (cur_dim_points[end_ind, 1] - cur_dim_points[start_ind, 1]) / (
86
+ cur_dim_points[end_ind, 0] - cur_dim_points[start_ind, 0])
87
+ y_intercept = cur_dim_points[start_ind, 1] - cur_dim_points[start_ind, 0] * slope
88
+ start_time = cur_dim_points[start_ind, 0]
89
+ end_time = cur_dim_points[end_ind, 0]
90
+ assert start_time < end_time
91
+ if start_time == 0:
92
+ linear_separators.append((start_time, end_time, slope, y_intercept, 0, end_ind + 1))
93
+ else:
94
+ linear_separators.append((start_time, end_time, slope, y_intercept, start_ind + 1, end_ind + 1))
95
+ linear_separators.sort()
96
+ prev_val = 0
97
+ prev_ind = 1 if initial_radii[dim_ind - 1] == 0 else 0
98
+ for linear_separator in linear_separators:
99
+ _, _, slope, y_intercept, start_ind, end_ind = linear_separator
100
+ assert prev_ind == start_ind
101
+ assert start_ind < end_ind
102
+ segment_t = center_trace[start_ind:end_ind + 1, 0]
103
+ segment_df = normalizing_initial_set_radii[dim_ind - 1] * np.exp(y_intercept) * np.exp(
104
+ slope * segment_t)
105
+ segment_df[0] = max(segment_df[0], prev_val)
106
+ df[start_ind:end_ind + 1, dim_ind] = segment_df
107
+ prev_val = segment_df[-1]
108
+ prev_ind = end_ind
109
+ else:
110
+ print('Discrepancy computation method,', method, ', is not supported!')
111
+ raise ValueError
112
+ assert (np.all(df >= 0))
113
+ reachtube_segment: np.ndarray = np.zeros((trace_len, 2, ndims))
114
+ reachtube_segment[:, 0, :] = center_trace - df
115
+ reachtube_segment[:, 1, :] = center_trace + df
116
+ # assert 100% training accuracy (all trajectories are contained)
117
+ for trace_ind in range(training_traces.shape[0]):
118
+ if not (np.all(reachtube_segment[:, 0, :] <= training_traces[trace_ind, :, :]) and np.all(reachtube_segment[:, 1, :] >= training_traces[trace_ind, :, :])):
119
+ # assert np.any(np.abs(training_traces[trace_ind, 0, 1:]-center_trace[0, 1:]) > initial_radii),
120
+ # print(f"Warning: Trace #{trace_ind}", "of this initial set is sampled outside of the initial set because of floating point error and is not contained in the initial set")
121
+ pass
122
+ return reachtube_segment
123
+
124
+ def calcCenterPoint(lower, upper):
125
+ """
126
+ Calculate the center point between the lower and upper bound
127
+ The function only supports list since we assue initial set is always list
128
+
129
+ Args:
130
+ lower (list): lowerbound.
131
+ upper (list): upperbound.
132
+
133
+ Returns:
134
+ delta (list of float)
135
+
136
+ """
137
+
138
+ # Convert list into float in case they are int
139
+ lower = [float(val) for val in lower]
140
+ upper = [float(val) for val in upper]
141
+ assert len(lower) == len(upper), "Center Point List Range Error"
142
+ return [(upper[i] + lower[i]) / 2 for i in range(len(upper))]
143
+
144
+ def calcDelta(lower, upper):
145
+ """
146
+ Calculate the delta value between the lower and upper bound
147
+ The function only supports list since we assume initial set is always list
148
+
149
+ Args:
150
+ lower (list): lowerbound.
151
+ upper (list): upperbound.
152
+
153
+ Returns:
154
+ delta (list of float)
155
+
156
+ """
157
+ # Convert list into float in case they are int
158
+ lower = [float(val) for val in lower]
159
+ upper = [float(val) for val in upper]
160
+
161
+ assert len(lower) == len(upper), "Delta calc List Range Error"
162
+ return [(upper[i] - lower[i]) / 2 for i in range(len(upper))]
163
+
164
+ def randomPoint(lower, upper, seed=None):
165
+ """
166
+ Pick a random point between lower and upper bound
167
+ This function supports both int or list
168
+
169
+ Args:
170
+ lower (list or int or float): lower bound.
171
+ upper (list or int or float): upper bound.
172
+
173
+ Returns:
174
+ random point (either float or list of float)
175
+
176
+ """
177
+ if seed is not None:
178
+ random.seed(seed)
179
+
180
+ if isinstance(lower, int) or isinstance(lower, float):
181
+ return random.uniform(lower, upper)
182
+
183
+ if isinstance(lower, list):
184
+ assert len(lower) == len(upper), "Random Point List Range Error"
185
+
186
+ return [random.uniform(lower[i], upper[i]) for i in range(len(lower))]
187
+
188
+ raise Exception(f"Unexpected initial set type: expected a list or instance of int or floats, got {type(lower)}")
189
+
190
+ def trimTraces(traces):
191
+ """
192
+ trim all traces to the same length
193
+
194
+ Args:
195
+ traces (list): list of traces generated by simulator
196
+ Returns:
197
+ traces (list) after trim to the same length
198
+
199
+ """
200
+
201
+ trace_len = min(len(trace) for trace in traces)
202
+ return [trace[:trace_len] for trace in traces]
203
+
204
+ def calc_bloated_tube_dryvr(
205
+ mode_label,
206
+ initial_set,
207
+ time_horizon,
208
+ time_step,
209
+ sim_func,
210
+ bloating_method,
211
+ kvalue,
212
+ sim_trace_num,
213
+ guard_checker=None,
214
+ guard_str="",
215
+ lane_map = None,
216
+ traces = None
217
+ ):
218
+ """
219
+ This function calculate the reach tube for single given mode
220
+
221
+ Args:
222
+ mode_label (str): mode name
223
+ initial_set (list): a list contains upper and lower bound of the initial set
224
+ time_horizon (float): time horizon to simulate
225
+ sim_func (function): simulation function
226
+ bloating_method (str): determine the bloating method for reach tube, either GLOBAL or PW
227
+ sim_trace_num (int): number of simulations used to calculate the discrepancy
228
+ kvalue (list): list of float used when bloating method set to PW
229
+ guard_checker (verse.core.guard.Guard or None): guard check object
230
+ guard_str (str): guard string
231
+
232
+ Returns:
233
+ Bloated reach tube
234
+
235
+ """
236
+ cur_center = calcCenterPoint(initial_set[0], initial_set[1])
237
+ cur_delta = calcDelta(initial_set[0], initial_set[1])
238
+ if traces is None:
239
+ traces = [sim_func(mode_label, cur_center, time_horizon, time_step, lane_map)]
240
+ # Simulate SIMTRACENUM times to learn the sensitivity
241
+ for i in range(sim_trace_num):
242
+ new_init_point = randomPoint(initial_set[0], initial_set[1], i)
243
+ traces.append(sim_func(mode_label, new_init_point, time_horizon, time_step, lane_map))
244
+ # Trim the trace to the same length
245
+ traces = trimTraces(traces)
246
+ if guard_checker is not None:
247
+ # pre truncated traces to get better bloat result
248
+ max_idx = -1
249
+ for trace in traces:
250
+ ret_idx = guard_checker.guard_sim_trace_time(trace, guard_str)
251
+ max_idx = max(max_idx, ret_idx + 1)
252
+ for i in range(len(traces)):
253
+ traces[i] = traces[i][:max_idx]
254
+
255
+ # The major
256
+ if bloating_method == GLOBAL:
257
+ cur_reach_tube: np.ndarray = get_reachtube_segment(np.array(traces), np.array(cur_delta), "PWGlobal")
258
+ # cur_reach_tube: np.ndarray = ReachabilityEngine.get_reachtube_segment_wrapper(np.array(traces), np.array(cur_delta))
259
+ elif bloating_method == PW:
260
+ cur_reach_tube: np.ndarray = get_reachtube_segment(np.array(traces), np.array(cur_delta), "PW")
261
+ # cur_reach_tube: np.ndarray = ReachabilityEngine.get_reachtube_segment_wrapper(np.array(traces), np.array(cur_delta))
262
+ else:
263
+ raise ValueError("Unsupported bloating method '" + bloating_method + "'")
264
+ final_tube = np.zeros((cur_reach_tube.shape[0]*2, cur_reach_tube.shape[2]))
265
+ final_tube[0::2, :] = cur_reach_tube[:, 0, :]
266
+ final_tube[1::2, :] = cur_reach_tube[:, 1, :]
267
+ # print(final_tube.tolist()[-2], final_tube.tolist()[-1])
268
+ return final_tube
269
+