Datasets:
Download script/generate_trajectory_html.py from humanoidro/gimbaled-uav-tracking-dataset: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/datasets/humanoidro/gimbaled-uav-tracking-dataset/resolve/main/script/generate_trajectory_html.py
- Command line
-
hf download hf://datasets/humanoidro/gimbaled-uav-tracking-dataset/script/generate_trajectory_html.py
-
curl -L -o generate_trajectory_html.py https://huggingface.co/datasets/humanoidro/gimbaled-uav-tracking-dataset/resolve/main/script/generate_trajectory_html.py
20.4 kB
| #!/usr/bin/env python3 | |
| """Generate one offline HTML page comparing tracking and RTK trajectories.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import html | |
| import math | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import plotly.graph_objects as go | |
| import plotly.io as pio | |
| from plotly.subplots import make_subplots | |
| EXPECTED_FLIGHTS = tuple(f"flight_{index:02d}" for index in range(1, 17)) | |
| RTK_COLOR = "#16803c" | |
| TRACKING_COLOR = "#d44a3a" | |
| VEHICLE_COLOR = "#24527a" | |
| GRID_COLOR = "#dfe5e8" | |
| TEXT_COLOR = "#243238" | |
| MINIMUM_AXIS_DISPLAY_RATIO = 0.30 | |
| class Trajectory: | |
| flight_id: str | |
| timestamp_us: list[int] | |
| tracking_x_m: list[float] | |
| tracking_y_m: list[float] | |
| tracking_z_m: list[float] | |
| rtk_x_m: list[float] | |
| rtk_y_m: list[float] | |
| rtk_z_m: list[float] | |
| error_3d_m: list[float] | |
| def relative_time_s(self) -> list[float]: | |
| first = self.timestamp_us[0] | |
| return [(value - first) / 1e6 for value in self.timestamp_us] | |
| def rmse_3d_m(self) -> float: | |
| return math.sqrt( | |
| math.fsum(value * value for value in self.error_3d_m) | |
| / len(self.error_3d_m) | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| script_dir = Path(__file__).resolve().parent | |
| default_root = script_dir.parent | |
| parser = argparse.ArgumentParser( | |
| description="生成全部航次识别轨迹与 RTK 轨迹的离线 HTML" | |
| ) | |
| parser.add_argument( | |
| "dataset_root", | |
| nargs="?", | |
| type=Path, | |
| default=default_root, | |
| help="数据集根目录;默认根据脚本位置确定", | |
| ) | |
| parser.add_argument( | |
| "--input", | |
| type=Path, | |
| help="轨迹 CSV;默认为 DATASET_ROOT/script/output/paired_errors.csv", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| type=Path, | |
| help="HTML 路径;默认为 DATASET_ROOT/script/output/trajectories.html", | |
| ) | |
| return parser.parse_args() | |
| def finite_float(row: dict[str, str], key: str, line_number: int) -> float: | |
| try: | |
| value = float(row[key]) | |
| except (KeyError, TypeError, ValueError) as error: | |
| raise ValueError(f"第 {line_number} 行的 {key} 无法解析") from error | |
| if not math.isfinite(value): | |
| raise ValueError(f"第 {line_number} 行的 {key} 不是有限数") | |
| return value | |
| def empty_trajectory(flight_id: str) -> Trajectory: | |
| return Trajectory( | |
| flight_id=flight_id, | |
| timestamp_us=[], | |
| tracking_x_m=[], | |
| tracking_y_m=[], | |
| tracking_z_m=[], | |
| rtk_x_m=[], | |
| rtk_y_m=[], | |
| rtk_z_m=[], | |
| error_3d_m=[], | |
| ) | |
| def read_trajectories(path: Path) -> list[Trajectory]: | |
| required_columns = { | |
| "flight_id", | |
| "timestamp_us", | |
| "tracking_x_v_m", | |
| "tracking_y_v_m", | |
| "tracking_z_v_m", | |
| "reference_x_v_m", | |
| "reference_y_v_m", | |
| "reference_z_v_m", | |
| "error_3d_m", | |
| } | |
| grouped: dict[str, Trajectory] = {} | |
| with path.open("r", encoding="utf-8", newline="") as stream: | |
| reader = csv.DictReader(stream) | |
| fieldnames = set(reader.fieldnames or ()) | |
| missing = sorted(required_columns - fieldnames) | |
| if missing: | |
| raise ValueError(f"{path} 缺少字段:{', '.join(missing)}") | |
| for line_number, row in enumerate(reader, start=2): | |
| flight_id = row["flight_id"] | |
| if flight_id not in EXPECTED_FLIGHTS: | |
| raise ValueError(f"第 {line_number} 行包含未知航次:{flight_id}") | |
| trajectory = grouped.setdefault( | |
| flight_id, empty_trajectory(flight_id) | |
| ) | |
| try: | |
| timestamp_us = int(row["timestamp_us"]) | |
| except (TypeError, ValueError) as error: | |
| raise ValueError( | |
| f"第 {line_number} 行的 timestamp_us 无法解析" | |
| ) from error | |
| trajectory.timestamp_us.append(timestamp_us) | |
| trajectory.tracking_x_m.append( | |
| finite_float(row, "tracking_x_v_m", line_number) | |
| ) | |
| trajectory.tracking_y_m.append( | |
| finite_float(row, "tracking_y_v_m", line_number) | |
| ) | |
| trajectory.tracking_z_m.append( | |
| finite_float(row, "tracking_z_v_m", line_number) | |
| ) | |
| trajectory.rtk_x_m.append( | |
| finite_float(row, "reference_x_v_m", line_number) | |
| ) | |
| trajectory.rtk_y_m.append( | |
| finite_float(row, "reference_y_v_m", line_number) | |
| ) | |
| trajectory.rtk_z_m.append( | |
| finite_float(row, "reference_z_v_m", line_number) | |
| ) | |
| trajectory.error_3d_m.append( | |
| finite_float(row, "error_3d_m", line_number) | |
| ) | |
| missing_flights = sorted(set(EXPECTED_FLIGHTS) - set(grouped)) | |
| if missing_flights: | |
| raise ValueError(f"{path} 缺少航次:{', '.join(missing_flights)}") | |
| trajectories = [grouped[flight_id] for flight_id in EXPECTED_FLIGHTS] | |
| for trajectory in trajectories: | |
| if len(trajectory.timestamp_us) < 2: | |
| raise ValueError(f"{trajectory.flight_id} 的有效轨迹点不足 2 个") | |
| order = sorted( | |
| range(len(trajectory.timestamp_us)), | |
| key=trajectory.timestamp_us.__getitem__, | |
| ) | |
| for field_name in ( | |
| "timestamp_us", | |
| "tracking_x_m", | |
| "tracking_y_m", | |
| "tracking_z_m", | |
| "rtk_x_m", | |
| "rtk_y_m", | |
| "rtk_z_m", | |
| "error_3d_m", | |
| ): | |
| values = getattr(trajectory, field_name) | |
| setattr(trajectory, field_name, [values[index] for index in order]) | |
| return trajectories | |
| def scene_aspect_ratio(trajectory: Trajectory) -> dict[str, float]: | |
| coordinates = ( | |
| trajectory.tracking_x_m + trajectory.rtk_x_m + [0.0], | |
| trajectory.tracking_y_m + trajectory.rtk_y_m + [0.0], | |
| trajectory.tracking_z_m + trajectory.rtk_z_m + [0.0], | |
| ) | |
| spans = [max(values) - min(values) for values in coordinates] | |
| maximum_span = max(spans) | |
| if maximum_span <= 0.0: | |
| return {"x": 1.0, "y": 1.0, "z": 1.0} | |
| ratios = [ | |
| max(span / maximum_span, MINIMUM_AXIS_DISPLAY_RATIO) | |
| for span in spans | |
| ] | |
| return {"x": ratios[0], "y": ratios[1], "z": ratios[2]} | |
| def build_overview(trajectories: list[Trajectory]) -> go.Figure: | |
| rows = 4 | |
| columns = 4 | |
| titles = [ | |
| ( | |
| f"<b>{trajectory.flight_id}</b>" | |
| f" · RMSE {trajectory.rmse_3d_m:.3f} m" | |
| ) | |
| for trajectory in trajectories | |
| ] | |
| figure = make_subplots( | |
| rows=rows, | |
| cols=columns, | |
| specs=[ | |
| [{"type": "scene"} for _ in range(columns)] | |
| for _ in range(rows) | |
| ], | |
| subplot_titles=titles, | |
| horizontal_spacing=0.035, | |
| vertical_spacing=0.065, | |
| ) | |
| for index, trajectory in enumerate(trajectories): | |
| row = index // columns + 1 | |
| column = index % columns + 1 | |
| figure.add_trace( | |
| go.Scatter3d( | |
| x=trajectory.rtk_x_m, | |
| y=trajectory.rtk_y_m, | |
| z=trajectory.rtk_z_m, | |
| mode="lines", | |
| line={"color": RTK_COLOR, "width": 6}, | |
| name="RTK 轨迹", | |
| legendgroup="rtk", | |
| showlegend=index == 0, | |
| customdata=[ | |
| [time_s] | |
| for time_s in trajectory.relative_time_s | |
| ], | |
| hovertemplate=( | |
| "<b>RTK</b><br>" | |
| "X=%{x:.2f} m<br>Y=%{y:.2f} m<br>Z=%{z:.2f} m<br>" | |
| "t=%{customdata[0]:.1f} s<extra></extra>" | |
| ), | |
| ), | |
| row=row, | |
| col=column, | |
| ) | |
| figure.add_trace( | |
| go.Scatter3d( | |
| x=[0.0], | |
| y=[0.0], | |
| z=[0.0], | |
| mode="markers+text", | |
| marker={ | |
| "color": VEHICLE_COLOR, | |
| "size": 7, | |
| "symbol": "diamond", | |
| "line": {"color": "#ffffff", "width": 1}, | |
| }, | |
| text=["车辆原点"], | |
| textposition="top center", | |
| textfont={"color": VEHICLE_COLOR, "size": 11}, | |
| name="车辆原点", | |
| legendgroup="vehicle", | |
| showlegend=index == 0, | |
| hovertemplate=( | |
| "<b>车辆原点</b><br>" | |
| "X=0.00 m<br>Y=0.00 m<br>Z=0.00 m<extra></extra>" | |
| ), | |
| ), | |
| row=row, | |
| col=column, | |
| ) | |
| figure.add_trace( | |
| go.Scatter3d( | |
| x=trajectory.tracking_x_m, | |
| y=trajectory.tracking_y_m, | |
| z=trajectory.tracking_z_m, | |
| mode="lines", | |
| line={"color": TRACKING_COLOR, "width": 5}, | |
| name="识别轨迹", | |
| legendgroup="tracking", | |
| showlegend=index == 0, | |
| customdata=[ | |
| [time_s, error_m] | |
| for time_s, error_m in zip( | |
| trajectory.relative_time_s, | |
| trajectory.error_3d_m, | |
| ) | |
| ], | |
| hovertemplate=( | |
| "<b>识别</b><br>" | |
| "X=%{x:.2f} m<br>Y=%{y:.2f} m<br>Z=%{z:.2f} m<br>" | |
| "t=%{customdata[0]:.1f} s<br>" | |
| "3D 误差=%{customdata[1]:.3f} m<extra></extra>" | |
| ), | |
| ), | |
| row=row, | |
| col=column, | |
| ) | |
| for index, trajectory in enumerate(trajectories): | |
| scene_name = "scene" if index == 0 else f"scene{index + 1}" | |
| figure.layout[scene_name].update( | |
| { | |
| "xaxis": { | |
| "title": "X (m)", | |
| "gridcolor": GRID_COLOR, | |
| "backgroundcolor": "#f8fafb", | |
| }, | |
| "yaxis": { | |
| "title": "Y (m)", | |
| "gridcolor": GRID_COLOR, | |
| "backgroundcolor": "#f8fafb", | |
| }, | |
| "zaxis": { | |
| "title": "Z (m)", | |
| "gridcolor": GRID_COLOR, | |
| "backgroundcolor": "#f8fafb", | |
| }, | |
| "aspectmode": "manual", | |
| "aspectratio": scene_aspect_ratio(trajectory), | |
| } | |
| ) | |
| figure.update_layout( | |
| height=1500, | |
| paper_bgcolor="#ffffff", | |
| plot_bgcolor="#f8fafb", | |
| font={"family": "Arial, sans-serif", "color": TEXT_COLOR}, | |
| margin={"l": 20, "r": 20, "t": 72, "b": 25}, | |
| legend={ | |
| "orientation": "h", | |
| "x": 0.5, | |
| "xanchor": "center", | |
| "y": 1.045, | |
| "yanchor": "bottom", | |
| }, | |
| hovermode="closest", | |
| ) | |
| return figure | |
| def build_detail(trajectories: list[Trajectory]) -> go.Figure: | |
| figure = go.Figure() | |
| for index, trajectory in enumerate(trajectories): | |
| visible = index == 0 | |
| figure.add_trace( | |
| go.Scatter3d( | |
| x=trajectory.rtk_x_m, | |
| y=trajectory.rtk_y_m, | |
| z=trajectory.rtk_z_m, | |
| mode="lines", | |
| line={"color": RTK_COLOR, "width": 7}, | |
| name="RTK 轨迹", | |
| legendgroup="rtk", | |
| visible=visible, | |
| customdata=[ | |
| [time_s] | |
| for time_s in trajectory.relative_time_s | |
| ], | |
| hovertemplate=( | |
| "<b>RTK</b><br>" | |
| "X=%{x:.2f} m<br>Y=%{y:.2f} m<br>Z=%{z:.2f} m<br>" | |
| "t=%{customdata[0]:.1f} s<extra></extra>" | |
| ), | |
| ) | |
| ) | |
| figure.add_trace( | |
| go.Scatter3d( | |
| x=[0.0], | |
| y=[0.0], | |
| z=[0.0], | |
| mode="markers+text", | |
| marker={ | |
| "color": VEHICLE_COLOR, | |
| "size": 8, | |
| "symbol": "diamond", | |
| "line": {"color": "#ffffff", "width": 1}, | |
| }, | |
| text=["车辆原点"], | |
| textposition="top center", | |
| textfont={"color": VEHICLE_COLOR, "size": 12}, | |
| name="车辆原点", | |
| legendgroup="vehicle", | |
| visible=visible, | |
| hovertemplate=( | |
| "<b>车辆原点</b><br>" | |
| "X=0.00 m<br>Y=0.00 m<br>Z=0.00 m<extra></extra>" | |
| ), | |
| ) | |
| ) | |
| figure.add_trace( | |
| go.Scatter3d( | |
| x=trajectory.tracking_x_m, | |
| y=trajectory.tracking_y_m, | |
| z=trajectory.tracking_z_m, | |
| mode="lines", | |
| line={"color": TRACKING_COLOR, "width": 6}, | |
| name="识别轨迹", | |
| legendgroup="tracking", | |
| visible=visible, | |
| customdata=[ | |
| [time_s, error_m] | |
| for time_s, error_m in zip( | |
| trajectory.relative_time_s, | |
| trajectory.error_3d_m, | |
| ) | |
| ], | |
| hovertemplate=( | |
| "<b>识别</b><br>" | |
| "X=%{x:.2f} m<br>Y=%{y:.2f} m<br>Z=%{z:.2f} m<br>" | |
| "t=%{customdata[0]:.1f} s<br>" | |
| "3D 误差=%{customdata[1]:.3f} m<extra></extra>" | |
| ), | |
| ) | |
| ) | |
| buttons = [] | |
| for index, trajectory in enumerate(trajectories): | |
| visibility = [ | |
| trace_index // 3 == index | |
| for trace_index in range(3 * len(trajectories)) | |
| ] | |
| buttons.append( | |
| { | |
| "label": trajectory.flight_id, | |
| "method": "update", | |
| "args": [ | |
| {"visible": visibility}, | |
| { | |
| "title": { | |
| "text": ( | |
| f"{trajectory.flight_id}" | |
| f" · 3D RMSE {trajectory.rmse_3d_m:.3f} m" | |
| ), | |
| "x": 0.5, | |
| }, | |
| "scene.aspectmode": "manual", | |
| "scene.aspectratio": scene_aspect_ratio(trajectory), | |
| }, | |
| ], | |
| } | |
| ) | |
| first = trajectories[0] | |
| figure.update_layout( | |
| height=720, | |
| title={ | |
| "text": f"{first.flight_id} · 3D RMSE {first.rmse_3d_m:.3f} m", | |
| "x": 0.5, | |
| }, | |
| paper_bgcolor="#ffffff", | |
| font={"family": "Arial, sans-serif", "color": TEXT_COLOR}, | |
| margin={"l": 15, "r": 15, "t": 95, "b": 10}, | |
| scene={ | |
| "xaxis": { | |
| "title": "X 前向 (m)", | |
| "gridcolor": GRID_COLOR, | |
| "backgroundcolor": "#f8fafb", | |
| }, | |
| "yaxis": { | |
| "title": "Y 左向 (m)", | |
| "gridcolor": GRID_COLOR, | |
| "backgroundcolor": "#f8fafb", | |
| }, | |
| "zaxis": { | |
| "title": "Z 上向 (m)", | |
| "gridcolor": GRID_COLOR, | |
| "backgroundcolor": "#f8fafb", | |
| }, | |
| "aspectmode": "manual", | |
| "aspectratio": scene_aspect_ratio(first), | |
| }, | |
| legend={ | |
| "orientation": "h", | |
| "x": 0.5, | |
| "xanchor": "center", | |
| "y": 1.02, | |
| "yanchor": "bottom", | |
| }, | |
| updatemenus=[ | |
| { | |
| "buttons": buttons, | |
| "direction": "down", | |
| "showactive": True, | |
| "active": 0, | |
| "x": 0.01, | |
| "xanchor": "left", | |
| "y": 1.13, | |
| "yanchor": "top", | |
| } | |
| ], | |
| ) | |
| return figure | |
| def write_html( | |
| output_path: Path, | |
| input_path: Path, | |
| trajectories: list[Trajectory], | |
| ) -> None: | |
| config = { | |
| "displaylogo": False, | |
| "responsive": True, | |
| "scrollZoom": True, | |
| "toImageButtonOptions": { | |
| "format": "png", | |
| "filename": "tracking_rtk_trajectory", | |
| "scale": 2, | |
| }, | |
| } | |
| overview_html = pio.to_html( | |
| build_overview(trajectories), | |
| include_plotlyjs=True, | |
| full_html=False, | |
| config=config, | |
| ) | |
| detail_html = pio.to_html( | |
| build_detail(trajectories), | |
| include_plotlyjs=False, | |
| full_html=False, | |
| config=config, | |
| ) | |
| sample_count = sum(len(item.timestamp_us) for item in trajectories) | |
| source_name = html.escape(input_path.name) | |
| document = f"""<!doctype html> | |
| <html lang="zh-CN"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>识别轨迹与 RTK 轨迹</title> | |
| <style> | |
| :root {{ | |
| color-scheme: light; | |
| --ink: {TEXT_COLOR}; | |
| --muted: #647278; | |
| --line: #dfe5e8; | |
| --panel: #ffffff; | |
| --page: #f3f6f7; | |
| }} | |
| * {{ box-sizing: border-box; }} | |
| body {{ | |
| margin: 0; | |
| color: var(--ink); | |
| background: var(--page); | |
| font-family: Arial, "Microsoft YaHei", sans-serif; | |
| }} | |
| main {{ width: min(1580px, 100%); margin: 0 auto; padding: 28px; }} | |
| header {{ margin: 0 0 18px; }} | |
| h1 {{ margin: 0 0 8px; font-size: 28px; letter-spacing: .01em; }} | |
| p {{ margin: 0; color: var(--muted); line-height: 1.65; }} | |
| .facts {{ display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }} | |
| .fact {{ | |
| padding: 6px 10px; | |
| border: 1px solid var(--line); | |
| border-radius: 999px; | |
| background: var(--panel); | |
| color: #45555c; | |
| font-size: 13px; | |
| }} | |
| section {{ | |
| margin-top: 18px; | |
| padding: 18px; | |
| border: 1px solid var(--line); | |
| border-radius: 14px; | |
| background: var(--panel); | |
| box-shadow: 0 3px 16px rgba(23, 43, 51, .05); | |
| }} | |
| h2 {{ margin: 0 0 6px; font-size: 18px; }} | |
| .plot {{ width: 100%; overflow: hidden; }} | |
| footer {{ padding: 16px 2px 0; color: var(--muted); font-size: 12px; }} | |
| @media (max-width: 720px) {{ | |
| main {{ padding: 14px; }} | |
| section {{ padding: 8px; border-radius: 10px; }} | |
| h1 {{ font-size: 22px; }} | |
| }} | |
| </style> | |
| </head> | |
| <body> | |
| <main> | |
| <header> | |
| <h1>识别轨迹与 RTK 轨迹</h1> | |
| <p>绿色为 RTK 轨迹,橙色为识别轨迹,蓝色菱形为车辆原点;小跨度方向采用最低显示厚度,坐标值保持不变。</p> | |
| <div class="facts"> | |
| <span class="fact">{len(trajectories)} 个航次</span> | |
| <span class="fact">{sample_count:,} 个配对点</span> | |
| <span class="fact">X 前向 · Y 左向 · Z 上向</span> | |
| </div> | |
| </header> | |
| <section> | |
| <h2>全部航次三维轨迹</h2> | |
| <div class="plot">{overview_html}</div> | |
| </section> | |
| <section> | |
| <h2>单航次三维查看</h2> | |
| <p>通过下拉菜单选择航次,可旋转、缩放并悬停查看坐标。</p> | |
| <div class="plot">{detail_html}</div> | |
| </section> | |
| <footer>数据:{source_name}</footer> | |
| </main> | |
| </body> | |
| </html> | |
| """ | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| output_path.write_text(document, encoding="utf-8") | |
| def main() -> None: | |
| args = parse_args() | |
| dataset_root = args.dataset_root.resolve() | |
| input_path = ( | |
| args.input.resolve() | |
| if args.input | |
| else dataset_root / "script" / "output" / "paired_errors.csv" | |
| ) | |
| output_path = ( | |
| args.output.resolve() | |
| if args.output | |
| else dataset_root / "script" / "output" / "trajectories.html" | |
| ) | |
| if input_path == output_path: | |
| raise ValueError("输入 CSV 与输出 HTML 不能是同一文件") | |
| trajectories = read_trajectories(input_path) | |
| write_html(output_path, input_path, trajectories) | |
| print(f"HTML: {output_path}") | |
| print( | |
| f"航次: {len(trajectories)}, " | |
| f"轨迹点: {sum(len(item.timestamp_us) for item in trajectories)}, " | |
| f"文件大小: {output_path.stat().st_size / 1024 / 1024:.2f} MiB" | |
| ) | |
| if __name__ == "__main__": | |
| main() | |