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.
- verse/__init__.py +8 -0
- verse/agents/__init__.py +2 -0
- verse/agents/base_agent.py +93 -0
- verse/agents/example_agent/__init__.py +3 -0
- verse/agents/example_agent/ball_agent.py +43 -0
- verse/agents/example_agent/ballg_agent.py +42 -0
- verse/agents/example_agent/car_agent.py +254 -0
- verse/agents/example_agent/line_agent.py +40 -0
- verse/agents/example_agent/origin_agent.py +183 -0
- verse/agents/example_agent/prarm.json +184 -0
- verse/agents/example_agent/quadrotor_agent.py +249 -0
- verse/agents/example_agent/robot_agent.py +37 -0
- verse/agents/example_agent/sign_agent.py +15 -0
- verse/analysis/__init__.py +6 -0
- verse/analysis/analysis_tree.py +571 -0
- verse/analysis/dryvr.py +320 -0
- verse/analysis/dryvr_disc.py +269 -0
- verse/analysis/incremental.py +402 -0
- verse/analysis/mixmonotone.py +291 -0
- verse/analysis/parsed_wrap/__init__.py +3 -0
- verse/analysis/parsed_wrap/_cache.py +95 -0
- verse/analysis/parsed_wrap/bounded_angular.py +434 -0
- verse/analysis/parsed_wrap/bounded_map.py +53 -0
- verse/analysis/parsed_wrap/bounded_piecewise.py +292 -0
- verse/analysis/parsed_wrap/parser_wrapper.py +454 -0
- verse/analysis/parsed_wrap/sensor_parser.py +582 -0
- verse/analysis/parsed_wrap/wrapper_consts.py +29 -0
- verse/analysis/simulator.py +893 -0
- verse/analysis/verifier.py +1899 -0
- verse/automaton/__init__.py +3 -0
- verse/automaton/guard.py +1348 -0
- verse/automaton/hybrid_automaton.py +34 -0
- verse/automaton/hybrid_io_automaton.py +30 -0
- verse/automaton/reset.py +110 -0
- verse/map/__init__.py +5 -0
- verse/map/example_map/__init__.py +2 -0
- verse/map/example_map/intersection.py +127 -0
- verse/map/example_map/map_tacas.py +262 -0
- verse/map/example_map/simple_map.py +31 -0
- verse/map/example_map/simple_map2.py +188 -0
- verse/map/example_map/simple_map_3d.py +278 -0
- verse/map/lane.py +60 -0
- verse/map/lane_3d.py +78 -0
- verse/map/lane_map.py +120 -0
- verse/map/lane_map_3d.py +293 -0
- verse/map/lane_segment.py +324 -0
- verse/map/lane_segment_3d.py +638 -0
- verse/map/opendrive_parser.py +483 -0
- verse/parser/__init__.py +2 -0
- verse/parser/astunparser.py +989 -0
- verse/parser/parser.py +967 -0
- verse/plotter/__init__.py +23 -0
- verse/plotter/plotter2D.py +2864 -0
- verse/plotter/plotter2D_old.py +223 -0
- verse/plotter/plotter3D.py +147 -0
- verse/plotter/plotter3D_new.py +735 -0
- verse/plotter/plotterStar.py +105 -0
- verse/scenario/__init__.py +2 -0
- verse/scenario/scenario.py +595 -0
- verse/sensor/__init__.py +2 -0
- verse/sensor/base_sensor.py +135 -0
- verse/sensor/base_sensor_stars.py +159 -0
- verse/sensor/example_sensor/__init__.py +0 -0
- verse/sensor/example_sensor/craft_sensor.py +62 -0
- verse/sensor/example_sensor/craft_star_sensor.py +81 -0
- verse/sensor/example_sensor/quadrotor_sensor.py +62 -0
- verse/sensor/example_sensor/single_sensor.py +179 -0
- verse/sensor/example_sensor/thermo_sensor.py +62 -0
- verse/stars/__init__.py +3 -0
- verse/stars/reach_at_star.py +73 -0
- verse/stars/starset.py +889 -0
- verse/stars/startests.py +383 -0
- verse/utils/__init__.py +2 -0
- verse/utils/fixed_points.py +125 -0
- verse/utils/star_diams.py +171 -0
- verse/utils/star_manhattan.py +232 -0
- verse/utils/utils.py +437 -0
- verse_lib-2.0.0.dist-info/METADATA +337 -0
- verse_lib-2.0.0.dist-info/RECORD +82 -0
- verse_lib-2.0.0.dist-info/WHEEL +5 -0
- verse_lib-2.0.0.dist-info/licenses/Licence.txt +16 -0
- verse_lib-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import inspect
|
|
3
|
+
import textwrap
|
|
4
|
+
from typing import Callable, Dict, Tuple, List
|
|
5
|
+
import numpy as np
|
|
6
|
+
import torch
|
|
7
|
+
import torch.nn as nn
|
|
8
|
+
from .sensor_parser import parsed_sensor_expr
|
|
9
|
+
from .wrapper_consts import ALIASES, ANGULAR_FUNCTIONS, MAP_FUNCTIONS
|
|
10
|
+
from .bounded_angular import angular_span_rect_parser, angular_bounds_diff_correct, combine_angular_bounds
|
|
11
|
+
from .bounded_map import get_heading_bounds_optimized, get_lateral_distance_bounds_optimized
|
|
12
|
+
import itertools
|
|
13
|
+
from .bounded_piecewise import bounded_piecewise_z3, parse_piecewise_function
|
|
14
|
+
from . import _cache
|
|
15
|
+
|
|
16
|
+
def _parse_key(kind, func, input_bounds, piecewise_functions, track_mode, track_map, num_splits=1):
|
|
17
|
+
return _cache.make_key(
|
|
18
|
+
kind,
|
|
19
|
+
_cache.function_fingerprint(func),
|
|
20
|
+
input_bounds,
|
|
21
|
+
[_cache.function_fingerprint(f) for f in (piecewise_functions or [])],
|
|
22
|
+
_cache.object_fingerprint(track_mode),
|
|
23
|
+
_cache.object_fingerprint(track_map),
|
|
24
|
+
num_splits,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def clear_parse_cache():
|
|
28
|
+
"""Clear all cached parse_function and parse_function_array results."""
|
|
29
|
+
_cache.clear("parse")
|
|
30
|
+
|
|
31
|
+
def parse_function_array(func: Callable, input_bounds: List[List[float]], piecewise_functions: List[Callable] = None, track_mode=None, track_map=None, cache: bool = True, logging: bool = False, num_splits: int = 1):
|
|
32
|
+
"""
|
|
33
|
+
Wrapper for parse_function that accepts array-like bounds and converts them to the required dictionary format before processing using `parse_function`.
|
|
34
|
+
Supports domain partitioning for tighter bounds.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
func: Function to parse (must contain only assignments and return)
|
|
38
|
+
input_bounds: List of [min, max] pairs for each argument, e.g., [[min_x, max_x], [min_y, max_y], ...]
|
|
39
|
+
piecewise_functions: List of piecewise functions (optional)
|
|
40
|
+
track_mode: Track mode (optional)
|
|
41
|
+
track_map: Track map (optional)
|
|
42
|
+
cache: Whether to cache results (default True)
|
|
43
|
+
num_splits: Number of splits per dimension (default 1, no partitioning)
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
unioned_bounds: dict mapping each variable to a list of (min, max) bounds
|
|
47
|
+
|
|
48
|
+
Notes
|
|
49
|
+
-----
|
|
50
|
+
Caching is enabled by default because `verify` typically calls sense many times with the same arguments.
|
|
51
|
+
The cache key covers the function's source, the bounds, and every other argument (see `_cache`).
|
|
52
|
+
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
# NOTE: Extracting arg names for later
|
|
56
|
+
sig = inspect.signature(func)
|
|
57
|
+
arg_names = list(sig.parameters.keys())
|
|
58
|
+
|
|
59
|
+
# NOTE: bound-argument size validation
|
|
60
|
+
if len(input_bounds) != len(arg_names):
|
|
61
|
+
raise ValueError(f"Number of bounds ({len(input_bounds)}) must match number of function arguments ({len(arg_names)})")
|
|
62
|
+
|
|
63
|
+
# NOTE: bound validation
|
|
64
|
+
for i, bounds in enumerate(input_bounds):
|
|
65
|
+
if len(bounds) != 2:
|
|
66
|
+
raise ValueError(f"Each bound must be a [min, max] pair, got {bounds} for argument {arg_names[i]}")
|
|
67
|
+
min_val, max_val = bounds
|
|
68
|
+
if min_val > max_val:
|
|
69
|
+
raise ValueError(f"For argument {arg_names[i]}, expected max_val to be greater than min_val, got {min_val} (min_val) > {max_val} (max_val)")
|
|
70
|
+
|
|
71
|
+
key_bounds = [(float(lo), float(hi)) for lo, hi in input_bounds]
|
|
72
|
+
cache_key = _parse_key("array", func, key_bounds, piecewise_functions, track_mode, track_map, num_splits)
|
|
73
|
+
if cache:
|
|
74
|
+
hit = _cache.load("parse", cache_key)
|
|
75
|
+
if hit is not None:
|
|
76
|
+
return hit
|
|
77
|
+
|
|
78
|
+
if num_splits == 1:
|
|
79
|
+
parsed_input_bounds = {}
|
|
80
|
+
for name, bounds in zip(arg_names, input_bounds):
|
|
81
|
+
min_val, max_val = bounds
|
|
82
|
+
parsed_input_bounds[name] = [(min_val, max_val)]
|
|
83
|
+
unioned_bounds, _ = parse_function(func, parsed_input_bounds, piecewise_functions, track_mode, track_map, cache, logging)
|
|
84
|
+
if cache:
|
|
85
|
+
_cache.store("parse", cache_key, unioned_bounds)
|
|
86
|
+
return unioned_bounds
|
|
87
|
+
|
|
88
|
+
# NOTE: Domain partitioning: generate splits for each dimension if bounds are non-trivial
|
|
89
|
+
splits = []
|
|
90
|
+
for bounds in input_bounds:
|
|
91
|
+
min_val, max_val = bounds
|
|
92
|
+
if min_val == max_val:
|
|
93
|
+
splits.append([(min_val, max_val)])
|
|
94
|
+
else:
|
|
95
|
+
split_points = np.linspace(min_val, max_val, num_splits + 1)
|
|
96
|
+
splits.append(list(zip(split_points[:-1], split_points[1:]))) # NOTE: Cleverly creating split bounds
|
|
97
|
+
|
|
98
|
+
all_current_bounds = []
|
|
99
|
+
# FIXME: Consider getting rid of all_bounds_history in this case or handle it better -- currently is worthless
|
|
100
|
+
all_bounds_histories = []
|
|
101
|
+
|
|
102
|
+
for split_bounds in itertools.product(*splits):
|
|
103
|
+
parsed_input_bounds = {}
|
|
104
|
+
for name, bounds in zip(arg_names, split_bounds):
|
|
105
|
+
parsed_input_bounds[name] = [(bounds[0], bounds[1])]
|
|
106
|
+
current_bounds, bounds_history = parse_function(func, parsed_input_bounds, piecewise_functions, track_mode, track_map, cache, parent_cache=True)
|
|
107
|
+
all_current_bounds.append(current_bounds)
|
|
108
|
+
all_bounds_histories.append(bounds_history)
|
|
109
|
+
|
|
110
|
+
unioned_bounds = {}
|
|
111
|
+
for var in all_current_bounds[0].keys():
|
|
112
|
+
all_var_bounds = [cb[var] for cb in all_current_bounds]
|
|
113
|
+
has_multiple = any(len(bounds) > 1 for bounds in all_var_bounds)
|
|
114
|
+
# NOTE: Currently considering any variable with multiple bounds necessarily an angular bound
|
|
115
|
+
if has_multiple:
|
|
116
|
+
unioned_bounds[var] = combine_angular_bounds(all_var_bounds)
|
|
117
|
+
else:
|
|
118
|
+
all_mins = [b[0][0] for b in all_var_bounds]
|
|
119
|
+
all_maxs = [b[0][1] for b in all_var_bounds]
|
|
120
|
+
unioned_bounds[var] = [(min(all_mins), max(all_maxs))]
|
|
121
|
+
|
|
122
|
+
if cache:
|
|
123
|
+
_cache.store("parse", cache_key, unioned_bounds)
|
|
124
|
+
|
|
125
|
+
return unioned_bounds
|
|
126
|
+
|
|
127
|
+
def parse_function(func: Callable, input_bounds: Dict[str, List[Tuple[float, float]]], piecewise_functions: List[Callable] = None, track_mode = None, track_map = None, cache: bool = True, logging: bool = False, parent_cache = False):
|
|
128
|
+
"""
|
|
129
|
+
Process a function line-by-line, computing bounds at each step using parsed_sensor. Typically called as a helper function by `parsed_function_array`.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
func: Function to analyze (must contain only assignments and return)
|
|
133
|
+
input_bounds: Dict mapping variable names to (min, max) tuples
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
(current_bounds, bounds_history): Tuple where current_bounds is a dict mapping arg_names to bounds, which is a list of bounds, and bounds_history, which is a list that contains the entire revision history of current_bounds.
|
|
137
|
+
"""
|
|
138
|
+
key_bounds = {k: [tuple(float(x) for x in b) for b in v] for k, v in input_bounds.items()}
|
|
139
|
+
cache_key = _parse_key("function", func, key_bounds, piecewise_functions, track_mode, track_map)
|
|
140
|
+
if cache and not parent_cache:
|
|
141
|
+
hit = _cache.load("parse", cache_key)
|
|
142
|
+
if hit is not None:
|
|
143
|
+
return hit
|
|
144
|
+
|
|
145
|
+
source = inspect.getsource(func)
|
|
146
|
+
source = textwrap.dedent(source)
|
|
147
|
+
tree = ast.parse(source)
|
|
148
|
+
func_def = tree.body[0]
|
|
149
|
+
|
|
150
|
+
current_bounds = dict(input_bounds)
|
|
151
|
+
bounds_history = [dict(input_bounds)]
|
|
152
|
+
|
|
153
|
+
for stmt in func_def.body:
|
|
154
|
+
# NOTE: Currently returns don't do anything aside from just ending the parse loop
|
|
155
|
+
if isinstance(stmt, ast.Return):
|
|
156
|
+
break
|
|
157
|
+
|
|
158
|
+
elif isinstance(stmt, ast.Assign):
|
|
159
|
+
# NOTE: Currently only handling single variable assignments in functions
|
|
160
|
+
# TODO: Consider adding support for lists and list decomposition
|
|
161
|
+
if len(stmt.targets) != 1 or not isinstance(stmt.targets[0], ast.Name):
|
|
162
|
+
raise ValueError("Only simple assignments supported")
|
|
163
|
+
|
|
164
|
+
var_name = stmt.targets[0].id
|
|
165
|
+
rhs_expr = stmt.value
|
|
166
|
+
rhs_code = ast.unparse(rhs_expr)
|
|
167
|
+
|
|
168
|
+
rhs_bounds = compute_expression_bounds_with_parsed_sensor(
|
|
169
|
+
rhs_code,
|
|
170
|
+
list(current_bounds.keys()),
|
|
171
|
+
current_bounds,
|
|
172
|
+
piecewise_functions,
|
|
173
|
+
track_mode,
|
|
174
|
+
track_map
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
current_bounds[var_name] = rhs_bounds
|
|
178
|
+
bounds_history.append(dict(current_bounds))
|
|
179
|
+
|
|
180
|
+
if logging:
|
|
181
|
+
print(f"After {var_name} = {rhs_code}")
|
|
182
|
+
for rhs_bound in rhs_bounds:
|
|
183
|
+
print(f" {var_name} ∈ [{rhs_bound[0]:.6f}, {rhs_bound[-1]:.6f}]")
|
|
184
|
+
|
|
185
|
+
else:
|
|
186
|
+
raise Exception(f'Line is of type {type(stmt)} instead of assign or return.')
|
|
187
|
+
|
|
188
|
+
if cache and not parent_cache:
|
|
189
|
+
_cache.store("parse", cache_key, (current_bounds, bounds_history))
|
|
190
|
+
|
|
191
|
+
return current_bounds, bounds_history
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def compute_expression_bounds_with_parsed_sensor(
|
|
195
|
+
expr_code: str,
|
|
196
|
+
arg_names: List[str],
|
|
197
|
+
current_bounds: Dict[str, List[Tuple[float, float]]],
|
|
198
|
+
piecewise_functions: List[Callable] = None,
|
|
199
|
+
track_mode = None,
|
|
200
|
+
track_map = None,
|
|
201
|
+
) -> Tuple[float, float]:
|
|
202
|
+
"""
|
|
203
|
+
Use parsed_sensor to compute bounds for an expression.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
expr_code: Expression as string, e.g., "x**2 + y**2"
|
|
207
|
+
arg_names: List of argument names, e.g., ["x", "y"]
|
|
208
|
+
current_bounds: Current variable bounds
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
List of (lower_bound, upper_bound) tuples
|
|
212
|
+
|
|
213
|
+
Notes
|
|
214
|
+
-----
|
|
215
|
+
|
|
216
|
+
"""
|
|
217
|
+
for alias, func_name in ALIASES.items():
|
|
218
|
+
if alias in expr_code:
|
|
219
|
+
expr_code = expr_code.replace(alias, func_name)
|
|
220
|
+
|
|
221
|
+
tree = ast.parse(expr_code)
|
|
222
|
+
func_def = tree.body[0].value
|
|
223
|
+
|
|
224
|
+
args = []
|
|
225
|
+
for node in ast.walk(func_def):
|
|
226
|
+
if isinstance(node, ast.Call):
|
|
227
|
+
args = [arg.id for arg in node.args if isinstance(arg, ast.Name) and arg.id in arg_names]
|
|
228
|
+
break
|
|
229
|
+
|
|
230
|
+
# NOTE: Currently checking type of function using function name exclusively
|
|
231
|
+
if any(func in expr_code for func in ANGULAR_FUNCTIONS):
|
|
232
|
+
func_name = [func for func in ANGULAR_FUNCTIONS if func in expr_code][0]
|
|
233
|
+
bounds = handle_angular_function(func_name, args, current_bounds)
|
|
234
|
+
return bounds
|
|
235
|
+
|
|
236
|
+
elif piecewise_functions is not None and any(func.__name__ in expr_code for func in piecewise_functions):
|
|
237
|
+
func = next(func for func in piecewise_functions if func.__name__ in expr_code)
|
|
238
|
+
bounds = handle_piecewise_function(func, args, current_bounds)
|
|
239
|
+
return bounds
|
|
240
|
+
|
|
241
|
+
elif any(func in expr_code for func in MAP_FUNCTIONS):
|
|
242
|
+
func_name = [func for func in MAP_FUNCTIONS if func in expr_code][0]
|
|
243
|
+
bounds = handle_map_function(func_name, args, current_bounds, track_map, track_mode)
|
|
244
|
+
return bounds
|
|
245
|
+
else:
|
|
246
|
+
# NOTE: If no match to handle function in a special way, default to handling function as a CROWN function.
|
|
247
|
+
bounds = handle_crown_function(expr_code, arg_names, current_bounds)
|
|
248
|
+
return bounds
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def handle_angular_function(func_name: str, args: List[str], current_bounds: Dict[str, List[Tuple[float, float]]]) -> Tuple[float, float]:
|
|
252
|
+
"""
|
|
253
|
+
Handle angular functions (e.g., atan2, arctan2).
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
func_name: Name of the angular function
|
|
257
|
+
args: List of argument names
|
|
258
|
+
current_bounds: Current variable bounds
|
|
259
|
+
|
|
260
|
+
Returns:
|
|
261
|
+
List of (lower_bound, upper_bound) tuples
|
|
262
|
+
"""
|
|
263
|
+
func = globals()[func_name]
|
|
264
|
+
|
|
265
|
+
bounds_list = [current_bounds[name] for name in args]
|
|
266
|
+
output_bounds = []
|
|
267
|
+
|
|
268
|
+
for bounds_combination in itertools.product(*bounds_list):
|
|
269
|
+
try:
|
|
270
|
+
bounds = func(*bounds_combination)
|
|
271
|
+
output_bounds.append(bounds)
|
|
272
|
+
except Exception as e:
|
|
273
|
+
raise Exception(f"Error computing angular bounds: {e}")
|
|
274
|
+
|
|
275
|
+
combined_bounds = combine_angular_bounds(output_bounds)
|
|
276
|
+
|
|
277
|
+
return combined_bounds
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def handle_map_function(func_name: str, args: List[str], current_bounds: Dict[str, List[Tuple[float, float]]], track_mode, track_map) -> Tuple[float, float]:
|
|
281
|
+
"""
|
|
282
|
+
Handle map functions that require track_mode and track_map.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
func_name: Name of the map function
|
|
286
|
+
args: List of argument names
|
|
287
|
+
current_bounds: Current variable bounds
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
List of (lower_bound, upper_bound) tuples
|
|
291
|
+
"""
|
|
292
|
+
func = globals()[func_name]
|
|
293
|
+
|
|
294
|
+
bounds_list = [current_bounds[name] for name in args]
|
|
295
|
+
output_bounds = []
|
|
296
|
+
|
|
297
|
+
for bounds_combination in itertools.product(*bounds_list):
|
|
298
|
+
try:
|
|
299
|
+
bounds = func(track_mode, track_map, *bounds_combination)
|
|
300
|
+
output_bounds.append(bounds)
|
|
301
|
+
except Exception as e:
|
|
302
|
+
raise Exception(f"Error computing map function bounds: {e}")
|
|
303
|
+
|
|
304
|
+
return [(min(np.array(output_bounds)[:,0]), max(np.array(output_bounds)[:,1]))]
|
|
305
|
+
|
|
306
|
+
def handle_piecewise_function(func: Callable, args: List[str], current_bounds: Dict[str, List[Tuple[float, float]]]) -> Tuple[float, float]:
|
|
307
|
+
"""
|
|
308
|
+
Handle piecewise functions using Z3 analysis.
|
|
309
|
+
|
|
310
|
+
Args:
|
|
311
|
+
func: Piecewise function to analyze
|
|
312
|
+
args: List of argument names
|
|
313
|
+
current_bounds: Current variable bounds
|
|
314
|
+
|
|
315
|
+
Returns:
|
|
316
|
+
List of (lower_bound, upper_bound) tuples
|
|
317
|
+
"""
|
|
318
|
+
bounds_list = [current_bounds[name] for name in args]
|
|
319
|
+
all_output_bounds = []
|
|
320
|
+
# NOTE: Use helper to first convert piecewise function to (z3 expression, output expression) pairs
|
|
321
|
+
parsed_func = parse_piecewise_function(func)
|
|
322
|
+
|
|
323
|
+
for bounds_combination in itertools.product(*bounds_list):
|
|
324
|
+
try:
|
|
325
|
+
bounds_dict = dict(zip(args, bounds_combination))
|
|
326
|
+
res = bounded_piecewise_z3(parsed_func, bounds_dict)
|
|
327
|
+
for i in range(len(res)):
|
|
328
|
+
output_function = str(res[i][1])
|
|
329
|
+
# NOTE: Using constrained bounds so that if only part of the argument's bounds satisfy an expression, only that part will be used
|
|
330
|
+
constrained_bounds = {arg: [res[i][0][arg]] for arg in res[i][0]}
|
|
331
|
+
# NOTE: Assuming piecewise functions don't recursively call piecewise functions.
|
|
332
|
+
output_bounds = compute_expression_bounds_with_parsed_sensor(
|
|
333
|
+
output_function,
|
|
334
|
+
args,
|
|
335
|
+
constrained_bounds,
|
|
336
|
+
)
|
|
337
|
+
all_output_bounds.extend(output_bounds)
|
|
338
|
+
|
|
339
|
+
except Exception as e:
|
|
340
|
+
raise Exception(f"Error computing piecewise function bounds: {e}")
|
|
341
|
+
|
|
342
|
+
min_bound = min(min(output_bound) for output_bound in all_output_bounds)
|
|
343
|
+
max_bound = max(max(output_bound) for output_bound in all_output_bounds)
|
|
344
|
+
|
|
345
|
+
return [(min_bound, max_bound)]
|
|
346
|
+
|
|
347
|
+
def handle_crown_function(func_code: str, arg_names: List[str], current_bounds: Dict[str, List[Tuple[float, float]]]) -> Tuple[float, float]:
|
|
348
|
+
"""
|
|
349
|
+
Handle general expressions using CROWN (auto_LiRPA) for bound computation.
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
func_code: Code of the RHS expression
|
|
353
|
+
arg_names: Complete list of argument names
|
|
354
|
+
current_bounds: Current variable bounds
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
List of (lower_bound, upper_bound) tuples
|
|
358
|
+
"""
|
|
359
|
+
tree = ast.parse(func_code)
|
|
360
|
+
func_def = tree.body[0].value
|
|
361
|
+
|
|
362
|
+
args = []
|
|
363
|
+
for node in ast.walk(func_def):
|
|
364
|
+
if isinstance(node, ast.Name) and node.id in arg_names:
|
|
365
|
+
args.append(node.id)
|
|
366
|
+
|
|
367
|
+
args = sorted(list(set(args)))
|
|
368
|
+
|
|
369
|
+
func_source = f"""
|
|
370
|
+
def temp_func({', '.join(args)}):
|
|
371
|
+
return {func_code}
|
|
372
|
+
"""
|
|
373
|
+
|
|
374
|
+
bounds_list = [current_bounds[name] for name in args]
|
|
375
|
+
|
|
376
|
+
lower_bounds = []
|
|
377
|
+
upper_bounds = []
|
|
378
|
+
|
|
379
|
+
for bounds_combination in itertools.product(*bounds_list):
|
|
380
|
+
try:
|
|
381
|
+
lb, ub = parsed_sensor_expr(func_source, input_bounds=bounds_combination)
|
|
382
|
+
if isinstance(lb, np.ndarray):
|
|
383
|
+
lb = float(lb[0])
|
|
384
|
+
if isinstance(ub, np.ndarray):
|
|
385
|
+
ub = float(ub[0])
|
|
386
|
+
|
|
387
|
+
lower_bounds.append(lb)
|
|
388
|
+
upper_bounds.append(ub)
|
|
389
|
+
except ImportError:
|
|
390
|
+
raise # auto_LiRPA missing: keep the install instructions
|
|
391
|
+
except Exception as e:
|
|
392
|
+
if isinstance(e, TypeError) and ("Output of the model is expected to be a single torch.Tensor. Actual type: <class 'int'>" in str(e) or "Output of the model is expected to be a single torch.Tensor. Actual type: <class 'float'>" in str(e)):
|
|
393
|
+
try:
|
|
394
|
+
result = eval(func_code, {"np": np, "torch": torch})
|
|
395
|
+
return [(result, result)]
|
|
396
|
+
except Exception as e:
|
|
397
|
+
raise Exception(f"Error computing CROWN bounds: {e}")
|
|
398
|
+
|
|
399
|
+
raise Exception(f"Error computing CROWN bounds: {e}")
|
|
400
|
+
|
|
401
|
+
return [(min(lower_bounds), max(upper_bounds))]
|
|
402
|
+
|
|
403
|
+
if __name__ == "__main__":
|
|
404
|
+
from verse.map import opendrive_map
|
|
405
|
+
from enum import Enum, auto
|
|
406
|
+
import os
|
|
407
|
+
|
|
408
|
+
class TrackMode(Enum):
|
|
409
|
+
T0 = auto()
|
|
410
|
+
T1 = auto()
|
|
411
|
+
T2 = auto()
|
|
412
|
+
M01 = auto()
|
|
413
|
+
M12 = auto()
|
|
414
|
+
M21 = auto()
|
|
415
|
+
M10 = auto()
|
|
416
|
+
|
|
417
|
+
def test_sensor(x, y):
|
|
418
|
+
z = x**2 + y**2
|
|
419
|
+
w = arctan2(x,y)
|
|
420
|
+
m = arctan2(y,x)
|
|
421
|
+
z = torch.sqrt(z) + torch.sum(torch.stack([x,y], dim=-1), dim=-1)
|
|
422
|
+
return z
|
|
423
|
+
|
|
424
|
+
def map_sensor(x,y):
|
|
425
|
+
# z = get_lane_heading(x,y)
|
|
426
|
+
z = -2*np.pi
|
|
427
|
+
return z
|
|
428
|
+
|
|
429
|
+
def vis_sensor_piecewise(psi, phi):
|
|
430
|
+
if psi >= 0 and psi <= phi:
|
|
431
|
+
return -1
|
|
432
|
+
elif psi < 0 and psi >= -phi:
|
|
433
|
+
return 1
|
|
434
|
+
elif psi > phi:
|
|
435
|
+
return -2-psi**2
|
|
436
|
+
else:
|
|
437
|
+
return 2
|
|
438
|
+
|
|
439
|
+
def pw(psi, phi):
|
|
440
|
+
y = vis_sensor_piecewise(psi, phi)
|
|
441
|
+
return y
|
|
442
|
+
|
|
443
|
+
input_bounds = {'psi': [(-1.1, 2)], 'phi': [(1,1)]}
|
|
444
|
+
final_bounds, history = parse_function(pw, input_bounds, [vis_sensor_piecewise])
|
|
445
|
+
|
|
446
|
+
print("\nFinal bounds:")
|
|
447
|
+
for var, bounds in final_bounds.items():
|
|
448
|
+
for bound in bounds:
|
|
449
|
+
print(f" {var} ∈ [{bound[0]:.6f}, {bound[-1]:.6f}]")
|
|
450
|
+
|
|
451
|
+
# NOTE: The most complex part requiring some attention is the handling of piecewise functions
|
|
452
|
+
# and the interaction between Z3 optimization (bounded_piecewise_z3) and CROWN-based bound
|
|
453
|
+
# propagation. The compute_expression_bounds_with_parsed_sensor function dispatches to different
|
|
454
|
+
# handlers based on function type, which can create subtle edge cases when functions are nested.
|