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,402 @@
|
|
|
1
|
+
from collections import defaultdict
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from pprint import pp
|
|
4
|
+
from typing import Any, DefaultDict, List, Tuple, Optional, Dict, Set
|
|
5
|
+
from verse.agents.base_agent import BaseAgent
|
|
6
|
+
from verse.analysis import AnalysisTreeNode
|
|
7
|
+
from intervaltree import IntervalTree
|
|
8
|
+
import itertools, copy, numpy.typing as nptyp, numpy as np
|
|
9
|
+
|
|
10
|
+
from verse.analysis.dryvr import _EPSILON
|
|
11
|
+
|
|
12
|
+
# from verse.analysis.simulator import PathDiffs
|
|
13
|
+
from verse.parser.parser import ControllerIR, ModePath
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class CachedTransition:
|
|
18
|
+
inits: Dict[str, List[float]]
|
|
19
|
+
transition: int
|
|
20
|
+
disc: List[str]
|
|
21
|
+
cont: List[float]
|
|
22
|
+
paths: List[ModePath]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class CachedSegment:
|
|
27
|
+
trace: nptyp.NDArray[np.double]
|
|
28
|
+
asserts: List[str]
|
|
29
|
+
transitions: List[CachedTransition]
|
|
30
|
+
node_ids: Set[Tuple[int, int]]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class CachedReachTrans:
|
|
35
|
+
inits: Dict[str, List[float]]
|
|
36
|
+
transition: int
|
|
37
|
+
mode: List[str]
|
|
38
|
+
dest: List[float]
|
|
39
|
+
reset: List[float]
|
|
40
|
+
reset_idx: List[int]
|
|
41
|
+
paths: List[ModePath]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class CachedRTTrans:
|
|
46
|
+
asserts: List[str]
|
|
47
|
+
transitions: List[CachedReachTrans]
|
|
48
|
+
node_ids: Set[Tuple[int, int]] # run_num, node_id
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def to_simulate(
|
|
52
|
+
old_agents: Dict[str, BaseAgent],
|
|
53
|
+
new_agents: Dict[str, BaseAgent],
|
|
54
|
+
cached: Dict[str, CachedSegment],
|
|
55
|
+
) -> Tuple[Dict[str, CachedSegment], Any]: # s/Any/PathDiffs/
|
|
56
|
+
assert set(old_agents.keys()) == set(new_agents.keys())
|
|
57
|
+
new_cache = {}
|
|
58
|
+
total_added_paths = []
|
|
59
|
+
for agent_id, segment in cached.items():
|
|
60
|
+
if not segment.transitions:
|
|
61
|
+
new_cache[agent_id] = segment
|
|
62
|
+
continue
|
|
63
|
+
segment = copy.deepcopy(segment)
|
|
64
|
+
removed_paths, added_paths, reset_changed_paths = [], [], []
|
|
65
|
+
old_agent, new_agent = old_agents[agent_id], new_agents[agent_id]
|
|
66
|
+
old_ctlr, new_ctlr = old_agent.decision_logic, new_agent.decision_logic
|
|
67
|
+
assert old_ctlr.args == new_ctlr.args
|
|
68
|
+
|
|
69
|
+
def group_by_var(ctlr: ControllerIR) -> Dict[str, List[ModePath]]:
|
|
70
|
+
grouped = defaultdict(list)
|
|
71
|
+
for path in ctlr.paths:
|
|
72
|
+
grouped[path.var].append(path)
|
|
73
|
+
return dict(grouped)
|
|
74
|
+
|
|
75
|
+
old_grouped, new_grouped = group_by_var(old_ctlr), group_by_var(new_ctlr)
|
|
76
|
+
if set(old_grouped.keys()) != set(new_grouped.keys()):
|
|
77
|
+
raise NotImplementedError("different variable outputs")
|
|
78
|
+
for var, old_paths in old_grouped.items():
|
|
79
|
+
new_paths = new_grouped[var]
|
|
80
|
+
for i, (old, new) in enumerate(itertools.zip_longest(old_paths, new_paths)):
|
|
81
|
+
if new == None:
|
|
82
|
+
removed_paths.append(old)
|
|
83
|
+
elif not ControllerIR.ir_eq(old.cond_veri, new.cond_veri):
|
|
84
|
+
removed_paths.append(old)
|
|
85
|
+
added_paths.append(new)
|
|
86
|
+
elif not ControllerIR.ir_eq(old.val_veri, new.val_veri):
|
|
87
|
+
reset_changed_paths.append(new)
|
|
88
|
+
removed = False
|
|
89
|
+
for trans in segment.transitions:
|
|
90
|
+
for path in trans.paths:
|
|
91
|
+
removed = removed or (path in removed_paths)
|
|
92
|
+
for rcp in reset_changed_paths:
|
|
93
|
+
if path.cond == rcp.cond:
|
|
94
|
+
path.val = rcp.val
|
|
95
|
+
if not removed:
|
|
96
|
+
new_cache[agent_id] = segment
|
|
97
|
+
total_added_paths.extend((new_agent, p) for p in added_paths)
|
|
98
|
+
return new_cache, total_added_paths
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def convert_sim_trans(agent_id, transit_agents, inits, transition, trans_ind):
|
|
102
|
+
if agent_id in transit_agents:
|
|
103
|
+
return [
|
|
104
|
+
CachedTransition(
|
|
105
|
+
{k: list(v) for k, v in inits.items()}, trans_ind, mode, list(init), paths
|
|
106
|
+
)
|
|
107
|
+
for _id, mode, init, paths in transition
|
|
108
|
+
]
|
|
109
|
+
else:
|
|
110
|
+
return []
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def convert_reach_trans(agent_id, transit_agents, inits, transition, trans_ind):
|
|
114
|
+
if agent_id in transit_agents:
|
|
115
|
+
return [
|
|
116
|
+
CachedReachTrans(inits, trans_ind, mode, dest, reset, reset_idx, paths)
|
|
117
|
+
for _id, mode, dest, reset, reset_idx, paths in transition
|
|
118
|
+
]
|
|
119
|
+
else:
|
|
120
|
+
return []
|
|
121
|
+
|
|
122
|
+
def combine_all(inits, stars=False):
|
|
123
|
+
if stars:
|
|
124
|
+
from verse.stars.starset import StarSet
|
|
125
|
+
#breakpoint()
|
|
126
|
+
while type(inits[0]) == list:
|
|
127
|
+
#KB : todo: fix this weird workaround
|
|
128
|
+
inits = inits[0]
|
|
129
|
+
return StarSet.combine_stars(inits)
|
|
130
|
+
return [
|
|
131
|
+
[min(a) for a in np.transpose(np.array(inits)[:, 0])],
|
|
132
|
+
[max(a) for a in np.transpose(np.array(inits)[:, 1])],
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def sim_trans_suit(a: Dict[str, List[float]], b: Dict[str, List[float]]) -> bool:
|
|
137
|
+
assert set(a.keys()) == set(b.keys())
|
|
138
|
+
return all(abs(av - bv) < _EPSILON for aid in a.keys() for av, bv in zip(a[aid], b[aid]))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def reach_trans_suit(
|
|
142
|
+
a: Dict[str, List[List[List[float]]]], b: Dict[str, List[List[List[float]]]]
|
|
143
|
+
) -> bool:
|
|
144
|
+
# FIXME include discrete stuff
|
|
145
|
+
assert set(a.keys()) == set(b.keys())
|
|
146
|
+
|
|
147
|
+
def transp(a):
|
|
148
|
+
return list(map(list, zip(*a)))
|
|
149
|
+
|
|
150
|
+
def suits(a: List[List[float]], b: List[List[float]]) -> bool:
|
|
151
|
+
at, bt = transp(a), transp(b)
|
|
152
|
+
return all(al <= bl and ah >= bh for (al, ah), (bl, bh) in zip(at, bt))
|
|
153
|
+
|
|
154
|
+
return all(suits(av, bv) for aid in a.keys() for av, bv in zip(a[aid], b[aid]))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass
|
|
158
|
+
class CachedTube:
|
|
159
|
+
tube: List[List[List[float]]]
|
|
160
|
+
|
|
161
|
+
def __eq__(self, other) -> bool:
|
|
162
|
+
if other is None:
|
|
163
|
+
return False
|
|
164
|
+
return (self.tube == other.tube).all()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class SimTraceCache:
|
|
168
|
+
def __init__(self):
|
|
169
|
+
self.cache: DefaultDict[tuple, IntervalTree] = defaultdict(IntervalTree)
|
|
170
|
+
|
|
171
|
+
def add_segment(
|
|
172
|
+
self,
|
|
173
|
+
agent_id: str,
|
|
174
|
+
node: AnalysisTreeNode,
|
|
175
|
+
transit_agents: List[str],
|
|
176
|
+
trace: nptyp.NDArray[np.double],
|
|
177
|
+
transition,
|
|
178
|
+
trans_ind: int,
|
|
179
|
+
run_num: int,
|
|
180
|
+
):
|
|
181
|
+
key = (agent_id,) + tuple(node.mode[agent_id])
|
|
182
|
+
init = node.init[agent_id]
|
|
183
|
+
tree = self.cache[key]
|
|
184
|
+
assert_hits = node.assert_hits or {}
|
|
185
|
+
# pp(('add seg', agent_id, *node.mode[agent_id], *init))
|
|
186
|
+
for i, val in enumerate(init):
|
|
187
|
+
if i == len(init) - 1:
|
|
188
|
+
transitions = convert_sim_trans(
|
|
189
|
+
agent_id, transit_agents, node.init, transition, trans_ind
|
|
190
|
+
)
|
|
191
|
+
entry = CachedSegment(
|
|
192
|
+
trace, assert_hits.get(agent_id), transitions, set([(run_num, node.id)])
|
|
193
|
+
)
|
|
194
|
+
tree[val - _EPSILON : val + _EPSILON] = entry
|
|
195
|
+
return entry
|
|
196
|
+
else:
|
|
197
|
+
next_level_tree = IntervalTree()
|
|
198
|
+
tree[val - _EPSILON : val + _EPSILON] = next_level_tree
|
|
199
|
+
tree = next_level_tree
|
|
200
|
+
raise Exception("???")
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def iter_tree(tree, depth: int) -> List[List[float]]:
|
|
204
|
+
if depth == 0:
|
|
205
|
+
return [
|
|
206
|
+
[
|
|
207
|
+
(i.begin + i.end) / 2,
|
|
208
|
+
(
|
|
209
|
+
i.data.node_ids,
|
|
210
|
+
[t.transition for t in i.data.transitions],
|
|
211
|
+
len(i.data.trace),
|
|
212
|
+
),
|
|
213
|
+
]
|
|
214
|
+
for i in tree
|
|
215
|
+
]
|
|
216
|
+
res = []
|
|
217
|
+
for i in tree:
|
|
218
|
+
mid = (i.begin + i.end) / 2
|
|
219
|
+
subs = SimTraceCache.iter_tree(i.data, depth - 1)
|
|
220
|
+
res.extend([mid] + sub for sub in subs)
|
|
221
|
+
return res
|
|
222
|
+
|
|
223
|
+
def get_cached_inits(self, n: int):
|
|
224
|
+
inits = defaultdict(list)
|
|
225
|
+
for key, tree in self.cache.items():
|
|
226
|
+
inits[key[0]].extend((*key[1:], *init) for init in self.iter_tree(tree, n))
|
|
227
|
+
inits = {k: sorted(v) for k, v in inits.items()}
|
|
228
|
+
return inits
|
|
229
|
+
|
|
230
|
+
@staticmethod
|
|
231
|
+
def query_cont(tree: IntervalTree, cont: List[float]) -> List[CachedSegment]:
|
|
232
|
+
assert isinstance(tree, IntervalTree)
|
|
233
|
+
next_level_entries = [t.data for t in tree[cont[0]]]
|
|
234
|
+
if len(cont) == 1:
|
|
235
|
+
for ent in next_level_entries:
|
|
236
|
+
assert isinstance(ent, CachedSegment)
|
|
237
|
+
return next_level_entries
|
|
238
|
+
else:
|
|
239
|
+
return [
|
|
240
|
+
ent for t in next_level_entries for ent in SimTraceCache.query_cont(t, cont[1:])
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
def check_hit(
|
|
244
|
+
self, agent_id: str, mode: Tuple[str], init: List[float], inits: Dict[str, List[float]]
|
|
245
|
+
) -> Optional[CachedSegment]:
|
|
246
|
+
key = (agent_id,) + tuple(mode)
|
|
247
|
+
if key not in self.cache:
|
|
248
|
+
return None
|
|
249
|
+
tree = self.cache[key]
|
|
250
|
+
entries = self.query_cont(tree, init)
|
|
251
|
+
if len(entries) == 0:
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
def num_trans_suit(e: CachedSegment) -> int:
|
|
255
|
+
return sum(1 if sim_trans_suit(t.inits, inits) else 0 for t in e.transitions)
|
|
256
|
+
|
|
257
|
+
entries = list(sorted([(e, -num_trans_suit(e)) for e in entries], key=lambda p: p[1]))
|
|
258
|
+
# pp(("check hit entries", len(entries), entries[0][1]))
|
|
259
|
+
assert isinstance(entries[0][0], (type(None), CachedSegment))
|
|
260
|
+
return entries[0][0]
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class TubeCache:
|
|
264
|
+
def __init__(self):
|
|
265
|
+
self.cache: DefaultDict[tuple, IntervalTree] = defaultdict(IntervalTree)
|
|
266
|
+
|
|
267
|
+
def add_tube(
|
|
268
|
+
self,
|
|
269
|
+
agent_id: str,
|
|
270
|
+
mode: Tuple[str],
|
|
271
|
+
init: List[List[float]],
|
|
272
|
+
trace: List[List[List[float]]],
|
|
273
|
+
):
|
|
274
|
+
key = (agent_id,) + tuple(mode)
|
|
275
|
+
init = list(map(list, zip(*init)))
|
|
276
|
+
tree = self.cache[key]
|
|
277
|
+
for i, (low, high) in enumerate(init):
|
|
278
|
+
if i == len(init) - 1:
|
|
279
|
+
entry = CachedTube(trace)
|
|
280
|
+
tree[low : high + _EPSILON] = entry
|
|
281
|
+
return entry
|
|
282
|
+
else:
|
|
283
|
+
next_level_tree = IntervalTree()
|
|
284
|
+
tree[low : high + _EPSILON] = next_level_tree
|
|
285
|
+
tree = next_level_tree
|
|
286
|
+
raise Exception("???")
|
|
287
|
+
|
|
288
|
+
def check_hit(
|
|
289
|
+
self, agent_id: str, mode: Tuple[str], init: List[List[float]]
|
|
290
|
+
) -> Optional[CachedTube]:
|
|
291
|
+
key = (agent_id,) + tuple(mode)
|
|
292
|
+
if key not in self.cache:
|
|
293
|
+
return None
|
|
294
|
+
tree = self.cache[key]
|
|
295
|
+
for low, high in list(map(list, zip(*init))):
|
|
296
|
+
next_level_entries = [
|
|
297
|
+
t for t in tree[low : high + _EPSILON] if t.begin <= low and high <= t.end
|
|
298
|
+
]
|
|
299
|
+
if len(next_level_entries) == 0:
|
|
300
|
+
return None
|
|
301
|
+
tree = min(next_level_entries, key=lambda e: low - e.begin + e.end - high).data
|
|
302
|
+
assert isinstance(tree, CachedTube)
|
|
303
|
+
return tree
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class ReachTubeCache:
|
|
307
|
+
def __init__(self):
|
|
308
|
+
self.cache: DefaultDict[tuple, IntervalTree] = defaultdict(IntervalTree)
|
|
309
|
+
|
|
310
|
+
def add_tube(
|
|
311
|
+
self,
|
|
312
|
+
agent_id: str,
|
|
313
|
+
init: Dict[str, List[List[float]]],
|
|
314
|
+
node: AnalysisTreeNode,
|
|
315
|
+
transit_agents: List[str],
|
|
316
|
+
transition,
|
|
317
|
+
trans_ind: int,
|
|
318
|
+
run_num: int,
|
|
319
|
+
):
|
|
320
|
+
key = (agent_id,) + tuple(node.mode[agent_id])
|
|
321
|
+
tree = self.cache[key]
|
|
322
|
+
# pp(('add seg', agent_id, node.mode[agent_id], init))
|
|
323
|
+
assert_hits = node.assert_hits or {}
|
|
324
|
+
init = list(map(tuple, zip(*init[agent_id])))
|
|
325
|
+
for i, (low, high) in enumerate(init):
|
|
326
|
+
if i == len(init) - 1:
|
|
327
|
+
transitions = convert_reach_trans(
|
|
328
|
+
agent_id, transit_agents, node.init, transition, trans_ind
|
|
329
|
+
)
|
|
330
|
+
entry = CachedRTTrans(
|
|
331
|
+
assert_hits.get(agent_id), transitions, set([(run_num, node.id)])
|
|
332
|
+
)
|
|
333
|
+
tree[low : high + _EPSILON] = entry
|
|
334
|
+
return entry
|
|
335
|
+
else:
|
|
336
|
+
next_level_tree = IntervalTree()
|
|
337
|
+
tree[low : high + _EPSILON] = next_level_tree
|
|
338
|
+
tree = next_level_tree
|
|
339
|
+
raise Exception("???")
|
|
340
|
+
|
|
341
|
+
@staticmethod
|
|
342
|
+
def query_cont(tree: IntervalTree, cont: List[Tuple[float, float]]) -> List[CachedRTTrans]:
|
|
343
|
+
assert isinstance(tree, IntervalTree)
|
|
344
|
+
low, high = cont[0]
|
|
345
|
+
next_level_entries = [
|
|
346
|
+
t.data for t in tree[low : high + _EPSILON] if t.begin <= low and high <= t.end
|
|
347
|
+
]
|
|
348
|
+
if len(cont) == 1:
|
|
349
|
+
for ent in next_level_entries:
|
|
350
|
+
assert isinstance(ent, CachedRTTrans)
|
|
351
|
+
return next_level_entries
|
|
352
|
+
else:
|
|
353
|
+
return [
|
|
354
|
+
ent for t in next_level_entries for ent in ReachTubeCache.query_cont(t, cont[1:])
|
|
355
|
+
]
|
|
356
|
+
|
|
357
|
+
def check_hit(
|
|
358
|
+
self,
|
|
359
|
+
agent_id: str,
|
|
360
|
+
mode: Tuple[str],
|
|
361
|
+
init: List[float],
|
|
362
|
+
inits: Dict[str, List[List[List[float]]]],
|
|
363
|
+
) -> Optional[CachedRTTrans]:
|
|
364
|
+
key = (agent_id,) + tuple(mode)
|
|
365
|
+
if key not in self.cache:
|
|
366
|
+
return None
|
|
367
|
+
tree = self.cache[key]
|
|
368
|
+
entries = self.query_cont(tree, list(map(tuple, zip(*init))))
|
|
369
|
+
if len(entries) == 0:
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
def num_trans_suit(e: CachedRTTrans) -> int:
|
|
373
|
+
return sum(1 if reach_trans_suit(t.inits, inits) else 0 for t in e.transitions)
|
|
374
|
+
|
|
375
|
+
entries = list(sorted([(e, -num_trans_suit(e)) for e in entries], key=lambda p: p[1]))
|
|
376
|
+
# pp(("check hit entries", len(entries), entries[0][1]))
|
|
377
|
+
assert isinstance(entries[0][0], CachedRTTrans)
|
|
378
|
+
return entries[0][0]
|
|
379
|
+
|
|
380
|
+
@staticmethod
|
|
381
|
+
def iter_tree(tree, depth: int) -> List[List[float]]:
|
|
382
|
+
if depth == 0:
|
|
383
|
+
return [
|
|
384
|
+
[
|
|
385
|
+
(i.begin + i.end) / 2,
|
|
386
|
+
(i.data.run_num, i.data.node_id, [t.transition for t in i.data.transitions]),
|
|
387
|
+
]
|
|
388
|
+
for i in tree
|
|
389
|
+
]
|
|
390
|
+
res = []
|
|
391
|
+
for i in tree:
|
|
392
|
+
mid = (i.begin + i.end) / 2
|
|
393
|
+
subs = ReachTubeCache.iter_tree(i.data, depth - 1)
|
|
394
|
+
res.extend([mid] + sub for sub in subs)
|
|
395
|
+
return res
|
|
396
|
+
|
|
397
|
+
def get_cached_inits(self, n: int):
|
|
398
|
+
inits = defaultdict(list)
|
|
399
|
+
for key, tree in self.cache.items():
|
|
400
|
+
inits[key[0]].extend((*key[1:], *init) for init in self.iter_tree(tree, n))
|
|
401
|
+
inits = dict(inits)
|
|
402
|
+
return inits
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.optimize import minimize
|
|
3
|
+
import inspect, ast, textwrap, inspect, astunparse
|
|
4
|
+
import warnings
|
|
5
|
+
from sympy import Symbol, diff
|
|
6
|
+
from sympy.utilities.lambdify import lambdify
|
|
7
|
+
from sympy.core import *
|
|
8
|
+
|
|
9
|
+
from scipy.integrate import ode
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def find_min(expr_func, jac_func, var_range, num_var, args, idx):
|
|
13
|
+
bounds = []
|
|
14
|
+
x0 = []
|
|
15
|
+
for i in range(var_range.shape[1]):
|
|
16
|
+
bounds.append((var_range[0, i], var_range[1, i]))
|
|
17
|
+
x0.append(var_range[0, i])
|
|
18
|
+
# print(expr_func(x0, args, idx))
|
|
19
|
+
# print(jac_func(x0, args, idx).shape)
|
|
20
|
+
res = minimize(
|
|
21
|
+
expr_func, x0, args=(num_var, args, idx), bounds=bounds, jac=jac_func, method="L-BFGS-B"
|
|
22
|
+
)
|
|
23
|
+
# print(res)
|
|
24
|
+
return res.fun
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def find_max(expr_func, jac_func, var_range, num_var, args, idx):
|
|
28
|
+
neg_expr_func = lambda x, num_var, args, idx: -expr_func(x, num_var, args, idx)
|
|
29
|
+
neg_jac_func = lambda x, num_var, args, idx: -jac_func(x, num_var, args, idx)
|
|
30
|
+
res = find_min(neg_expr_func, neg_jac_func, var_range, num_var, args, idx)
|
|
31
|
+
return -res
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def find_min_symbolic(expr, var_range):
|
|
35
|
+
bounds = []
|
|
36
|
+
vars = list(expr.free_symbols)
|
|
37
|
+
x0 = []
|
|
38
|
+
jac = []
|
|
39
|
+
for var in vars:
|
|
40
|
+
bounds.append(var_range[var])
|
|
41
|
+
x0.append(var_range[var][0])
|
|
42
|
+
jac.append(diff(expr, var))
|
|
43
|
+
expr_func = lambdify([vars], expr)
|
|
44
|
+
jac_func = lambdify([vars], jac)
|
|
45
|
+
res = minimize(expr_func, x0, bounds=bounds, jac=jac_func, method="L-BFGS-B")
|
|
46
|
+
return res.fun
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def find_max_symbolic(expr, var_range):
|
|
50
|
+
tmp = -expr
|
|
51
|
+
res = find_min_symbolic(tmp, var_range)
|
|
52
|
+
return -res
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def compute_reachtube_mixmono_disc(
|
|
56
|
+
initial_set, uncertain_var_bound, time_horizon, time_step, decomposition
|
|
57
|
+
):
|
|
58
|
+
initial_set = initial_set[0]
|
|
59
|
+
number_points = int(np.ceil(time_horizon / time_step))
|
|
60
|
+
t = [round(i * time_step, 10) for i in range(0, number_points)]
|
|
61
|
+
trace = [[0] + initial_set[0] + initial_set[1]]
|
|
62
|
+
num_var = len(initial_set[0])
|
|
63
|
+
for i in range(len(t)):
|
|
64
|
+
xk = trace[-1]
|
|
65
|
+
x = xk[1 : 1 + num_var]
|
|
66
|
+
xhat = xk[1 + num_var :]
|
|
67
|
+
w = uncertain_var_bound[0]
|
|
68
|
+
what = uncertain_var_bound[1]
|
|
69
|
+
d = decomposition(x, w, xhat, what, time_step)
|
|
70
|
+
dhat = decomposition(xhat, what, x, w, time_step)
|
|
71
|
+
trace.append([round(t[i] + time_step, 10)] + d + dhat)
|
|
72
|
+
|
|
73
|
+
res = []
|
|
74
|
+
for i in range(len(trace) - 1):
|
|
75
|
+
res0 = [trace[i][0]] + np.minimum.reduce(
|
|
76
|
+
[
|
|
77
|
+
trace[i][1 : 1 + num_var],
|
|
78
|
+
trace[i + 1][1 : 1 + num_var],
|
|
79
|
+
trace[i][1 + num_var :],
|
|
80
|
+
trace[i + 1][1 + num_var :],
|
|
81
|
+
]
|
|
82
|
+
).tolist()
|
|
83
|
+
res.append(res0)
|
|
84
|
+
res1 = [trace[i + 1][0]] + np.maximum.reduce(
|
|
85
|
+
[
|
|
86
|
+
trace[i][1 : 1 + num_var],
|
|
87
|
+
trace[i + 1][1 : 1 + num_var],
|
|
88
|
+
trace[i][1 + num_var :],
|
|
89
|
+
trace[i + 1][1 + num_var :],
|
|
90
|
+
]
|
|
91
|
+
).tolist()
|
|
92
|
+
res.append(res1)
|
|
93
|
+
return res
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def compute_reachtube_mixmono_cont(
|
|
97
|
+
initial_set, uncertain_var_bound, time_horizon, time_step, decomposition
|
|
98
|
+
):
|
|
99
|
+
initial_set = initial_set[0]
|
|
100
|
+
num_var = len(initial_set[0])
|
|
101
|
+
num_uncertain_var = len(uncertain_var_bound[0])
|
|
102
|
+
|
|
103
|
+
def decomposition_dynamics(t, state, u):
|
|
104
|
+
x, xhat = state[:num_var], state[num_var:]
|
|
105
|
+
w, what = u[:num_uncertain_var], u[num_uncertain_var:]
|
|
106
|
+
|
|
107
|
+
d = decomposition(x, w, xhat, what)
|
|
108
|
+
dhat = decomposition(xhat, what, x, w)
|
|
109
|
+
|
|
110
|
+
return np.concatenate((d, dhat))
|
|
111
|
+
|
|
112
|
+
time_bound = float(time_horizon)
|
|
113
|
+
number_points = int(np.ceil(time_bound / time_step))
|
|
114
|
+
t = [round(i * time_step, 10) for i in range(0, number_points)]
|
|
115
|
+
init = initial_set[0] + initial_set[1]
|
|
116
|
+
uncertain = uncertain_var_bound[0] + uncertain_var_bound[1]
|
|
117
|
+
trace = [[0] + init]
|
|
118
|
+
r = (
|
|
119
|
+
ode(decomposition_dynamics)
|
|
120
|
+
.set_integrator("dopri5", nsteps=2000)
|
|
121
|
+
.set_initial_value(init)
|
|
122
|
+
.set_f_params(uncertain)
|
|
123
|
+
)
|
|
124
|
+
for i in range(len(t)):
|
|
125
|
+
res: np.ndarray = r.integrate(r.t + time_step)
|
|
126
|
+
res = res.flatten().tolist()
|
|
127
|
+
trace.append([t[i] + time_step] + res)
|
|
128
|
+
|
|
129
|
+
res = []
|
|
130
|
+
for i in range(len(trace) - 1):
|
|
131
|
+
res0 = [trace[i][0]] + np.minimum.reduce(
|
|
132
|
+
[
|
|
133
|
+
trace[i][1 : 1 + num_var],
|
|
134
|
+
trace[i + 1][1 : 1 + num_var],
|
|
135
|
+
trace[i][1 + num_var :],
|
|
136
|
+
trace[i + 1][1 + num_var :],
|
|
137
|
+
]
|
|
138
|
+
).tolist()
|
|
139
|
+
res.append(res0)
|
|
140
|
+
res1 = [trace[i + 1][0]] + np.maximum.reduce(
|
|
141
|
+
[
|
|
142
|
+
trace[i][1 : 1 + num_var],
|
|
143
|
+
trace[i + 1][1 : 1 + num_var],
|
|
144
|
+
trace[i][1 + num_var :],
|
|
145
|
+
trace[i + 1][1 + num_var :],
|
|
146
|
+
]
|
|
147
|
+
).tolist()
|
|
148
|
+
res.append(res1)
|
|
149
|
+
return res
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def calculate_bloated_tube_mixmono_cont(
|
|
153
|
+
mode, init, uncertain_param, time_horizon, time_step, agent, lane_map
|
|
154
|
+
):
|
|
155
|
+
if hasattr(agent, "dynamics") and hasattr(agent, "decomposition"):
|
|
156
|
+
decomposition = agent.decomposition
|
|
157
|
+
res = compute_reachtube_mixmono_cont(
|
|
158
|
+
init, uncertain_param, time_horizon, time_step, decomposition
|
|
159
|
+
)
|
|
160
|
+
else:
|
|
161
|
+
raise ValueError("Not enough information to apply discrete time mixed monotone algorithm.")
|
|
162
|
+
return res
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def calculate_bloated_tube_mixmono_disc(
|
|
166
|
+
mode, init, uncertain_param, time_horizon, time_step, agent, lane_map
|
|
167
|
+
):
|
|
168
|
+
if hasattr(agent, "dynamics") and hasattr(agent, "decomposition"):
|
|
169
|
+
decomposition = agent.decomposition
|
|
170
|
+
res = compute_reachtube_mixmono_disc(
|
|
171
|
+
init, uncertain_param, time_horizon, time_step, decomposition
|
|
172
|
+
)
|
|
173
|
+
elif hasattr(agent, "dynamics") and hasattr(agent, "dynamics_jac"):
|
|
174
|
+
|
|
175
|
+
def decomposition_func(x, w, xhat, what, dt):
|
|
176
|
+
expr_func = lambda x, num_var, args, idx: agent.dynamics(
|
|
177
|
+
list(x[:num_var]), list(x[num_var:]) + args
|
|
178
|
+
)[idx]
|
|
179
|
+
jac_func = lambda x, num_var, args, idx: agent.dynamics_jac(
|
|
180
|
+
list(x[:num_var]), list(x[num_var:]) + args
|
|
181
|
+
)[idx, :]
|
|
182
|
+
|
|
183
|
+
assert len(x) == len(xhat)
|
|
184
|
+
assert len(w) == len(what)
|
|
185
|
+
|
|
186
|
+
d = []
|
|
187
|
+
num_var = len(x)
|
|
188
|
+
args = [dt]
|
|
189
|
+
if all(a <= b for a, b in zip(x, xhat)) and all(a <= b for a, b in zip(w, what)):
|
|
190
|
+
var_range = np.array([x + w, xhat + what])
|
|
191
|
+
for i in range(len(x)):
|
|
192
|
+
val = find_min(expr_func, jac_func, var_range, num_var, args, i)
|
|
193
|
+
d.append(val)
|
|
194
|
+
elif all(b <= a for a, b in zip(x, xhat)) and all(b <= a for a, b in zip(w, what)):
|
|
195
|
+
var_range = np.array([xhat + what, x + w])
|
|
196
|
+
for i in range(len(x)):
|
|
197
|
+
val = find_max(expr_func, jac_func, var_range, num_var, args, i)
|
|
198
|
+
d.append(val)
|
|
199
|
+
else:
|
|
200
|
+
raise ValueError(
|
|
201
|
+
f"Condition for x, w, x_hat, w_hat not satisfied: {[x, w, xhat, what]}"
|
|
202
|
+
)
|
|
203
|
+
return d
|
|
204
|
+
|
|
205
|
+
res = compute_reachtube_mixmono_disc(
|
|
206
|
+
init, uncertain_param, time_horizon, time_step, decomposition_func
|
|
207
|
+
)
|
|
208
|
+
elif hasattr(agent, "dynamics"):
|
|
209
|
+
dynamics_func = agent.dynamics
|
|
210
|
+
lines = inspect.getsource(dynamics_func)
|
|
211
|
+
function_body = ast.parse(textwrap.dedent(lines)).body[0].body
|
|
212
|
+
if not isinstance(function_body, list):
|
|
213
|
+
raise ValueError(f"Failed to extract dynamics for {agent}")
|
|
214
|
+
|
|
215
|
+
text_exprs = []
|
|
216
|
+
extract = False
|
|
217
|
+
x_var = []
|
|
218
|
+
w_var = []
|
|
219
|
+
for i, elem in enumerate(function_body):
|
|
220
|
+
if isinstance(elem, ast.Expr):
|
|
221
|
+
if isinstance(elem.value, ast.Constant) and elem.value.value == "Begin Dynamic":
|
|
222
|
+
extract = True
|
|
223
|
+
elif isinstance(elem, ast.Expr):
|
|
224
|
+
if isinstance(elem.value, ast.Constant) and elem.value.value == "End Dynamic":
|
|
225
|
+
extract = False
|
|
226
|
+
elif extract:
|
|
227
|
+
if isinstance(elem, ast.Assign):
|
|
228
|
+
text_exprs.append(astunparse.unparse(elem.value))
|
|
229
|
+
# x_var_name = elem.targets[0].id.replace('_plus','')
|
|
230
|
+
# x_var.append(x_var_name)
|
|
231
|
+
else:
|
|
232
|
+
if isinstance(elem, ast.Assign):
|
|
233
|
+
if elem.value.id == "args":
|
|
234
|
+
var_list = elem.targets[0].elts
|
|
235
|
+
for var in var_list[:-1]:
|
|
236
|
+
w_var.append(var.id)
|
|
237
|
+
elif elem.value.id == "x":
|
|
238
|
+
var_list = elem.targets[0].elts
|
|
239
|
+
for var in var_list:
|
|
240
|
+
x_var.append(var.id)
|
|
241
|
+
|
|
242
|
+
if len(text_exprs) != len(x_var):
|
|
243
|
+
raise ValueError(f"Failed to extract dynamics for {agent}")
|
|
244
|
+
|
|
245
|
+
symbol_x = [Symbol(elem, real=True) for elem in x_var]
|
|
246
|
+
symbol_w = [Symbol(elem, real=True) for elem in w_var]
|
|
247
|
+
dt = Symbol("dt", real=True)
|
|
248
|
+
|
|
249
|
+
tmp = [sympify(elem).subs("dt", time_step) for elem in text_exprs]
|
|
250
|
+
expr_symbol = []
|
|
251
|
+
for expr in tmp:
|
|
252
|
+
for symbol in symbol_x:
|
|
253
|
+
expr = expr.subs(symbol.name, symbol)
|
|
254
|
+
for symbol in symbol_w:
|
|
255
|
+
expr = expr.subs(symbol.name, symbol)
|
|
256
|
+
expr_symbol.append(expr)
|
|
257
|
+
exprs = expr_symbol
|
|
258
|
+
|
|
259
|
+
def computeD(x, w, x_hat, w_hat, dt):
|
|
260
|
+
d = []
|
|
261
|
+
for expr in exprs:
|
|
262
|
+
if all(a <= b for a, b in zip(x, x_hat)) and all(a <= b for a, b in zip(w, w_hat)):
|
|
263
|
+
var_range = {}
|
|
264
|
+
for i, var in enumerate(symbol_x):
|
|
265
|
+
var_range[var] = (x[i], x_hat[i])
|
|
266
|
+
for i, var in enumerate(symbol_w):
|
|
267
|
+
var_range[var] = (w[i], w_hat[i])
|
|
268
|
+
res = find_min_symbolic(expr, var_range)
|
|
269
|
+
d.append(res)
|
|
270
|
+
elif all(a >= b for a, b in zip(x, x_hat)) and all(
|
|
271
|
+
a >= b for a, b in zip(w, w_hat)
|
|
272
|
+
):
|
|
273
|
+
var_range = {}
|
|
274
|
+
for i, var in enumerate(symbol_x):
|
|
275
|
+
var_range[var] = (x_hat[i], x[i])
|
|
276
|
+
for i, var in enumerate(symbol_w):
|
|
277
|
+
var_range[var] = (w_hat[i], w[i])
|
|
278
|
+
res = find_max_symbolic(expr, var_range)
|
|
279
|
+
d.append(res)
|
|
280
|
+
else:
|
|
281
|
+
raise ValueError(
|
|
282
|
+
f"Condition for x, w, x_hat, w_hat not satisfied: {[x, w, x_hat, w_hat]}"
|
|
283
|
+
)
|
|
284
|
+
return d
|
|
285
|
+
|
|
286
|
+
res = compute_reachtube_mixmono_disc(
|
|
287
|
+
init, uncertain_param, time_horizon, time_step, computeD
|
|
288
|
+
)
|
|
289
|
+
else:
|
|
290
|
+
raise ValueError("Not enough information to apply discrete time mixed monotone algorithm.")
|
|
291
|
+
return res
|