Repository navigation
Expand file tree
/
Copy pathsimulation_monitor.py
More file actions
240 lines (200 loc) · 7.52 KB
/
Copy pathsimulation_monitor.py
File metadata and controls
240 lines (200 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""Standalone simulation monitoring module for recording robot state and metrics."""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Any
import numpy as np
@dataclass
class StateRecord:
"""Single timestep state record."""
timestamp: float
position: np.ndarray # (x, y) or full position
velocity: np.ndarray # (vx, vy)
min_obstacle_distance: float
mpc_latency: float = 0.0
@dataclass
class PlanningRecord:
"""Planning phase record."""
phase_name: str
planner_type: str # "rrt_star" or "ompl"
success: bool
planning_time: float
path_length: float
num_waypoints: int
@dataclass
class PhaseRecord:
"""Execution phase timing record."""
phase_name: str
start_time: float
end_time: float = 0.0
success: bool = True
@property
def duration(self) -> float:
return self.end_time - self.start_time if self.end_time > 0 else 0.0
class SimulationMonitor:
"""
Monitors simulation state and computes metrics.
Usage:
monitor = SimulationMonitor(safety_margin=0.1)
monitor.start()
# During simulation loop:
monitor.record_state(position, velocity, obstacle_dist, mpc_latency)
# After simulation:
stats = monitor.get_statistics()
"""
def __init__(self, safety_margin: float = 0.1):
"""
Initialize monitor.
Args:
safety_margin: Distance threshold for "safe" (meters).
"""
self.safety_margin = safety_margin
# State records
self.trajectory: list[StateRecord] = []
self.planning_records: list[PlanningRecord] = []
self.phase_records: list[PhaseRecord] = []
self.collision_events: list[tuple[float, np.ndarray]] = []
# Timing
self._start_time: float | None = None
self._active_phases: dict[str, PhaseRecord] = {}
# Goal tracking
self.goal_positions: list[tuple[float, float, float]] = []
self.reached_goals: list[bool] = []
def start(self) -> None:
"""Start monitoring (sets reference time)."""
self._start_time = time.time()
def _get_timestamp(self) -> float:
"""Get elapsed time since start."""
if self._start_time is None:
self._start_time = time.time()
return time.time() - self._start_time
def record_state(
self,
position: np.ndarray,
velocity: np.ndarray,
min_obstacle_distance: float,
mpc_latency: float = 0.0,
) -> None:
"""Record state at current timestep."""
self.trajectory.append(StateRecord(
timestamp=self._get_timestamp(),
position=np.array(position, dtype=float),
velocity=np.array(velocity, dtype=float),
min_obstacle_distance=min_obstacle_distance,
mpc_latency=mpc_latency,
))
def record_collision(self, position: np.ndarray) -> None:
"""Record a collision event."""
self.collision_events.append((
self._get_timestamp(),
np.array(position, dtype=float)
))
def start_phase(self, phase_name: str) -> None:
"""Start timing a phase."""
self._active_phases[phase_name] = PhaseRecord(
phase_name=phase_name,
start_time=time.time(),
)
def end_phase(self, phase_name: str, success: bool = True) -> None:
"""End timing a phase."""
if phase_name in self._active_phases:
phase = self._active_phases.pop(phase_name)
phase.end_time = time.time()
phase.success = success
self.phase_records.append(phase)
def record_planning_result(
self,
phase_name: str,
planner_type: str,
success: bool,
planning_time: float,
path: list | None = None,
) -> None:
"""Record a planning result."""
path_length = 0.0
num_waypoints = 0
if path is not None and len(path) > 1:
num_waypoints = len(path)
for i in range(1, len(path)):
if len(path[i]) >= 2 and len(path[i-1]) >= 2:
dx = path[i][0] - path[i-1][0]
dy = path[i][1] - path[i-1][1]
path_length += np.sqrt(dx*dx + dy*dy)
self.planning_records.append(PlanningRecord(
phase_name=phase_name,
planner_type=planner_type,
success=success,
planning_time=planning_time,
path_length=path_length,
num_waypoints=num_waypoints,
))
def set_goal_positions(self, goals: list[tuple[float, float, float]]) -> None:
"""Set goal positions to track."""
self.goal_positions = list(goals)
self.reached_goals = [False] * len(goals)
def mark_goal_reached(self, goal_index: int) -> None:
"""Mark a goal as reached."""
if 0 <= goal_index < len(self.reached_goals):
self.reached_goals[goal_index] = True
def get_statistics(self) -> dict[str, Any]:
"""
Compute and return all statistics.
Returns:
Dictionary with computed metrics.
"""
stats = {
"num_timesteps": len(self.trajectory),
"collision_count": len(self.collision_events),
"goals_reached": sum(self.reached_goals),
"total_goals": len(self.reached_goals),
}
# Time stats
if self.trajectory:
stats["total_time"] = self.trajectory[-1].timestamp
# Path length from trajectory
total_path = 0.0
for i in range(1, len(self.trajectory)):
pos_curr = self.trajectory[i].position
pos_prev = self.trajectory[i-1].position
if len(pos_curr) >= 2 and len(pos_prev) >= 2:
dx = pos_curr[0] - pos_prev[0]
dy = pos_curr[1] - pos_prev[1]
total_path += np.sqrt(dx*dx + dy*dy)
stats["total_path_length"] = total_path
# Obstacle margins
margins = [s.min_obstacle_distance for s in self.trajectory]
stats["min_obstacle_margin"] = min(margins)
stats["avg_obstacle_margin"] = np.mean(margins)
safe_count = sum(1 for m in margins if m > self.safety_margin)
stats["safety_rate"] = safe_count / len(margins)
# MPC latency
latencies = [s.mpc_latency for s in self.trajectory if s.mpc_latency > 0]
if latencies:
stats["avg_mpc_latency"] = np.mean(latencies)
stats["max_mpc_latency"] = max(latencies)
else:
stats["avg_mpc_latency"] = 0.0
stats["max_mpc_latency"] = 0.0
else:
stats["total_time"] = 0.0
stats["total_path_length"] = 0.0
stats["min_obstacle_margin"] = float('inf')
stats["avg_obstacle_margin"] = 0.0
stats["safety_rate"] = 0.0
stats["avg_mpc_latency"] = 0.0
stats["max_mpc_latency"] = 0.0
# Planning stats
stats["total_planning_time"] = sum(
pr.planning_time for pr in self.planning_records
)
return stats
def clear(self) -> None:
"""Clear all recorded data."""
self.trajectory.clear()
self.planning_records.clear()
self.phase_records.clear()
self.collision_events.clear()
self._active_phases.clear()
self.goal_positions.clear()
self.reached_goals.clear()
self._start_time = None