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,582 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import inspect, textwrap
|
|
3
|
+
import torch
|
|
4
|
+
import torch.nn as nn
|
|
5
|
+
try:
|
|
6
|
+
from auto_LiRPA import BoundedModule, BoundedTensor, PerturbationLpNorm
|
|
7
|
+
except ImportError as _err: # CROWN bounds are optional; everything else in Verse works without them
|
|
8
|
+
_LIRPA_IMPORT_ERROR = _err
|
|
9
|
+
_LIRPA_MESSAGE = (
|
|
10
|
+
"CROWN bounds for sensor programs need auto_LiRPA, which is not installed. Install it with\n"
|
|
11
|
+
" pip install \"auto_LiRPA @ git+https://github.com/Verified-Intelligence/auto_LiRPA.git@e393035\"\n"
|
|
12
|
+
"(see the Verse README, section 'Sensor programs and CROWN')."
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
def _missing_lirpa(*args, **kwargs):
|
|
16
|
+
raise ImportError(_LIRPA_MESSAGE) from _LIRPA_IMPORT_ERROR
|
|
17
|
+
|
|
18
|
+
BoundedModule = BoundedTensor = PerturbationLpNorm = _missing_lirpa
|
|
19
|
+
from .bounded_angular import box_extreme_error
|
|
20
|
+
import time
|
|
21
|
+
from multiprocessing import Pool
|
|
22
|
+
from itertools import product
|
|
23
|
+
import numpy as np
|
|
24
|
+
from . import _cache
|
|
25
|
+
|
|
26
|
+
FUNC_MAP = {
|
|
27
|
+
"sin": "torch.sin",
|
|
28
|
+
"cos": "torch.cos",
|
|
29
|
+
# "atan2": "torch.atan2",
|
|
30
|
+
"atan2": "atan2_crown_safe",
|
|
31
|
+
# "atan2": "atan2_crown",
|
|
32
|
+
"norm": "norm",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
def clear_sensor_cache():
|
|
36
|
+
"""Clear all cached parsed_sensor results."""
|
|
37
|
+
_cache.clear("sensor")
|
|
38
|
+
|
|
39
|
+
def norm(x, *args, **kwargs):
|
|
40
|
+
"""
|
|
41
|
+
Replacement for torch.norm that avoids ReduceL2 (unsupported in CROWN).
|
|
42
|
+
Works for:
|
|
43
|
+
- a single tensor
|
|
44
|
+
- a list/tuple of tensors (like [x, y])
|
|
45
|
+
Ensures non-negative inputs for sqrt by using x*x instead of abs(x).
|
|
46
|
+
"""
|
|
47
|
+
if isinstance(x, (list, tuple)):
|
|
48
|
+
x = torch.stack(list(x), dim=-1)
|
|
49
|
+
# Use x*x to ensure non-negativity - this keeps gradient information
|
|
50
|
+
# better than abs(x) or x**2
|
|
51
|
+
squared = torch.sum(x * x, dim=-1, keepdim=kwargs.get("keepdim", False))
|
|
52
|
+
# Add small epsilon to prevent divide by zero in backward pass
|
|
53
|
+
return torch.sqrt(squared + 1e-8)
|
|
54
|
+
|
|
55
|
+
def atan2_crown(y, x):
|
|
56
|
+
"""
|
|
57
|
+
Compute atan2 in a way compatible with CROWN bound computation.
|
|
58
|
+
Avoids negative denominators by using alternative formulation.
|
|
59
|
+
"""
|
|
60
|
+
eps = 1e-6 # small number for numerical stability
|
|
61
|
+
|
|
62
|
+
# We can rearrange y/x into sign(x)*y / abs(x) to ensure denominator is positive
|
|
63
|
+
abs_x = torch.abs(x) #
|
|
64
|
+
y_adj = y * torch.sign(x + eps)
|
|
65
|
+
|
|
66
|
+
# Now compute arctan with guaranteed positive denominator
|
|
67
|
+
theta = torch.atan(y_adj / abs_x)
|
|
68
|
+
|
|
69
|
+
# Handle quadrants correctly
|
|
70
|
+
x_neg = torch.relu(-x) / (abs_x + eps) # ≈ 1 if x<0 else 0
|
|
71
|
+
y_neg = torch.relu(-y) / (torch.abs(y)+eps) # ≈ 1 if y<0 else 0
|
|
72
|
+
|
|
73
|
+
# Quadrant corrections
|
|
74
|
+
correction = torch.pi * x_neg * (1 - 2*y_neg)
|
|
75
|
+
|
|
76
|
+
return theta + correction
|
|
77
|
+
|
|
78
|
+
def atan2_crown_safe(y, x):
|
|
79
|
+
"""
|
|
80
|
+
Compute atan2 assuming x and y bounds don't cross zero.
|
|
81
|
+
"""
|
|
82
|
+
eps = 1e-8
|
|
83
|
+
|
|
84
|
+
abs_x = torch.abs(x) #
|
|
85
|
+
y_adj = y * torch.sign(x + eps)
|
|
86
|
+
|
|
87
|
+
# Now compute arctan with guaranteed positive denominator
|
|
88
|
+
theta = torch.atan(y_adj / abs_x)
|
|
89
|
+
|
|
90
|
+
# Correction using only sign(), constants, and arithmetic
|
|
91
|
+
# When x < 0: correction = π * sign(y)
|
|
92
|
+
# When x > 0: correction = 0
|
|
93
|
+
#
|
|
94
|
+
# This can be written as:
|
|
95
|
+
# correction = π * (1 - sign(x)) / 2 * sign(y)
|
|
96
|
+
#
|
|
97
|
+
# Derivation:
|
|
98
|
+
# sign(x) = +1 if x > 0, -1 if x < 0
|
|
99
|
+
# (1 - sign(x))/2 = (1 - 1)/2 = 0 if x > 0
|
|
100
|
+
# = (1 - (-1))/2 = 1 if x < 0
|
|
101
|
+
correction = torch.pi * (1 - torch.sign(x)) / 2 * torch.sign(y)
|
|
102
|
+
|
|
103
|
+
return theta + correction
|
|
104
|
+
|
|
105
|
+
# def atan2_crown(y, x): # less accurate but more operations -> worse performance
|
|
106
|
+
# """
|
|
107
|
+
# Ultra-simplified linear approximation of atan2.
|
|
108
|
+
# Avoids division by sqrt to prevent Auto-LiRPA's special case handling.
|
|
109
|
+
# """
|
|
110
|
+
# eps = 1e-6
|
|
111
|
+
|
|
112
|
+
# # Instead of y/sqrt(x^2), compute y*x/sqrt(x^2 * x^2)
|
|
113
|
+
# x_sq = x * x
|
|
114
|
+
# numerator = y * x
|
|
115
|
+
# denom = torch.sqrt(x_sq * x_sq + eps)
|
|
116
|
+
|
|
117
|
+
# # Basic ratio computation
|
|
118
|
+
# theta = numerator / denom
|
|
119
|
+
|
|
120
|
+
# # Quadrant correction using relu
|
|
121
|
+
# x_is_neg = torch.relu(-x)
|
|
122
|
+
|
|
123
|
+
# return theta + (x_is_neg * torch.pi)
|
|
124
|
+
|
|
125
|
+
class TorchFuncModule(nn.Module):
|
|
126
|
+
def __init__(self, fn):
|
|
127
|
+
super().__init__()
|
|
128
|
+
self.fn = fn
|
|
129
|
+
self._compiled = self._compile(fn)
|
|
130
|
+
|
|
131
|
+
def _compile(self, fn):
|
|
132
|
+
# get source code
|
|
133
|
+
# src = inspect.getsource(fn)
|
|
134
|
+
# src = textwrap.dedent(src)
|
|
135
|
+
|
|
136
|
+
src: str = None
|
|
137
|
+
if type(fn) is str:
|
|
138
|
+
src = fn # assume that we are grabbing directly from code
|
|
139
|
+
else: # FIXME: this should be an elif
|
|
140
|
+
src = inspect.getsource(fn)
|
|
141
|
+
src = textwrap.dedent(src)
|
|
142
|
+
|
|
143
|
+
tree = ast.parse(src)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# function def is the first node
|
|
147
|
+
func_def = tree.body[0]
|
|
148
|
+
arg_names = [arg.arg for arg in func_def.args.args]
|
|
149
|
+
|
|
150
|
+
# replace bare names with torch equivalents
|
|
151
|
+
class TorchTransformer(ast.NodeTransformer):
|
|
152
|
+
def visit_Name(self, node):
|
|
153
|
+
if node.id in FUNC_MAP:
|
|
154
|
+
return ast.copy_location(
|
|
155
|
+
ast.parse(FUNC_MAP[node.id], mode="eval").body,
|
|
156
|
+
node
|
|
157
|
+
)
|
|
158
|
+
return node
|
|
159
|
+
|
|
160
|
+
new_tree = TorchTransformer().visit(tree)
|
|
161
|
+
ast.fix_missing_locations(new_tree)
|
|
162
|
+
|
|
163
|
+
code = compile(new_tree, filename="<userfunc>", mode="exec")
|
|
164
|
+
|
|
165
|
+
def wrapped(*args):
|
|
166
|
+
local_env = {"torch": torch,
|
|
167
|
+
"np": np,
|
|
168
|
+
"norm": norm,
|
|
169
|
+
"atan2_crown": atan2_crown,
|
|
170
|
+
"atan2_crown_safe": atan2_crown_safe,
|
|
171
|
+
}
|
|
172
|
+
for name, val in zip(arg_names, args):
|
|
173
|
+
local_env[name] = val
|
|
174
|
+
exec(code, local_env)
|
|
175
|
+
return local_env[func_def.name](*args) # call transformed fn
|
|
176
|
+
|
|
177
|
+
return wrapped
|
|
178
|
+
|
|
179
|
+
def forward(self, *args):
|
|
180
|
+
# return self._compiled(*args)
|
|
181
|
+
out = self._compiled(*args)
|
|
182
|
+
if isinstance(out, tuple) or isinstance(out, list):
|
|
183
|
+
# return torch.stack(out, dim=-1).squeeze(1)
|
|
184
|
+
return torch.concat(list(out), dim=-1) # shouldn't need list(out) but required due to torch quirks -- alternative above works without needing casting to list first
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
# def parsed_sensor(sensor_function, inputs=None, input_bounds=None, device="cpu", sim: bool = False):
|
|
188
|
+
# """
|
|
189
|
+
# Process inputs through a sensor function using TorchFuncModule
|
|
190
|
+
|
|
191
|
+
# Args:
|
|
192
|
+
# sensor_function: The sensor function to be processed
|
|
193
|
+
# inputs: For sim=True: numpy array of inputs. Ignored if sim=False.
|
|
194
|
+
# input_bounds: List of (lower, upper) bound tuples for each input. Required if sim=False
|
|
195
|
+
# device: Device to run computations on
|
|
196
|
+
# sim: If True, run in simulation mode. If False, compute bounds
|
|
197
|
+
|
|
198
|
+
# Returns:
|
|
199
|
+
# If sim=True: Direct sensor output
|
|
200
|
+
# If sim=False: (lower bounds, upper bounds) of the sensor output
|
|
201
|
+
# """
|
|
202
|
+
# model = TorchFuncModule(sensor_function)
|
|
203
|
+
|
|
204
|
+
# if sim:
|
|
205
|
+
# if inputs is None:
|
|
206
|
+
# raise ValueError("inputs required for simulation mode")
|
|
207
|
+
# # Convert numpy inputs to torch tensors
|
|
208
|
+
# torch_inputs = [torch.tensor([x], dtype=torch.float32) for x in inputs]
|
|
209
|
+
# return model(*torch_inputs).numpy()
|
|
210
|
+
# else:
|
|
211
|
+
# if input_bounds is None:
|
|
212
|
+
# raise ValueError("input_bounds required for bound computation mode")
|
|
213
|
+
|
|
214
|
+
# # Create dummy inputs for CROWN model initialization
|
|
215
|
+
# dummy_inputs = tuple([torch.zeros(1, 1) for _ in input_bounds])
|
|
216
|
+
|
|
217
|
+
# # Initialize CROWN model
|
|
218
|
+
# lirpa_model = BoundedModule(model, dummy_inputs, device=device)
|
|
219
|
+
|
|
220
|
+
# # Create bounded tensors for each input
|
|
221
|
+
# bounded_inputs = []
|
|
222
|
+
# for lower, upper in input_bounds:
|
|
223
|
+
# # Convert to torch tensors if they're numpy arrays
|
|
224
|
+
# lower = torch.tensor(lower, dtype=torch.float32)
|
|
225
|
+
# upper = torch.tensor(upper, dtype=torch.float32)
|
|
226
|
+
|
|
227
|
+
# # Calculate center as average of bounds
|
|
228
|
+
# center = ((lower + upper) / 2).unsqueeze(0)
|
|
229
|
+
# lower = lower.unsqueeze(0)
|
|
230
|
+
# upper = upper.unsqueeze(0)
|
|
231
|
+
|
|
232
|
+
# # Create perturbation and bounded tensor
|
|
233
|
+
# perturb = PerturbationLpNorm(x_L=lower, x_U=upper)
|
|
234
|
+
# bounded_inputs.append(BoundedTensor(center, perturb))
|
|
235
|
+
|
|
236
|
+
# # Compute bounds using CROWN
|
|
237
|
+
# lb, ub = lirpa_model.compute_bounds(
|
|
238
|
+
# x=tuple(bounded_inputs),
|
|
239
|
+
# method="CROWN"
|
|
240
|
+
# )
|
|
241
|
+
|
|
242
|
+
# return lb.detach().numpy()[0], ub.detach().numpy()[0]
|
|
243
|
+
|
|
244
|
+
def compute_bounds_for_split(args):
|
|
245
|
+
"""Helper function to compute bounds for a single split"""
|
|
246
|
+
split_bounds, sensor_function = args
|
|
247
|
+
|
|
248
|
+
# Create model inside worker process
|
|
249
|
+
model = TorchFuncModule(sensor_function)
|
|
250
|
+
dummy_inputs = tuple([torch.zeros(1, 1) for _ in split_bounds])
|
|
251
|
+
lirpa_model = BoundedModule(model, dummy_inputs, device="cpu")
|
|
252
|
+
|
|
253
|
+
bounded_inputs = []
|
|
254
|
+
for bounds in split_bounds:
|
|
255
|
+
lower, upper = bounds
|
|
256
|
+
lower = torch.tensor(lower, dtype=torch.float32)
|
|
257
|
+
upper = torch.tensor(upper, dtype=torch.float32)
|
|
258
|
+
center = ((lower + upper) / 2).unsqueeze(0)
|
|
259
|
+
perturb = PerturbationLpNorm(x_L=lower.unsqueeze(0), x_U=upper.unsqueeze(0))
|
|
260
|
+
bounded_inputs.append(BoundedTensor(center, perturb))
|
|
261
|
+
|
|
262
|
+
lb, ub = lirpa_model.compute_bounds(x=tuple(bounded_inputs), method="CROWN")
|
|
263
|
+
return lb.detach().numpy()[0], ub.detach().numpy()[0]
|
|
264
|
+
|
|
265
|
+
def parsed_sensor(sensor_function, inputs=None, input_bounds=None, device="cpu", sim: bool = False, num_splits=1):
|
|
266
|
+
"""
|
|
267
|
+
Process inputs through a sensor function using TorchFuncModule with domain splitting
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
sensor_function: The sensor function to be processed
|
|
271
|
+
inputs: For sim=True: numpy array of inputs. Ignored if sim=False.
|
|
272
|
+
input_bounds: List of (lower, upper) bound tuples for each input. Required if sim=False
|
|
273
|
+
device: Device to run computations on
|
|
274
|
+
sim: If True, run in simulation mode. If False, compute bounds
|
|
275
|
+
num_splits: Number of splits per dimension (default=2)
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
if sim:
|
|
279
|
+
if inputs is None:
|
|
280
|
+
raise ValueError("inputs required for simulation mode")
|
|
281
|
+
model = TorchFuncModule(sensor_function)
|
|
282
|
+
torch_inputs = [torch.tensor([x], dtype=torch.float32) for x in inputs]
|
|
283
|
+
with torch.no_grad():
|
|
284
|
+
return model(*torch_inputs).numpy()
|
|
285
|
+
|
|
286
|
+
if input_bounds is None:
|
|
287
|
+
raise ValueError("input_bounds required for bound computation mode")
|
|
288
|
+
|
|
289
|
+
cache_key = _cache.make_key(
|
|
290
|
+
"parsed_sensor", _cache.function_fingerprint(sensor_function),
|
|
291
|
+
[(float(lo), float(hi)) for lo, hi in input_bounds], num_splits, str(device),
|
|
292
|
+
)
|
|
293
|
+
hit = _cache.load("sensor", cache_key)
|
|
294
|
+
if hit is not None:
|
|
295
|
+
return hit
|
|
296
|
+
|
|
297
|
+
model = TorchFuncModule(sensor_function)
|
|
298
|
+
dummy_inputs = tuple([torch.zeros(1, 1) for _ in input_bounds])
|
|
299
|
+
lirpa_model = BoundedModule(model, dummy_inputs, device=device)
|
|
300
|
+
|
|
301
|
+
# Initialize bounds as None
|
|
302
|
+
global_lb = None
|
|
303
|
+
global_ub = None
|
|
304
|
+
|
|
305
|
+
# Generate split points for each dimension
|
|
306
|
+
splits = []
|
|
307
|
+
for lower, upper in input_bounds:
|
|
308
|
+
if lower == upper:
|
|
309
|
+
# For unsplit dimensions, create a list with a single tuple
|
|
310
|
+
splits.append([(lower, lower)])
|
|
311
|
+
else:
|
|
312
|
+
split_points = np.linspace(lower, upper, num_splits+1)
|
|
313
|
+
# Create list of tuples for split points
|
|
314
|
+
splits.append(list(zip(split_points[:-1], split_points[1:])))
|
|
315
|
+
|
|
316
|
+
# Compute cartesian product of splits
|
|
317
|
+
for split_bounds in product(*splits):
|
|
318
|
+
# Create bounded tensors for this sub-domain
|
|
319
|
+
bounded_inputs = []
|
|
320
|
+
for bounds in split_bounds: # bounds is already a (lower, upper) tuple
|
|
321
|
+
lower, upper = bounds # Unpack the tuple
|
|
322
|
+
lower = torch.tensor(lower, dtype=torch.float32)
|
|
323
|
+
upper = torch.tensor(upper, dtype=torch.float32)
|
|
324
|
+
center = ((lower + upper) / 2).unsqueeze(0)
|
|
325
|
+
lower = lower.unsqueeze(0)
|
|
326
|
+
upper = upper.unsqueeze(0)
|
|
327
|
+
perturb = PerturbationLpNorm(x_L=lower, x_U=upper)
|
|
328
|
+
bounded_inputs.append(BoundedTensor(center, perturb))
|
|
329
|
+
|
|
330
|
+
# Compute bounds for this sub-domain
|
|
331
|
+
lb, ub = lirpa_model.compute_bounds(
|
|
332
|
+
x=tuple(bounded_inputs),
|
|
333
|
+
method="CROWN"
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
# Update global bounds
|
|
337
|
+
lb, ub = lb.detach().numpy()[0], ub.detach().numpy()[0]
|
|
338
|
+
if global_lb is None:
|
|
339
|
+
global_lb = lb
|
|
340
|
+
global_ub = ub
|
|
341
|
+
else:
|
|
342
|
+
global_lb = np.minimum(global_lb, lb)
|
|
343
|
+
global_ub = np.maximum(global_ub, ub)
|
|
344
|
+
|
|
345
|
+
_cache.store("sensor", cache_key, (global_lb, global_ub))
|
|
346
|
+
|
|
347
|
+
return global_lb, global_ub
|
|
348
|
+
|
|
349
|
+
def parsed_sensor_expr(sensor_src, input_bounds, device = 'cpu', nonce='', num_splits=1):
|
|
350
|
+
if input_bounds is None:
|
|
351
|
+
raise ValueError("input_bounds required for bound computation mode")
|
|
352
|
+
|
|
353
|
+
# TODO: start caching only when nonce exists for each expression
|
|
354
|
+
# # Create cache directory if it doesn't exist
|
|
355
|
+
# cache_dir = Path(__file__).parent / "sensor_cache" # this creates the folder at aprod, can change later to just Path("--") if I'd rather create the folder in the working directory instead
|
|
356
|
+
# cache_dir.mkdir(exist_ok=True)
|
|
357
|
+
|
|
358
|
+
# # Generate cache key from input bounds and function name
|
|
359
|
+
# cache_key = get_cache_key(np.array(input_bounds), nonce)
|
|
360
|
+
# cache_file = cache_dir / f"bounds_{cache_key}_splits_{num_splits}.pkl"
|
|
361
|
+
|
|
362
|
+
# # Check if cached result exists
|
|
363
|
+
# if cache_file.exists():
|
|
364
|
+
# with open(cache_file, 'rb') as f:
|
|
365
|
+
# return pickle.load(f)
|
|
366
|
+
|
|
367
|
+
model = TorchFuncModule(sensor_src)
|
|
368
|
+
dummy_inputs = tuple([torch.zeros(1, 1) for _ in input_bounds])
|
|
369
|
+
lirpa_model = BoundedModule(model, dummy_inputs, device=device)
|
|
370
|
+
|
|
371
|
+
# Initialize bounds as None
|
|
372
|
+
global_lb = None
|
|
373
|
+
global_ub = None
|
|
374
|
+
|
|
375
|
+
# Generate split points for each dimension
|
|
376
|
+
splits = []
|
|
377
|
+
for lower, upper in input_bounds:
|
|
378
|
+
if lower == upper:
|
|
379
|
+
# For unsplit dimensions, create a list with a single tuple
|
|
380
|
+
splits.append([(lower, lower)])
|
|
381
|
+
else:
|
|
382
|
+
split_points = np.linspace(lower, upper, num_splits+1)
|
|
383
|
+
# Create list of tuples for split points
|
|
384
|
+
splits.append(list(zip(split_points[:-1], split_points[1:])))
|
|
385
|
+
|
|
386
|
+
# Compute cartesian product of splits
|
|
387
|
+
for split_bounds in product(*splits):
|
|
388
|
+
# Create bounded tensors for this sub-domain
|
|
389
|
+
bounded_inputs = []
|
|
390
|
+
for bounds in split_bounds: # bounds is already a (lower, upper) tuple
|
|
391
|
+
lower, upper = bounds # Unpack the tuple
|
|
392
|
+
lower = torch.tensor(lower, dtype=torch.float32)
|
|
393
|
+
upper = torch.tensor(upper, dtype=torch.float32)
|
|
394
|
+
center = ((lower + upper) / 2).unsqueeze(0)
|
|
395
|
+
lower = lower.unsqueeze(0)
|
|
396
|
+
upper = upper.unsqueeze(0)
|
|
397
|
+
perturb = PerturbationLpNorm(x_L=lower, x_U=upper)
|
|
398
|
+
bounded_inputs.append(BoundedTensor(center, perturb))
|
|
399
|
+
|
|
400
|
+
# Compute bounds for this sub-domain
|
|
401
|
+
lb, ub = lirpa_model.compute_bounds(
|
|
402
|
+
x=tuple(bounded_inputs),
|
|
403
|
+
method="CROWN"
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
# Update global bounds
|
|
407
|
+
lb, ub = lb.detach().numpy()[0], ub.detach().numpy()[0]
|
|
408
|
+
if global_lb is None:
|
|
409
|
+
global_lb = lb
|
|
410
|
+
global_ub = ub
|
|
411
|
+
else:
|
|
412
|
+
global_lb = np.minimum(global_lb, lb)
|
|
413
|
+
global_ub = np.maximum(global_ub, ub)
|
|
414
|
+
|
|
415
|
+
# with open(cache_file, 'wb') as f:
|
|
416
|
+
# pickle.dump((global_lb, global_ub), f)
|
|
417
|
+
|
|
418
|
+
return global_lb, global_ub
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
if __name__ == "__main__":
|
|
422
|
+
import numpy as np
|
|
423
|
+
|
|
424
|
+
def noisy_sensor(x, y, e_rho, e_theta):
|
|
425
|
+
rho = norm([x, y])
|
|
426
|
+
theta = atan2(y, x)
|
|
427
|
+
rho_p = rho + e_rho
|
|
428
|
+
theta_p = theta + e_theta
|
|
429
|
+
return rho_p * cos(theta_p), rho_p * sin(theta_p)
|
|
430
|
+
|
|
431
|
+
def prox_error_ver(x, y, z, ep_r, ep_ang):
|
|
432
|
+
rho = norm([x,y,z])
|
|
433
|
+
rho_plane = norm([x,y])
|
|
434
|
+
theta = atan2(y,x)
|
|
435
|
+
psi = atan2(z, rho_plane)
|
|
436
|
+
rho_p, theta_p, psi_p = rho+ep_r, theta+ep_ang, psi+ep_ang
|
|
437
|
+
nx, ny, nz = rho_p*cos(theta_p)*cos(psi_p), rho_p*sin(theta_p)*cos(psi_p), rho_p*sin(psi_p)
|
|
438
|
+
return x-nx, y-ny, z-nz, cos(x)**1.33
|
|
439
|
+
|
|
440
|
+
def cur_sense_relu(x, y, other_x, other_y, theta, phi):
|
|
441
|
+
"""
|
|
442
|
+
Convert conditional cur_sense logic to ReLU-based function
|
|
443
|
+
|
|
444
|
+
Args:
|
|
445
|
+
rel_x, rel_y: relative position to assigned agent
|
|
446
|
+
theta: ego agent heading
|
|
447
|
+
phi: sensor field of view half-angle
|
|
448
|
+
|
|
449
|
+
Returns:
|
|
450
|
+
cur_sense value: -2, -1, 1, or 2
|
|
451
|
+
"""
|
|
452
|
+
# Step 1: Compute psi = normalized relative angle
|
|
453
|
+
rel_x, rel_y = other_x - x, other_y-y
|
|
454
|
+
psi = ((atan2(rel_y, rel_x) - theta + np.pi) % (2*np.pi)) - np.pi
|
|
455
|
+
|
|
456
|
+
eps = 1e-6
|
|
457
|
+
|
|
458
|
+
out_left = torch.relu(psi-phi+eps) # > 0 for any region implies that the sensor will output that value
|
|
459
|
+
right = (torch.relu(psi+phi)*torch.relu(-psi+eps))
|
|
460
|
+
left = (torch.relu(psi)*torch.relu(phi-psi))
|
|
461
|
+
# region3 = (torch.relu(psi)*torch.relu(phi-psi))
|
|
462
|
+
out_right = torch.relu(-phi-psi+eps)
|
|
463
|
+
# Combine regions with their output values
|
|
464
|
+
# cur_sense = -region3
|
|
465
|
+
# cur_sense = rel_x*0
|
|
466
|
+
|
|
467
|
+
return out_left, left, right, out_right, psi # Return both for debugging/validation
|
|
468
|
+
|
|
469
|
+
def vis_sense_cont(x,y,other_x, other_y, theta, phi):
|
|
470
|
+
"""
|
|
471
|
+
Outputs continuous y, if 0<y<1, then right, y>1 out right, -1<y<0 left, y<-1 out left -- can do this DL
|
|
472
|
+
Issues with discontinuity around pi/-pi -- but note that y>>0 in this case, can try to handle separately
|
|
473
|
+
"""
|
|
474
|
+
rel_x, rel_y = other_x - x, other_y-y
|
|
475
|
+
# psi = ((atan2(rel_y, rel_x) - theta + np.pi) % (2*np.pi)) - np.pi
|
|
476
|
+
psi = atan2(rel_y, rel_x) - theta
|
|
477
|
+
return psi/phi
|
|
478
|
+
|
|
479
|
+
def atan2_test(x, y, other_x, other_y):
|
|
480
|
+
eps = 1e-6 # small number for numerical stability
|
|
481
|
+
|
|
482
|
+
rel_x, rel_y = other_x-x, other_y-y
|
|
483
|
+
abs_x = torch.abs(rel_x) #
|
|
484
|
+
y_adj = rel_y * torch.sign(rel_x + eps)
|
|
485
|
+
|
|
486
|
+
# Now compute arctan with guaranteed positive denominator
|
|
487
|
+
theta = torch.atan(y_adj / (abs_x+eps))
|
|
488
|
+
|
|
489
|
+
# Handle quadrants correctly
|
|
490
|
+
# x_neg = torch.relu(-rel_x) / (abs_x + eps) # ≈ 1 if x<0 else 0
|
|
491
|
+
x_neg = torch.sigmoid(-rel_x*100)
|
|
492
|
+
# y_neg = torch.relu(-rel_y) / (torch.abs(rel_y)+eps) # ≈ 1 if y<0 else 0
|
|
493
|
+
y_neg = torch.sigmoid(-rel_y*100)
|
|
494
|
+
|
|
495
|
+
# Quadrant corrections
|
|
496
|
+
correction = torch.pi * x_neg * (1 - 2*y_neg)
|
|
497
|
+
|
|
498
|
+
return theta+correction
|
|
499
|
+
|
|
500
|
+
def atan2_test_only(x,y):
|
|
501
|
+
return atan2(y, x)
|
|
502
|
+
# model = TorchFuncModule(noisy_sensor)
|
|
503
|
+
|
|
504
|
+
# inputs = np.array([1,1,0,0])
|
|
505
|
+
# out = parsed_sensor(noisy_sensor, inputs, sim=True)
|
|
506
|
+
# print(out)
|
|
507
|
+
|
|
508
|
+
start = time.perf_counter()
|
|
509
|
+
clear_sensor_cache()
|
|
510
|
+
|
|
511
|
+
# input_bounds = [(.95,1.05), (1,1), (0,0), (0,0)]
|
|
512
|
+
# input_bounds = np.array([[.95,1.05], [1,1], [0,0], [0,0], [0,0]])
|
|
513
|
+
# input_bounds = np.array([[-5,-3], [-2,-1], [0,0], [-0.01,0.01], [-1e-6,1e-6]])
|
|
514
|
+
# input_bounds = np.array([[-5,-3], [-2,-1], [0,0], [0,0], [0,0]])
|
|
515
|
+
# lb, ub = parsed_sensor(prox_error_ver, input_bounds=input_bounds, num_splits=2)
|
|
516
|
+
|
|
517
|
+
# input_bounds = np.array([[0, 0], [0,0], [-1,1], [1,1], [0,0], [1,1]]) # test out more combinations
|
|
518
|
+
# input_bounds = np.array([[0, 0], [0,0], [-10,-0.05], [1,1]]) #
|
|
519
|
+
# lb, ub = parsed_sensor(atan2_test, input_bounds=input_bounds, num_splits=4)
|
|
520
|
+
# lb, ub = parsed_sensor(cur_sense_relu, input_bounds=input_bounds, num_splits=3)
|
|
521
|
+
# lb, ub = parsed_sensor(vis_sense_cont, input_bounds=input_bounds, num_splits=3)
|
|
522
|
+
|
|
523
|
+
# input_bounds = np.array([[0, 0], [0,0], [-5, 5], [-2, 2], [0, 0], [1, 1]])
|
|
524
|
+
input_bounds = np.array([[-1,-1], [-1, 1]])
|
|
525
|
+
# input_bounds = np.array([[0,0], [0,0,], [0.001, 0.001], [1, 1]])
|
|
526
|
+
# lb, ub = parsed_sensor(atan2_test, input_bounds=input_bounds, num_splits=2)
|
|
527
|
+
lb, ub = parsed_sensor_with_atan2_partitioning(atan2_test_only, input_bounds=input_bounds, num_splits=2)
|
|
528
|
+
# lb, ub = parsed_sensor_with_atan2_partitioning(cur_sense_relu, input_bounds=input_bounds, num_splits=2)
|
|
529
|
+
|
|
530
|
+
print(lb, ub, f'Runtime: {time.perf_counter()-start:.2f} s')
|
|
531
|
+
exit()
|
|
532
|
+
|
|
533
|
+
x = torch.tensor([1.0])
|
|
534
|
+
y = torch.tensor([1.0])
|
|
535
|
+
# e_rho = torch.tensor([0.05])
|
|
536
|
+
# e_theta = torch.tensor([-0.02])
|
|
537
|
+
e_rho = e_theta = torch.zeros(1)
|
|
538
|
+
|
|
539
|
+
out = model(x, y, e_rho, e_theta)
|
|
540
|
+
# print(out) # (tensor(...), tensor(...))
|
|
541
|
+
|
|
542
|
+
dummy_x = torch.zeros(1, 1) # batch size 1, dim 2
|
|
543
|
+
dummy_y = torch.zeros(1, 1)
|
|
544
|
+
dummy_e_rho = torch.zeros(1, 1)
|
|
545
|
+
dummy_e_theta = torch.zeros(1, 1)
|
|
546
|
+
|
|
547
|
+
lirpa_model = BoundedModule(model, (dummy_x, dummy_y, dummy_e_rho, dummy_e_theta), device="cpu")
|
|
548
|
+
|
|
549
|
+
# Interval bounds for each input
|
|
550
|
+
xl, xu = x-0.05, x+0.05
|
|
551
|
+
yl, yu = y, y
|
|
552
|
+
e_rho_l, e_rho_u = e_rho, e_rho # example
|
|
553
|
+
e_theta_l, e_theta_u = e_theta, e_theta
|
|
554
|
+
|
|
555
|
+
# Compute centers with batch dim
|
|
556
|
+
x_center = ((xl + xu) / 2).unsqueeze(0) # shape (1,2)
|
|
557
|
+
y_center = ((yl + yu) / 2).unsqueeze(0)
|
|
558
|
+
e_rho_center = ((e_rho_l + e_rho_u) / 2).unsqueeze(0)
|
|
559
|
+
e_theta_center = ((e_theta_l + e_theta_u) / 2).unsqueeze(0)
|
|
560
|
+
|
|
561
|
+
# Perturbations
|
|
562
|
+
x_perturb = PerturbationLpNorm(x_L=xl.unsqueeze(0), x_U=xu.unsqueeze(0))
|
|
563
|
+
y_perturb = PerturbationLpNorm(x_L=yl.unsqueeze(0), x_U=yu.unsqueeze(0))
|
|
564
|
+
e_rho_perturb = PerturbationLpNorm(x_L=e_rho_l.unsqueeze(0), x_U=e_rho_u.unsqueeze(0))
|
|
565
|
+
e_theta_perturb = PerturbationLpNorm(x_L=e_theta_l.unsqueeze(0), x_U=e_theta_u.unsqueeze(0))
|
|
566
|
+
|
|
567
|
+
# Bounded tensors
|
|
568
|
+
x_bounded = BoundedTensor(x_center, x_perturb)
|
|
569
|
+
y_bounded = BoundedTensor(y_center, y_perturb)
|
|
570
|
+
e_rho_bounded = BoundedTensor(e_rho_center, e_rho_perturb)
|
|
571
|
+
e_theta_bounded = BoundedTensor(e_theta_center, e_theta_perturb)
|
|
572
|
+
|
|
573
|
+
# Compute bounds
|
|
574
|
+
lb, ub = lirpa_model.compute_bounds(
|
|
575
|
+
x=(x_bounded, y_bounded, e_rho_bounded, e_theta_bounded),
|
|
576
|
+
method="CROWN" # or "CROWN"
|
|
577
|
+
)
|
|
578
|
+
print(lb, ub) # note that after some course testing, this seems to be a valid overapproximation -- though do note it's pretty coarse
|
|
579
|
+
|
|
580
|
+
# note that what box_extreme_error is trying to do is find bounds on the error, not the estimate itself, so need to change function before doing this again
|
|
581
|
+
# x_bounds_opt, y_bounds_opt = box_extreme_error([(x.item()-0.1, x.item()+0.1), (y.item(), y.item()), (0,0)], 0, 0, 'x'), box_extreme_error([(x.item()-0.1, x.item()+0.1), (y.item(), y.item()), (0,0)], 0, 0, 'y')
|
|
582
|
+
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from typing import List, Dict, Callable
|
|
2
|
+
from .bounded_angular import angular_span_rect_parser, angular_bounds_diff_correct
|
|
3
|
+
from .bounded_map import get_heading_bounds_optimized, get_lateral_distance_bounds_optimized
|
|
4
|
+
|
|
5
|
+
ALIASES = {
|
|
6
|
+
"atan2": "angular_span_rect_parser",
|
|
7
|
+
"arctan2": "angular_span_rect_parser",
|
|
8
|
+
"get_lane_heading": "get_heading_bounds_optimized",
|
|
9
|
+
"get_lateral_distance": "get_lateral_distance_bounds_optimized",
|
|
10
|
+
"minus_angular": "angular_bounds_diff_correct"
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
ANGULAR_FUNCTIONS = [
|
|
14
|
+
"angular_span_rect_parser", "angular_bounds_diff_correct"
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
MAP_FUNCTIONS: List[str] = [
|
|
18
|
+
# NOTE: in parser_wrapper, assume that lane_idx and lane_map are constants passed in -- the first two arguments of these two functions should just be given
|
|
19
|
+
"get_heading_bounds_optimized",
|
|
20
|
+
"get_lateral_distance_bounds_optimized",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
# NOTE: don't know if I need this, but it could be useful if I don't want to keep using the
|
|
24
|
+
FUNC_DICT: Dict[str, Callable] = {
|
|
25
|
+
"angular_span_rect_parser": angular_span_rect_parser,
|
|
26
|
+
"get_heading_bounds_optimized": get_heading_bounds_optimized,
|
|
27
|
+
"get_lateral_distance_bounds_optimized": get_lateral_distance_bounds_optimized,
|
|
28
|
+
"angular_bounds_diff_correct": angular_bounds_diff_correct,
|
|
29
|
+
}
|