File size: 20,414 Bytes
8e6ff1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#!/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


@dataclass
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]

    @property
    def relative_time_s(self) -> list[float]:
        first = self.timestamp_us[0]
        return [(value - first) / 1e6 for value in self.timestamp_us]

    @property
    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()