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,571 @@
|
|
|
1
|
+
from enum import Enum, auto
|
|
2
|
+
from functools import reduce
|
|
3
|
+
from typing import Any, Iterable, List, Dict, Optional, Sequence, TypeVar, Literal
|
|
4
|
+
import json
|
|
5
|
+
import numpy.typing as nptyp, numpy as np, portion
|
|
6
|
+
import networkx as nx
|
|
7
|
+
from matplotlib import colors
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import graphviz
|
|
10
|
+
|
|
11
|
+
from verse.analysis.dryvr import _EPSILON
|
|
12
|
+
from verse.agents.base_agent import BaseAgent
|
|
13
|
+
|
|
14
|
+
TraceType = nptyp.NDArray[np.double]
|
|
15
|
+
|
|
16
|
+
_T = TypeVar("_T")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def index_of(l: Iterable[_T], item: _T) -> Optional[int]:
|
|
20
|
+
"""Get the index of a item in an iterable. Returns None if not found"""
|
|
21
|
+
for i, v in enumerate(l):
|
|
22
|
+
if v == item:
|
|
23
|
+
return i
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AnalysisTreeNodeType(Enum):
|
|
28
|
+
"""Denotes different types of AnalysisTreeNode's. Can either be simulation traces or reach
|
|
29
|
+
tubes."""
|
|
30
|
+
|
|
31
|
+
SIM_TRACE = auto()
|
|
32
|
+
REACH_TUBE = auto()
|
|
33
|
+
|
|
34
|
+
def __str__(self) -> str:
|
|
35
|
+
return "simtrace" if self == AnalysisTreeNodeType.SIM_TRACE else "reachtube"
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def _from_str(s: str) -> "AnalysisTreeNodeType":
|
|
39
|
+
if s == "simtrace":
|
|
40
|
+
return AnalysisTreeNodeType.SIM_TRACE
|
|
41
|
+
if s == "reachtube":
|
|
42
|
+
return AnalysisTreeNodeType.REACH_TUBE
|
|
43
|
+
raise ValueError(f"Invalid string to AnalysisTreeNodeType: {s}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AnalysisTreeNode:
|
|
47
|
+
"""A AnalysisTreeNode stores the continous execution of the system without transition
|
|
48
|
+
happening"""
|
|
49
|
+
|
|
50
|
+
trace: Dict[str, TraceType]
|
|
51
|
+
"""The trace for each agent.
|
|
52
|
+
The key of the dict is the agent id and the value of the dict is the simulated traces for each
|
|
53
|
+
agent"""
|
|
54
|
+
init: Dict[str, Sequence[float]]
|
|
55
|
+
"""Initial conditions per agent for this node.
|
|
56
|
+
The key of the dict is the agent id and the value of the dict is the range/set of initial
|
|
57
|
+
conditions for that agent"""
|
|
58
|
+
mode: Dict[str, Sequence[str]]
|
|
59
|
+
"""Discrete mode per agent for this node.
|
|
60
|
+
The key of the dict is the agent id and the value of the dict is the discrete mode for that
|
|
61
|
+
agent"""
|
|
62
|
+
agent: Dict[str, BaseAgent]
|
|
63
|
+
"""Discrete mode per agent for this node.
|
|
64
|
+
The key of the dict is the agent id and the value of the dict is the object instance for that
|
|
65
|
+
agent"""
|
|
66
|
+
height: int
|
|
67
|
+
"""The height/depth of the current node in the AnalysisTree"""
|
|
68
|
+
assert_hits: Dict[str, Sequence[str]] # TODO type
|
|
69
|
+
"""Assert hits per agent for this node.
|
|
70
|
+
The key of the dict is the agent id and the value of the dict is the list of labels hit in the
|
|
71
|
+
node for that agent"""
|
|
72
|
+
child: List["AnalysisTreeNode"]
|
|
73
|
+
"""A list of children nodes for the current node. Can be empty."""
|
|
74
|
+
start_time: float
|
|
75
|
+
"""The earliest simulation time of this node."""
|
|
76
|
+
type: AnalysisTreeNodeType
|
|
77
|
+
"""Type of the node. Can either be "simtrace" or "reachtube"."""
|
|
78
|
+
ndigits: int
|
|
79
|
+
"""Number of digits to round `start_time` to."""
|
|
80
|
+
static: Dict[str, Sequence[str]]
|
|
81
|
+
"""Static data per agent for this node.
|
|
82
|
+
The key of the dict is the agent id and the value of the dict is the static data for that
|
|
83
|
+
agent"""
|
|
84
|
+
uncertain_param: Dict[str, Sequence[str]]
|
|
85
|
+
"""Parameters for uncertainty per agent for this node.
|
|
86
|
+
The key of the dict is the agent id and the value of the dict is the uncertainty data for that
|
|
87
|
+
agent"""
|
|
88
|
+
id: int
|
|
89
|
+
"""Integer ID for the current node. Unique amongst all nodes in the AnalysisTree"""
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
trace: Dict[str, TraceType],
|
|
94
|
+
init: Dict[str, Sequence[float]],
|
|
95
|
+
mode: Dict[str, Sequence[str]],
|
|
96
|
+
static: Dict[str, Sequence[str]],
|
|
97
|
+
uncertain_param: Dict[str, Sequence[str]],
|
|
98
|
+
agent: Dict[str, BaseAgent],
|
|
99
|
+
height: int,
|
|
100
|
+
assert_hits: Dict[str, Sequence[str]],
|
|
101
|
+
child: List["AnalysisTreeNode"],
|
|
102
|
+
start_time: float,
|
|
103
|
+
ndigits: int,
|
|
104
|
+
type: AnalysisTreeNodeType,
|
|
105
|
+
id: int,
|
|
106
|
+
) -> None:
|
|
107
|
+
self.trace = trace
|
|
108
|
+
self.init = init
|
|
109
|
+
self.mode = mode
|
|
110
|
+
self.agent = agent
|
|
111
|
+
self.height = height
|
|
112
|
+
self.child = child
|
|
113
|
+
self.start_time = round(start_time, ndigits)
|
|
114
|
+
self.assert_hits = assert_hits
|
|
115
|
+
self.type = type
|
|
116
|
+
self.static = static
|
|
117
|
+
self.uncertain_param = uncertain_param
|
|
118
|
+
self.id = id
|
|
119
|
+
self.ndigits = ndigits
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def root_from_inits(
|
|
123
|
+
init: Dict[str, Sequence[float]],
|
|
124
|
+
mode: Dict[str, Sequence[str]],
|
|
125
|
+
static: Dict[str, Sequence[str]],
|
|
126
|
+
uncertain_param: Dict[str, Sequence[str]],
|
|
127
|
+
agent: Dict[str, BaseAgent],
|
|
128
|
+
ndigits: int,
|
|
129
|
+
type: AnalysisTreeNodeType,
|
|
130
|
+
) -> "AnalysisTreeNode":
|
|
131
|
+
"""Construct the root node from initial conditions and other settings."""
|
|
132
|
+
return AnalysisTreeNode(
|
|
133
|
+
init=init,
|
|
134
|
+
mode=mode,
|
|
135
|
+
static=static,
|
|
136
|
+
uncertain_param=uncertain_param,
|
|
137
|
+
agent=agent,
|
|
138
|
+
ndigits=ndigits,
|
|
139
|
+
type=type,
|
|
140
|
+
trace={},
|
|
141
|
+
height=0,
|
|
142
|
+
child=[],
|
|
143
|
+
assert_hits={},
|
|
144
|
+
start_time=0,
|
|
145
|
+
id=0,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def new_child(
|
|
149
|
+
self,
|
|
150
|
+
init: Dict[str, Sequence[float]],
|
|
151
|
+
mode: Dict[str, Sequence[str]],
|
|
152
|
+
trace: Dict[str, TraceType],
|
|
153
|
+
start_time: float,
|
|
154
|
+
id: int,
|
|
155
|
+
) -> "AnalysisTreeNode":
|
|
156
|
+
"""Construct a child node, copying unchanged items from the parent node (self)."""
|
|
157
|
+
return AnalysisTreeNode(
|
|
158
|
+
init=init,
|
|
159
|
+
mode=mode,
|
|
160
|
+
trace=trace,
|
|
161
|
+
static=self.static,
|
|
162
|
+
uncertain_param=self.uncertain_param,
|
|
163
|
+
agent=self.agent,
|
|
164
|
+
ndigits=self.ndigits,
|
|
165
|
+
type=self.type,
|
|
166
|
+
height=self.height + 1,
|
|
167
|
+
child=[],
|
|
168
|
+
assert_hits={},
|
|
169
|
+
start_time=start_time,
|
|
170
|
+
id=id,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def _to_dict(self) -> Dict[str, Any]:
|
|
174
|
+
rst_dict = {
|
|
175
|
+
"id": self.id,
|
|
176
|
+
"parent": None,
|
|
177
|
+
"child": [],
|
|
178
|
+
"agent": {},
|
|
179
|
+
"init": {aid: list(init) for aid, init in self.init.items()},
|
|
180
|
+
"mode": self.mode,
|
|
181
|
+
"height": self.height,
|
|
182
|
+
"static": self.static,
|
|
183
|
+
"start_time": self.start_time,
|
|
184
|
+
"trace": (
|
|
185
|
+
{aid: t.tolist() for aid, t in self.trace.items()}
|
|
186
|
+
if self.type == AnalysisTreeNodeType.SIM_TRACE
|
|
187
|
+
else self.trace
|
|
188
|
+
),
|
|
189
|
+
"type": str(self.type),
|
|
190
|
+
"assert_hits": self.assert_hits,
|
|
191
|
+
"uncertain_param": self.uncertain_param,
|
|
192
|
+
"ndigits": self.ndigits,
|
|
193
|
+
}
|
|
194
|
+
agent_dict = {}
|
|
195
|
+
for agent_id in self.agent:
|
|
196
|
+
agent_dict[agent_id] = f"{type(self.agent[agent_id])}"
|
|
197
|
+
rst_dict["agent"] = agent_dict
|
|
198
|
+
|
|
199
|
+
return rst_dict
|
|
200
|
+
|
|
201
|
+
def get_track(self, agent_id: str, mode: Sequence[str]) -> Optional[str]:
|
|
202
|
+
"""Filter out the track mode(s) for a given agent"""
|
|
203
|
+
state_defs = self.agent[agent_id].decision_logic.state_defs
|
|
204
|
+
mode_def_names = next(iter(state_defs.values())).disc_type
|
|
205
|
+
track_mode_ind = index_of(mode_def_names, "TrackMode")
|
|
206
|
+
if track_mode_ind is None:
|
|
207
|
+
return None
|
|
208
|
+
return mode[track_mode_ind]
|
|
209
|
+
|
|
210
|
+
def get_mode(self, agent_id: str, mode: Sequence[str]) -> Optional[Sequence[str]]:
|
|
211
|
+
"""Either tries to find the AgentMode (or any non-TrackMode) if TrackMode exists or returns mode"""
|
|
212
|
+
state_defs = self.agent[agent_id].decision_logic.state_defs
|
|
213
|
+
mode_def_names = next(iter(state_defs.values())).disc_type
|
|
214
|
+
track_mode_ind = index_of(mode_def_names, "TrackMode")
|
|
215
|
+
if track_mode_ind is None:
|
|
216
|
+
if len(mode) == 1:
|
|
217
|
+
return mode[0]
|
|
218
|
+
return mode
|
|
219
|
+
# NOTE: TrackMode exists, find first discrete mode variable
|
|
220
|
+
for i in range(len(mode_def_names)):
|
|
221
|
+
if i != track_mode_ind:
|
|
222
|
+
return mode[i]
|
|
223
|
+
# NOTE: Only TrackMode exists, no other modes -- this should never be reached if scenario is created properly
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
@staticmethod
|
|
227
|
+
def _from_dict(data: Dict[str, Any]) -> "AnalysisTreeNode":
|
|
228
|
+
return AnalysisTreeNode(
|
|
229
|
+
trace=(
|
|
230
|
+
{aid: np.array(data["trace"][aid]) for aid in data["agent"].keys()}
|
|
231
|
+
if data["type"] == "simtrace"
|
|
232
|
+
else data["trace"]
|
|
233
|
+
),
|
|
234
|
+
id=data["id"],
|
|
235
|
+
init=data["init"],
|
|
236
|
+
mode=data["mode"],
|
|
237
|
+
height=data["height"],
|
|
238
|
+
static=data["static"],
|
|
239
|
+
agent=data["agent"],
|
|
240
|
+
assert_hits=data["assert_hits"],
|
|
241
|
+
child=[],
|
|
242
|
+
start_time=data["start_time"],
|
|
243
|
+
type=AnalysisTreeNodeType._from_str(data["type"]),
|
|
244
|
+
uncertain_param=data["uncertain_param"],
|
|
245
|
+
ndigits=data["ndigits"],
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _color_interp(c1: str, c2: str, mix: float) -> str:
|
|
250
|
+
return colors.to_hex(
|
|
251
|
+
(1 - mix) * np.array(colors.to_rgb(c1)) + mix * np.array(colors.to_rgb(c2))
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class AnalysisTree:
|
|
256
|
+
"""A tree containing the reachable states the scenario produced."""
|
|
257
|
+
|
|
258
|
+
root: AnalysisTreeNode
|
|
259
|
+
"""Root node for the tree"""
|
|
260
|
+
nodes: List[AnalysisTreeNode]
|
|
261
|
+
"""All nodes in the tree. Order is not guaranteed"""
|
|
262
|
+
type: AnalysisTreeNodeType
|
|
263
|
+
"""Type of the analysis tree"""
|
|
264
|
+
|
|
265
|
+
def __init__(self, root: AnalysisTreeNode) -> None:
|
|
266
|
+
self.root = root
|
|
267
|
+
self.nodes = self._get_all_nodes(root)
|
|
268
|
+
self.type = root.type
|
|
269
|
+
|
|
270
|
+
@staticmethod
|
|
271
|
+
def _get_all_nodes(root: AnalysisTreeNode) -> List[AnalysisTreeNode]:
|
|
272
|
+
# Perform BFS/DFS to store all the tree node in a list
|
|
273
|
+
res = []
|
|
274
|
+
queue = [root]
|
|
275
|
+
node_id = 0
|
|
276
|
+
while queue:
|
|
277
|
+
node = queue.pop(0)
|
|
278
|
+
res.append(node)
|
|
279
|
+
node_id += 1
|
|
280
|
+
queue += node.child
|
|
281
|
+
return res
|
|
282
|
+
|
|
283
|
+
def dump(self, fn: str) -> None:
|
|
284
|
+
"""Dumps the AnalysisTree as JSON data to the file "fn"."""
|
|
285
|
+
res_dict = {}
|
|
286
|
+
converted_node = self.root._to_dict()
|
|
287
|
+
res_dict[self.root.id] = converted_node
|
|
288
|
+
queue = [self.root]
|
|
289
|
+
while queue:
|
|
290
|
+
parent_node = queue.pop(0)
|
|
291
|
+
for child_node in parent_node.child:
|
|
292
|
+
node_dict = child_node._to_dict()
|
|
293
|
+
node_dict["parent"] = parent_node.id
|
|
294
|
+
res_dict[child_node.id] = node_dict
|
|
295
|
+
res_dict[parent_node.id]["child"].append(child_node.id)
|
|
296
|
+
queue.append(child_node)
|
|
297
|
+
|
|
298
|
+
with open(fn, "w+") as f:
|
|
299
|
+
json.dump(res_dict, f, indent=4, sort_keys=True)
|
|
300
|
+
|
|
301
|
+
@staticmethod
|
|
302
|
+
def load(fn: str) -> "AnalysisTree":
|
|
303
|
+
"""Loads the AnalysisTree from the file "fn" as JSON data."""
|
|
304
|
+
with open(fn, "r") as f:
|
|
305
|
+
data = json.load(f)
|
|
306
|
+
root_node_dict = data[str(0)]
|
|
307
|
+
root = AnalysisTreeNode._from_dict(root_node_dict)
|
|
308
|
+
queue = [(root_node_dict, root)]
|
|
309
|
+
while queue:
|
|
310
|
+
parent_node_dict, parent_node = queue.pop(0)
|
|
311
|
+
for child_node_idx in parent_node_dict["child"]:
|
|
312
|
+
child_node_dict = data[str(child_node_idx)]
|
|
313
|
+
child_node = AnalysisTreeNode._from_dict(child_node_dict)
|
|
314
|
+
parent_node.child.append(child_node)
|
|
315
|
+
queue.append((child_node_dict, child_node))
|
|
316
|
+
return AnalysisTree(root)
|
|
317
|
+
|
|
318
|
+
# TODO Generalize to different timesteps
|
|
319
|
+
def contains(
|
|
320
|
+
self, other: "AnalysisTree", strict: bool = True, tol: Optional[float] = None
|
|
321
|
+
) -> bool:
|
|
322
|
+
"""Checks whether this AnalysisTree constains the `other` AnalysisTree. Returns, for
|
|
323
|
+
reachability, whether the current tree (bloated by a small value) fully contains the other
|
|
324
|
+
tree or not; for simulation, whether the other tree is close enough to the current tree.
|
|
325
|
+
strict: requires set of agents to be the same
|
|
326
|
+
"""
|
|
327
|
+
tol = _EPSILON if tol is None else tol
|
|
328
|
+
cur_agents = set(self.nodes[0].agent.keys())
|
|
329
|
+
other_agents = set(other.nodes[0].agent.keys())
|
|
330
|
+
min_agents = list(other_agents)
|
|
331
|
+
types = list(set(n.type for n in self.nodes + other.nodes))
|
|
332
|
+
assert len(types) == 1, f"Different types of nodes: {types}"
|
|
333
|
+
if not (
|
|
334
|
+
(strict and cur_agents == other_agents)
|
|
335
|
+
or (not strict and cur_agents.issuperset(other_agents))
|
|
336
|
+
):
|
|
337
|
+
return False
|
|
338
|
+
if types[0] == "simtrace": # Simulation
|
|
339
|
+
if len(self.nodes) != len(other.nodes):
|
|
340
|
+
return False
|
|
341
|
+
|
|
342
|
+
def sim_seg_contains(a: Dict[str, TraceType], b: Dict[str, TraceType]) -> bool:
|
|
343
|
+
return all(
|
|
344
|
+
a[aid].shape == b[aid].shape
|
|
345
|
+
and bool(np.all(np.abs(a[aid][:, 1:] - b[aid][:, 1:]) < tol))
|
|
346
|
+
for aid in min_agents
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
def sim_node_contains(a: AnalysisTreeNode, b: AnalysisTreeNode) -> bool:
|
|
350
|
+
if not sim_seg_contains(a.trace, b.trace):
|
|
351
|
+
return False
|
|
352
|
+
if len(a.child) != len(b.child):
|
|
353
|
+
return False
|
|
354
|
+
child_num = len(a.child)
|
|
355
|
+
other_not_paired = set(range(child_num))
|
|
356
|
+
for i in range(child_num):
|
|
357
|
+
for j in other_not_paired:
|
|
358
|
+
if sim_node_contains(a.child[i], b.child[j]):
|
|
359
|
+
other_not_paired.remove(j)
|
|
360
|
+
break
|
|
361
|
+
else:
|
|
362
|
+
return False
|
|
363
|
+
return True
|
|
364
|
+
|
|
365
|
+
return sim_node_contains(self.root, other.root)
|
|
366
|
+
else: # Reachability
|
|
367
|
+
cont_num = len(other.nodes[0].trace[min_agents[0]][0])
|
|
368
|
+
|
|
369
|
+
def collect_ranges(
|
|
370
|
+
n: AnalysisTreeNode,
|
|
371
|
+
) -> Dict[str, List[List[portion.Interval]]]:
|
|
372
|
+
trace_len = len(n.trace[min_agents[0]])
|
|
373
|
+
cur = {
|
|
374
|
+
aid: [
|
|
375
|
+
[
|
|
376
|
+
portion.closed(n.trace[aid][i][j], n.trace[aid][i + 1][j])
|
|
377
|
+
for j in range(cont_num)
|
|
378
|
+
]
|
|
379
|
+
for i in range(0, trace_len, 2)
|
|
380
|
+
]
|
|
381
|
+
for aid in min_agents
|
|
382
|
+
}
|
|
383
|
+
if len(n.child) == 0:
|
|
384
|
+
return {aid: cur[aid] for aid in other_agents}
|
|
385
|
+
else:
|
|
386
|
+
children = [collect_ranges(c) for c in n.child]
|
|
387
|
+
child_num = len(children)
|
|
388
|
+
time_step = round(
|
|
389
|
+
n.trace[min_agents[0]][-1][0] - n.trace[min_agents[0]][-2][0],
|
|
390
|
+
10,
|
|
391
|
+
)
|
|
392
|
+
start_time_list = [c.start_time for c in n.child]
|
|
393
|
+
min_start_time = min(start_time_list)
|
|
394
|
+
bias_list = [
|
|
395
|
+
round((c.start_time - min_start_time) / time_step) for c in n.child
|
|
396
|
+
]
|
|
397
|
+
trace_len_list = [len(children[i][min_agents[0]]) for i in range(child_num)]
|
|
398
|
+
trace_len = max(trace_len_list)
|
|
399
|
+
combined = {
|
|
400
|
+
aid: [
|
|
401
|
+
[
|
|
402
|
+
reduce(
|
|
403
|
+
portion.Interval.union,
|
|
404
|
+
(
|
|
405
|
+
children[k][aid][i - bias_list[k]][j]
|
|
406
|
+
if i - bias_list[k] >= 0
|
|
407
|
+
and i - bias_list[k] < trace_len_list[k]
|
|
408
|
+
else portion.empty()
|
|
409
|
+
for k in range(child_num)
|
|
410
|
+
),
|
|
411
|
+
)
|
|
412
|
+
for j in range(cont_num)
|
|
413
|
+
]
|
|
414
|
+
for i in range(trace_len)
|
|
415
|
+
]
|
|
416
|
+
for aid in other_agents
|
|
417
|
+
}
|
|
418
|
+
overlap_len = round(
|
|
419
|
+
(n.trace[min_agents[0]][-1][0] - min_start_time) / time_step
|
|
420
|
+
)
|
|
421
|
+
overlap = {
|
|
422
|
+
aid: [
|
|
423
|
+
[
|
|
424
|
+
portion.Interval.union(
|
|
425
|
+
cur[aid][i][j], combined[aid][overlap_len + i][j]
|
|
426
|
+
)
|
|
427
|
+
for j in range(cont_num)
|
|
428
|
+
]
|
|
429
|
+
for i in range(-overlap_len, 0)
|
|
430
|
+
]
|
|
431
|
+
for aid in other_agents
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
aid: cur[aid][:-overlap_len] + overlap[aid] + combined[aid][overlap_len:]
|
|
435
|
+
for aid in other_agents
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
this_tree, other_tree = collect_ranges(self.root), collect_ranges(other.root)
|
|
439
|
+
total_len = len(other_tree[min_agents[0]])
|
|
440
|
+
assert total_len <= len(this_tree[min_agents[0]])
|
|
441
|
+
# bloat and containment
|
|
442
|
+
return all(
|
|
443
|
+
other_tree[aid][i][j]
|
|
444
|
+
in this_tree[aid][i][j].apply(
|
|
445
|
+
lambda x: x.replace(lower=lambda v: v - tol, upper=lambda v: v + tol)
|
|
446
|
+
)
|
|
447
|
+
for aid in other_agents
|
|
448
|
+
for i in range(total_len)
|
|
449
|
+
for j in range(cont_num)
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
@staticmethod
|
|
453
|
+
def _get_len(node: AnalysisTreeNode, lens: Dict[int, int]) -> int:
|
|
454
|
+
res = len(next(iter(node.trace.values()))) + (
|
|
455
|
+
0 if len(node.child) == 0 else max(AnalysisTree._get_len(c, lens) for c in node.child)
|
|
456
|
+
)
|
|
457
|
+
lens[node.id] = res
|
|
458
|
+
return res
|
|
459
|
+
|
|
460
|
+
def visualize(self) -> None:
|
|
461
|
+
"""Visualizes the AnalysisTree as a tree graph using `networkx`.
|
|
462
|
+
Each node in the graph will correspond to one AnalysisTreeNode, and the edges denote
|
|
463
|
+
parent/child relationship. Each node will be colored according to a gradient from red to
|
|
464
|
+
blue using the start_time of each node, where red signifies newer nodes and blue signifies
|
|
465
|
+
older nodes.
|
|
466
|
+
"""
|
|
467
|
+
lens = {}
|
|
468
|
+
total_len = AnalysisTree._get_len(self.root, lens)
|
|
469
|
+
G = nx.Graph()
|
|
470
|
+
for node in self.nodes:
|
|
471
|
+
G.add_node(node.id, time=(node.id, node.start_time))
|
|
472
|
+
for child in node.child:
|
|
473
|
+
G.add_node(child.id, time=(child.id, child.start_time))
|
|
474
|
+
G.add_edge(node.id, child.id)
|
|
475
|
+
labels = nx.get_node_attributes(G, "time")
|
|
476
|
+
nx.draw_planar(
|
|
477
|
+
G,
|
|
478
|
+
node_color=[_color_interp("red", "blue", lens[id] / total_len) for id in G],
|
|
479
|
+
labels=labels,
|
|
480
|
+
)
|
|
481
|
+
plt.show()
|
|
482
|
+
|
|
483
|
+
def visualize_dot(
|
|
484
|
+
self,
|
|
485
|
+
filename: str,
|
|
486
|
+
otype: Literal["png", "svg", "pdf", "jpg"] = "png",
|
|
487
|
+
font: Optional[str] = None,
|
|
488
|
+
) -> None:
|
|
489
|
+
"""Same as `visualize`, but rather use `graphviz` to for visualizing the tree.
|
|
490
|
+
`filename` is the prefix, i.e. doesn't include extensions. `filename.dot` will be saved as
|
|
491
|
+
well as `filename.png`
|
|
492
|
+
"""
|
|
493
|
+
|
|
494
|
+
def diff(a: AnalysisTreeNode, b: AnalysisTreeNode) -> List[str]:
|
|
495
|
+
return [aid for aid in a.agent if a.mode[aid] != b.mode[aid]]
|
|
496
|
+
|
|
497
|
+
lens = {}
|
|
498
|
+
total_len = AnalysisTree._get_len(self.root, lens)
|
|
499
|
+
graph = graphviz.Digraph()
|
|
500
|
+
for node in self.nodes:
|
|
501
|
+
tooltip = "\n".join(
|
|
502
|
+
f"{aid}: {[*node.mode[aid], *node.init[aid]]}" for aid in node.agent
|
|
503
|
+
)
|
|
504
|
+
graph.node(
|
|
505
|
+
str(node.id),
|
|
506
|
+
label=str(node.id),
|
|
507
|
+
color=_color_interp("red", "blue", lens[node.id] / total_len),
|
|
508
|
+
tooltip=tooltip,
|
|
509
|
+
)
|
|
510
|
+
for c in node.child:
|
|
511
|
+
d = diff(node, c)
|
|
512
|
+
tooltip = "\n".join(f"{aid}: {node.mode[aid]} -> {c.mode[aid]}" for aid in d)
|
|
513
|
+
graph.edge(str(node.id), str(c.id), label=", ".join(d), tooltip=tooltip)
|
|
514
|
+
if font is not None:
|
|
515
|
+
graph.node_attr.update(fontname=font)
|
|
516
|
+
graph.edge_attr.update(fontname=font)
|
|
517
|
+
graph.graph_attr.update(fontname=font)
|
|
518
|
+
graph.render(
|
|
519
|
+
filename + ".dot",
|
|
520
|
+
format=otype,
|
|
521
|
+
outfile=filename + "." + otype,
|
|
522
|
+
engine="twopi",
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
def is_equal(self, other: "AnalysisTree") -> bool:
|
|
526
|
+
"""Compares if 2 AnalysisTree's traces are close enough. For simulation, this simply
|
|
527
|
+
compares if the point data are within a small range. For reachability, this checks if the
|
|
528
|
+
start and end points respectively for each dimension are within a small range of the other
|
|
529
|
+
tree"""
|
|
530
|
+
return self.contains(other) and other.contains(self)
|
|
531
|
+
|
|
532
|
+
def leaves(self) -> int:
|
|
533
|
+
"""Return the number of leaves for this tree"""
|
|
534
|
+
count = 0
|
|
535
|
+
for node in self.nodes:
|
|
536
|
+
if len(node.child) == 0:
|
|
537
|
+
count += 1
|
|
538
|
+
return count
|
|
539
|
+
|
|
540
|
+
# get all the leaf nodes
|
|
541
|
+
def get_leaf_nodes(self, root):
|
|
542
|
+
leafs = []
|
|
543
|
+
self.collect_leaf_nodes(root, leafs)
|
|
544
|
+
return leafs
|
|
545
|
+
|
|
546
|
+
# helper method
|
|
547
|
+
def collect_leaf_nodes(self, node, leafs):
|
|
548
|
+
if node is not None:
|
|
549
|
+
if len(node.child) == 0: ###
|
|
550
|
+
leafs.append(node)
|
|
551
|
+
for n in node.child: ###
|
|
552
|
+
self.collect_leaf_nodes(n, leafs)
|
|
553
|
+
|
|
554
|
+
# get the height of the tree
|
|
555
|
+
def height(self, root):
|
|
556
|
+
if not root.child:
|
|
557
|
+
return 1
|
|
558
|
+
|
|
559
|
+
else:
|
|
560
|
+
return 1 + max(self.height(x) for x in root.child)
|
|
561
|
+
|
|
562
|
+
def first_transitions(tree: AnalysisTree) -> Dict[str, float]: # id, start time
|
|
563
|
+
"""Collects the time when each agent first transitions for a AnalysisTree. Returns a dict
|
|
564
|
+
mapping from agent IDs to the simulation time when it first transitions"""
|
|
565
|
+
d = {}
|
|
566
|
+
for node in tree.nodes:
|
|
567
|
+
for child in node.child:
|
|
568
|
+
for aid in node.agent:
|
|
569
|
+
if aid not in d and node.mode[aid] != child.mode[aid]:
|
|
570
|
+
d[aid] = child.start_time
|
|
571
|
+
return d
|