File size: 29,343 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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
#!/usr/bin/env python3
"""Evaluate all 16 flights in the unified UAV tracking dataset."""

from __future__ import annotations

import argparse
import csv
import itertools
import json
import math
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Sequence

import numpy as np


WGS84_A_M = 6378137.0
WGS84_F = 1.0 / 298.257223563
WGS84_E2 = WGS84_F * (2.0 - WGS84_F)
MAX_RTK_GAP_S = 0.30
BOOTSTRAP_REPLICATES = 100_000
BOOTSTRAP_SEED = 20260723

SENSITIVITY_BINS = {
    "range_m": np.array([9.0, 15.0, 22.0, 28.0, 35.0, 60.0]),
    "azimuth_deg": np.array([-91.0, -30.0, -10.0, 5.0, 25.0, 70.0]),
    "elevation_deg": np.array([3.0, 12.0, 18.0, 25.0, 35.0, 55.0]),
}
LEVER_Z_SENSITIVITY_M = (0.20, 0.25, 0.30)


@dataclass
class FlightSpec:
    flight_id: str
    experiment_day: str
    vehicle_pose_id: str
    trajectory: str
    difficulty: str


@dataclass
class FlightData:
    spec: FlightSpec
    timestamp_us: np.ndarray
    tracking_v_m: np.ndarray
    antenna_w_m: np.ndarray
    tracking_rows: int
    eligible_rows: int
    rtk_fixed_rows: int
    rtk_total_gga_rows: int


@dataclass
class Evaluation:
    flight: FlightData
    reference_v_m: np.ndarray
    residual_v_m: np.ndarray
    metrics: dict[str, Any]


FLIGHTS: tuple[FlightSpec, ...] = (
    FlightSpec("flight_01", "2026-07-16", "vehicle_pose_0716", "稳定悬停", "easy"),
    FlightSpec(
        "flight_02",
        "2026-07-16",
        "vehicle_pose_0716",
        "低动态悬停(含垂直漂移)",
        "easy",
    ),
    FlightSpec(
        "flight_03",
        "2026-07-16",
        "vehicle_pose_0716",
        "垂直升降及两端悬停",
        "medium",
    ),
    FlightSpec("flight_04", "2026-07-16", "vehicle_pose_0716", "左向右横移", "medium"),
    FlightSpec("flight_05", "2026-07-16", "vehicle_pose_0716", "右向左横移", "medium"),
    FlightSpec(
        "flight_06",
        "2026-07-23",
        "vehicle_pose_0723",
        "径向接近后远离",
        "medium",
    ),
    FlightSpec(
        "flight_07",
        "2026-07-23",
        "vehicle_pose_0723",
        "纵向/径向往返",
        "medium",
    ),
    FlightSpec(
        "flight_08",
        "2026-07-16",
        "vehicle_pose_0716",
        "宽弧线连续转向",
        "hard",
    ),
    FlightSpec(
        "flight_09",
        "2026-07-23",
        "vehicle_pose_0723",
        "8 字/连续左右转向",
        "hard",
    ),
    FlightSpec("flight_10", "2026-07-16", "vehicle_pose_0716", "近距横向掠过", "hard"),
    FlightSpec("flight_11", "2026-07-23", "vehicle_pose_0723", "横向飞越", "hard"),
    FlightSpec(
        "flight_12",
        "2026-07-16",
        "vehicle_pose_0716",
        "自然失跟与重捕获",
        "hard",
    ),
    FlightSpec(
        "flight_13",
        "2026-07-16",
        "vehicle_pose_0716",
        "近距复杂背景连续跟踪",
        "hard",
    ),
    FlightSpec(
        "flight_14",
        "2026-07-23",
        "vehicle_pose_0723",
        "严格复杂背景横移/缓弧",
        "hard",
    ),
    FlightSpec(
        "flight_15",
        "2026-07-23",
        "vehicle_pose_0723",
        "复杂背景重复",
        "hard",
    ),
    FlightSpec(
        "flight_16",
        "2026-07-23",
        "vehicle_pose_0723",
        "远距悬停及缓慢横移",
        "hard",
    ),
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "dataset_root",
        nargs="?",
        type=Path,
        default=Path(__file__).resolve().parents[1],
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        help="Default: DATASET_ROOT/script/output",
    )
    return parser.parse_args()


def read_json(path: Path) -> dict[str, Any]:
    with path.open("r", encoding="utf-8") as stream:
        return json.load(stream)


def write_json(path: Path, payload: Any) -> None:
    path.write_text(
        json.dumps(json_ready(payload), ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )


def write_csv(path: Path, rows: Sequence[dict[str, Any]]) -> None:
    if not rows:
        path.write_text("", encoding="utf-8")
        return
    fields: list[str] = []
    for row in rows:
        for key in row:
            if key not in fields:
                fields.append(key)
    with path.open("w", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)


def json_ready(value: Any) -> Any:
    if isinstance(value, Path):
        return str(value)
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, np.generic):
        return value.item()
    if isinstance(value, float) and not math.isfinite(value):
        return None
    if isinstance(value, dict):
        return {str(key): json_ready(item) for key, item in value.items()}
    if isinstance(value, (list, tuple)):
        return [json_ready(item) for item in value]
    return value


def exactly_one(paths: Iterable[Path], description: str) -> Path:
    matches = sorted(paths)
    if len(matches) != 1:
        raise ValueError(
            f"{description} should have exactly one match; found {len(matches)}: "
            f"{matches}"
        )
    return matches[0]


def geodetic_to_ecef(
    latitude_deg: np.ndarray,
    longitude_deg: np.ndarray,
    altitude_m: np.ndarray,
) -> np.ndarray:
    latitude = np.deg2rad(latitude_deg)
    longitude = np.deg2rad(longitude_deg)
    sin_latitude = np.sin(latitude)
    normal = WGS84_A_M / np.sqrt(1.0 - WGS84_E2 * sin_latitude * sin_latitude)
    return np.column_stack(
        (
            (normal + altitude_m) * np.cos(latitude) * np.cos(longitude),
            (normal + altitude_m) * np.cos(latitude) * np.sin(longitude),
            (normal * (1.0 - WGS84_E2) + altitude_m) * sin_latitude,
        )
    )


def enu_rotation(latitude_deg: float, longitude_deg: float) -> np.ndarray:
    latitude = math.radians(latitude_deg)
    longitude = math.radians(longitude_deg)
    return np.array(
        [
            [-math.sin(longitude), math.cos(longitude), 0.0],
            [
                -math.sin(latitude) * math.cos(longitude),
                -math.sin(latitude) * math.sin(longitude),
                math.cos(latitude),
            ],
            [
                math.cos(latitude) * math.cos(longitude),
                math.cos(latitude) * math.sin(longitude),
                math.sin(latitude),
            ],
        ],
        dtype=np.float64,
    )


def geodetic_to_enu(
    latitude_deg: np.ndarray,
    longitude_deg: np.ndarray,
    altitude_m: np.ndarray,
    origin: tuple[float, float, float],
) -> np.ndarray:
    latitude_0, longitude_0, altitude_0 = origin
    ecef_0 = geodetic_to_ecef(
        np.array([latitude_0]),
        np.array([longitude_0]),
        np.array([altitude_0]),
    )[0]
    ecef = geodetic_to_ecef(latitude_deg, longitude_deg, altitude_m)
    return (enu_rotation(latitude_0, longitude_0) @ (ecef - ecef_0).T).T


def read_rtk(
    path: Path,
    origin: tuple[float, float, float],
) -> tuple[np.ndarray, np.ndarray, int, int]:
    rows: list[tuple[int, float, float, float]] = []
    gga_rows = 0
    fixed_rows = 0
    with path.open("r", encoding="utf-8", newline="") as stream:
        for row in csv.reader(stream):
            if not row or row[0] != "GGA":
                continue
            gga_rows += 1
            if len(row) < 8 or row[2] != "4":
                continue
            fixed_rows += 1
            try:
                item = (int(row[1]), float(row[5]), float(row[6]), float(row[7]))
            except ValueError:
                continue
            if all(math.isfinite(float(value)) for value in item):
                rows.append(item)
    if len(rows) < 2:
        raise ValueError(f"Not enough fixed GGA samples: {path}")
    data = np.asarray(rows, dtype=np.float64)
    order = np.argsort(data[:, 0], kind="stable")
    data = data[order]
    time_ms, indices = np.unique(data[:, 0].astype(np.int64), return_index=True)
    data = data[indices]
    position_w = geodetic_to_enu(data[:, 1], data[:, 2], data[:, 3], origin)
    return time_ms * 1000, position_w, gga_rows, fixed_rows


def read_tracking(
    path: Path,
) -> tuple[np.ndarray, np.ndarray, int, int]:
    time_us: list[int] = []
    positions: list[list[float]] = []
    total_rows = 0
    eligible_rows = 0
    with path.open("r", encoding="utf-8", newline="") as stream:
        for row in csv.DictReader(stream):
            total_rows += 1
            if not (
                row.get("lifecycle", "").strip().lower() == "confirmed"
                and row.get("state_valid") == "1"
                and row.get("numerical_ok") == "1"
                and row.get("command_valid") == "1"
            ):
                continue
            try:
                timestamp = int(row["frame_timestamp_us"])
                position = [
                    float(row["px"]),
                    float(row["py"]),
                    float(row["pz"]),
                ]
            except (KeyError, ValueError):
                continue
            if timestamp <= 0 or not all(math.isfinite(value) for value in position):
                continue
            time_us.append(timestamp)
            positions.append(position)
            eligible_rows += 1
    if not time_us:
        raise ValueError(f"No eligible tracking states: {path}")
    times = np.asarray(time_us, dtype=np.int64)
    points = np.asarray(positions, dtype=np.float64)
    order = np.argsort(times, kind="stable")
    times = times[order]
    points = points[order]
    unique_times, indices = np.unique(times, return_index=True)
    return unique_times, points[indices], total_rows, eligible_rows


def interpolate_rtk(
    query_time_us: np.ndarray,
    rtk_time_us: np.ndarray,
    rtk_position_w_m: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    right = np.searchsorted(rtk_time_us, query_time_us, side="right")
    valid = (right > 0) & (right < len(rtk_time_us))
    selected = np.flatnonzero(valid)
    right_selected = right[selected]
    left_selected = right_selected - 1
    gap_us = rtk_time_us[right_selected] - rtk_time_us[left_selected]
    valid_gap = (gap_us > 0) & (gap_us <= int(round(MAX_RTK_GAP_S * 1e6)))
    selected = selected[valid_gap]
    right_selected = right_selected[valid_gap]
    left_selected = left_selected[valid_gap]
    gap_us = gap_us[valid_gap]
    alpha = (
        query_time_us[selected] - rtk_time_us[left_selected]
    ) / gap_us.astype(np.float64)
    position = rtk_position_w_m[left_selected] + alpha[:, None] * (
        rtk_position_w_m[right_selected] - rtk_position_w_m[left_selected]
    )
    mask = np.zeros(len(query_time_us), dtype=bool)
    mask[selected] = True
    return mask, position


def load_flight(
    dataset_root: Path,
    spec: FlightSpec,
    origin: tuple[float, float, float],
) -> FlightData:
    directory = dataset_root / spec.flight_id
    tracking_path = exactly_one(
        (directory / "tracking").glob("tracking_state_*.csv"),
        f"{spec.flight_id} tracking_state",
    )
    rtk_path = directory / "drone_rtk.csv"
    if not rtk_path.is_file():
        raise FileNotFoundError(rtk_path)
    track_time, tracking, tracking_rows, eligible_rows = read_tracking(tracking_path)
    rtk_time, rtk_w, gga_rows, fixed_rows = read_rtk(rtk_path, origin)
    mask, antenna_w = interpolate_rtk(track_time, rtk_time, rtk_w)
    if not np.any(mask):
        raise ValueError(f"No tracking/RTK pairs: {spec.flight_id}")
    return FlightData(
        spec=spec,
        timestamp_us=track_time[mask],
        tracking_v_m=tracking[mask],
        antenna_w_m=antenna_w,
        tracking_rows=tracking_rows,
        eligible_rows=eligible_rows,
        rtk_fixed_rows=fixed_rows,
        rtk_total_gga_rows=gga_rows,
    )


def reference_from_antenna(
    flight: FlightData,
    calibration: dict[str, Any],
    lever_z_m: float | None = None,
) -> np.ndarray:
    transform = np.asarray(
        calibration["transforms"]["T_W_V"][flight.spec.vehicle_pose_id],
        dtype=np.float64,
    )
    rotation_w_v = transform[:3, :3]
    translation_w_v = transform[:3, 3]
    lever_u = np.asarray(
        calibration["extrinsics_m"]["uav_rtk_antenna_in_u"],
        dtype=np.float64,
    ).copy()
    if lever_z_m is not None:
        lever_u[2] = lever_z_m
    antenna_v = (
        rotation_w_v.T @ (flight.antenna_w_m - translation_w_v).T
    ).T
    # UAV attitude was not logged. U and V axes are treated as parallel for
    # this small lever; the dominant vertical term is robust for approximately
    # level flight.
    return antenna_v - lever_u


def metric_summary(residual: np.ndarray) -> dict[str, float]:
    error_3d = np.linalg.norm(residual, axis=1)
    horizontal = np.linalg.norm(residual[:, :2], axis=1)
    vertical = np.abs(residual[:, 2])
    return {
        "error_3d_mean_m": float(np.mean(error_3d)),
        "error_3d_rmse_m": float(np.sqrt(np.mean(error_3d**2))),
        "error_3d_median_m": float(np.median(error_3d)),
        "error_3d_p95_m": float(np.percentile(error_3d, 95)),
        "error_3d_max_m": float(np.max(error_3d)),
        "horizontal_rmse_m": float(np.sqrt(np.mean(horizontal**2))),
        "horizontal_p95_m": float(np.percentile(horizontal, 95)),
        "vertical_rmse_m": float(np.sqrt(np.mean(vertical**2))),
        "vertical_p95_m": float(np.percentile(vertical, 95)),
        "x_mean_error_m": float(np.mean(residual[:, 0])),
        "y_mean_error_m": float(np.mean(residual[:, 1])),
        "z_mean_error_m": float(np.mean(residual[:, 2])),
        "error_ge_1m_ratio": float(np.mean(error_3d >= 1.0)),
        "error_ge_1_5m_ratio": float(np.mean(error_3d >= 1.5)),
        "error_ge_2m_ratio": float(np.mean(error_3d >= 2.0)),
    }


def evaluate_flight(
    flight: FlightData,
    calibration: dict[str, Any],
    lever_z_m: float | None = None,
) -> Evaluation:
    reference = reference_from_antenna(flight, calibration, lever_z_m)
    residual = flight.tracking_v_m - reference
    metrics: dict[str, Any] = {
        "flight_id": flight.spec.flight_id,
        "experiment_day": flight.spec.experiment_day,
        "vehicle_pose_id": flight.spec.vehicle_pose_id,
        "trajectory": flight.spec.trajectory,
        "difficulty": flight.spec.difficulty,
        "tracking_rows": flight.tracking_rows,
        "eligible_tracking_rows": flight.eligible_rows,
        "paired_rows": len(flight.timestamp_us),
        "eligible_coverage_ratio": len(flight.timestamp_us) / flight.eligible_rows,
        "rtk_fixed_rows": flight.rtk_fixed_rows,
        "rtk_total_gga_rows": flight.rtk_total_gga_rows,
        "rtk_fixed_ratio": flight.rtk_fixed_rows / flight.rtk_total_gga_rows,
    }
    metrics.update(metric_summary(residual))
    return Evaluation(flight, reference, residual, metrics)


def aggregate(evaluations: Sequence[Evaluation]) -> dict[str, Any]:
    if not evaluations:
        raise ValueError("Cannot aggregate an empty evaluation set")
    metric_keys = (
        "error_3d_mean_m",
        "error_3d_rmse_m",
        "error_3d_median_m",
        "error_3d_p95_m",
        "horizontal_rmse_m",
        "horizontal_p95_m",
        "vertical_rmse_m",
        "vertical_p95_m",
    )
    paired_rows = sum(len(item.flight.timestamp_us) for item in evaluations)
    output: dict[str, Any] = {
        "flight_count": len(evaluations),
        "paired_rows": paired_rows,
        "aggregation": "unweighted macro mean of per-flight metrics",
    }
    for key in metric_keys:
        output[f"macro_{key}"] = float(
            np.mean([float(item.metrics[key]) for item in evaluations])
        )
    output["micro_error_3d_rmse_m"] = math.sqrt(
        sum(
            len(item.flight.timestamp_us)
            * float(item.metrics["error_3d_rmse_m"]) ** 2
            for item in evaluations
        )
        / paired_rows
    )
    return output


def frame_rows(evaluations: Sequence[Evaluation]) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for item in evaluations:
        reference = item.reference_v_m
        residual = item.residual_v_m
        error_3d = np.linalg.norm(residual, axis=1)
        horizontal_error = np.linalg.norm(residual[:, :2], axis=1)
        horizontal_range = np.linalg.norm(reference[:, :2], axis=1)
        range_m = np.linalg.norm(reference, axis=1)
        azimuth = np.degrees(np.arctan2(reference[:, 1], reference[:, 0]))
        elevation = np.degrees(np.arctan2(reference[:, 2], horizontal_range))
        for index in range(len(reference)):
            rows.append(
                {
                    "flight_id": item.flight.spec.flight_id,
                    "experiment_day": item.flight.spec.experiment_day,
                    "timestamp_us": int(item.flight.timestamp_us[index]),
                    "tracking_x_v_m": float(item.flight.tracking_v_m[index, 0]),
                    "tracking_y_v_m": float(item.flight.tracking_v_m[index, 1]),
                    "tracking_z_v_m": float(item.flight.tracking_v_m[index, 2]),
                    "reference_x_v_m": float(reference[index, 0]),
                    "reference_y_v_m": float(reference[index, 1]),
                    "reference_z_v_m": float(reference[index, 2]),
                    "error_x_m": float(residual[index, 0]),
                    "error_y_m": float(residual[index, 1]),
                    "error_z_m": float(residual[index, 2]),
                    "error_3d_m": float(error_3d[index]),
                    "error_horizontal_m": float(horizontal_error[index]),
                    "error_vertical_abs_m": float(abs(residual[index, 2])),
                    "range_m": float(range_m[index]),
                    "azimuth_deg": float(azimuth[index]),
                    "elevation_deg": float(elevation[index]),
                    "relative_error_percent": float(
                        100.0 * error_3d[index] / range_m[index]
                    ),
                }
            )
    return rows


def bootstrap_mean_ci(values: np.ndarray, rng: np.random.Generator) -> tuple[float, float]:
    if len(values) == 1:
        return float(values[0]), float(values[0])
    indices = rng.integers(
        0,
        len(values),
        size=(BOOTSTRAP_REPLICATES, len(values)),
    )
    distribution = np.mean(values[indices], axis=1)
    low, high = np.percentile(distribution, [2.5, 97.5])
    return float(low), float(high)


def sensitivity_rows(
    evaluations: Sequence[Evaluation],
) -> list[dict[str, Any]]:
    rng = np.random.default_rng(BOOTSTRAP_SEED)
    prepared: list[dict[str, Any]] = []
    for item in evaluations:
        reference = item.reference_v_m
        residual = item.residual_v_m
        horizontal_range = np.linalg.norm(reference[:, :2], axis=1)
        prepared.append(
            {
                "flight_id": item.flight.spec.flight_id,
                "error_3d": np.linalg.norm(residual, axis=1),
                "horizontal": np.linalg.norm(residual[:, :2], axis=1),
                "vertical": np.abs(residual[:, 2]),
                "range_m": np.linalg.norm(reference, axis=1),
                "azimuth_deg": np.degrees(
                    np.arctan2(reference[:, 1], reference[:, 0])
                ),
                "elevation_deg": np.degrees(
                    np.arctan2(reference[:, 2], horizontal_range)
                ),
            }
        )
    output: list[dict[str, Any]] = []
    for variable, edges in SENSITIVITY_BINS.items():
        all_values = np.concatenate([item[variable] for item in prepared])
        if np.any((all_values < edges[0]) | (all_values > edges[-1])):
            raise ValueError(
                f"{variable} outside the specified bins: "
                f"[{all_values.min()}, {all_values.max()}]"
            )
        for bin_index in range(len(edges) - 1):
            per_flight: list[dict[str, float]] = []
            frame_count = 0
            for item in prepared:
                values = item[variable]
                mask = (values >= edges[bin_index]) & (
                    (values < edges[bin_index + 1])
                    if bin_index < len(edges) - 2
                    else (values <= edges[bin_index + 1])
                )
                if not np.any(mask):
                    continue
                frame_count += int(np.count_nonzero(mask))
                error_3d = item["error_3d"][mask]
                horizontal = item["horizontal"][mask]
                vertical = item["vertical"][mask]
                per_flight.append(
                    {
                        "rmse_3d": float(np.sqrt(np.mean(error_3d**2))),
                        "p95_3d": float(np.percentile(error_3d, 95)),
                        "rmse_horizontal": float(
                            np.sqrt(np.mean(horizontal**2))
                        ),
                        "p95_horizontal": float(
                            np.percentile(horizontal, 95)
                        ),
                        "rmse_vertical": float(np.sqrt(np.mean(vertical**2))),
                        "p95_vertical": float(np.percentile(vertical, 95)),
                    }
                )
            if not per_flight:
                raise ValueError(f"Empty sensitivity bin: {variable}/{bin_index}")
            rmse_values = np.asarray([item["rmse_3d"] for item in per_flight])
            low, high = bootstrap_mean_ci(rmse_values, rng)

            def macro(key: str) -> float:
                return float(np.mean([item[key] for item in per_flight]))

            output.append(
                {
                    "variable": variable,
                    "bin_index": bin_index + 1,
                    "lower": float(edges[bin_index]),
                    "upper": float(edges[bin_index + 1]),
                    "frame_count": frame_count,
                    "flight_count": len(per_flight),
                    "error_3d_rmse_m": macro("rmse_3d"),
                    "error_3d_rmse_ci95_low_m": low,
                    "error_3d_rmse_ci95_high_m": high,
                    "error_3d_p95_m": macro("p95_3d"),
                    "horizontal_rmse_m": macro("rmse_horizontal"),
                    "horizontal_p95_m": macro("p95_horizontal"),
                    "vertical_rmse_m": macro("rmse_vertical"),
                    "vertical_p95_m": macro("p95_vertical"),
                }
            )
    return output


def date_comparison(
    evaluations: Sequence[Evaluation],
) -> dict[str, Any]:
    days = sorted({item.flight.spec.experiment_day for item in evaluations})
    if len(days) != 2:
        raise ValueError(f"Expected exactly two acquisition days: {days}")
    first = np.asarray(
        [
            item.metrics["error_3d_rmse_m"]
            for item in evaluations
            if item.flight.spec.experiment_day == days[0]
        ],
        dtype=np.float64,
    )
    second = np.asarray(
        [
            item.metrics["error_3d_rmse_m"]
            for item in evaluations
            if item.flight.spec.experiment_day == days[1]
        ],
        dtype=np.float64,
    )
    observed = float(np.mean(first) - np.mean(second))
    rng = np.random.default_rng(BOOTSTRAP_SEED)
    first_boot = first[
        rng.integers(
            0,
            len(first),
            size=(BOOTSTRAP_REPLICATES, len(first)),
        )
    ].mean(axis=1)
    second_boot = second[
        rng.integers(
            0,
            len(second),
            size=(BOOTSTRAP_REPLICATES, len(second)),
        )
    ].mean(axis=1)
    low, high = np.percentile(first_boot - second_boot, [2.5, 97.5])
    combined = np.concatenate((first, second))
    permutation_differences: list[float] = []
    for indices in itertools.combinations(range(len(combined)), len(first)):
        mask = np.zeros(len(combined), dtype=bool)
        mask[list(indices)] = True
        permutation_differences.append(
            float(np.mean(combined[mask]) - np.mean(combined[~mask]))
        )
    permutation = np.asarray(permutation_differences)
    p_two_sided = (
        np.count_nonzero(np.abs(permutation) >= abs(observed)) - 1
    ) / (len(permutation) - 1)
    return {
        "unit": "flight",
        "metric": "per-flight 3D RMSE",
        "first_day": days[0],
        "second_day": days[1],
        "first_day_flight_count": len(first),
        "second_day_flight_count": len(second),
        "first_day_macro_rmse_m": float(np.mean(first)),
        "second_day_macro_rmse_m": float(np.mean(second)),
        "difference_first_minus_second_m": observed,
        "bootstrap_95_interval_m": [float(low), float(high)],
        "bootstrap_replicates": BOOTSTRAP_REPLICATES,
        "bootstrap_seed": BOOTSTRAP_SEED,
        "exact_permutation_two_sided_p": float(p_two_sided),
        "interpretation": (
            "Descriptive flight-level comparison; trajectories are not paired "
            "between acquisition days."
        ),
    }


def lever_sensitivity(
    flights: Sequence[FlightData],
    calibration: dict[str, Any],
) -> list[dict[str, Any]]:
    output: list[dict[str, Any]] = []
    for lever_z in LEVER_Z_SENSITIVITY_M:
        evaluations = [
            evaluate_flight(flight, calibration, lever_z_m=lever_z)
            for flight in flights
        ]
        overall = aggregate(evaluations)
        by_day = {
            day: aggregate(
                [
                    item
                    for item in evaluations
                    if item.flight.spec.experiment_day == day
                ]
            )
            for day in sorted(
                {item.flight.spec.experiment_day for item in evaluations}
            )
        }
        output.append(
            {
                "uav_rtk_antenna_z_in_u_m": lever_z,
                "all_macro_3d_rmse_m": overall["macro_error_3d_rmse_m"],
                "all_macro_3d_p95_m": overall["macro_error_3d_p95_m"],
                "all_macro_horizontal_rmse_m": overall[
                    "macro_horizontal_rmse_m"
                ],
                "all_macro_vertical_rmse_m": overall[
                    "macro_vertical_rmse_m"
                ],
                **{
                    f"{day}_macro_3d_rmse_m": summary[
                        "macro_error_3d_rmse_m"
                    ]
                    for day, summary in by_day.items()
                },
            }
        )
    return output


def main() -> None:
    args = parse_args()
    dataset_root = args.dataset_root.resolve()
    script_dir = Path(__file__).resolve().parent
    output_dir = (
        args.output_dir.resolve()
        if args.output_dir
        else script_dir / "output"
    )
    output_dir.mkdir(parents=True, exist_ok=True)
    calibration = read_json(script_dir / "calibration.json")
    world = calibration["frames"]["world"]
    origin = (
        float(world["origin_llh_gga"]["latitude_deg"]),
        float(world["origin_llh_gga"]["longitude_deg"]),
        float(world["origin_llh_gga"]["altitude_m"]),
    )
    flights = [load_flight(dataset_root, spec, origin) for spec in FLIGHTS]
    evaluations = [
        evaluate_flight(flight, calibration)
        for flight in flights
    ]
    per_flight = [item.metrics for item in evaluations]
    overall = aggregate(evaluations)
    by_day = {
        day: aggregate(
            [
                item
                for item in evaluations
                if item.flight.spec.experiment_day == day
            ]
        )
        for day in sorted({item.flight.spec.experiment_day for item in evaluations})
    }
    summary = {
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "method": {
            "state_selection": (
                "lifecycle=confirmed && state_valid=1 && numerical_ok=1 "
                "&& command_valid=1"
            ),
            "rtk_quality": 4,
            "rtk_interpolation": "bracketing linear",
            "maximum_rtk_gap_s": MAX_RTK_GAP_S,
            "rtk_extrapolation": False,
        },
        "overall": overall,
        "by_day": by_day,
        "date_comparison": date_comparison(evaluations),
    }
    write_json(output_dir / "accuracy_summary.json", summary)
    write_csv(output_dir / "accuracy_by_flight.csv", per_flight)
    write_csv(output_dir / "paired_errors.csv", frame_rows(evaluations))
    write_csv(
        output_dir / "range_azimuth_elevation_sensitivity.csv",
        sensitivity_rows(evaluations),
    )
    write_csv(
        output_dir / "uav_lever_arm_sensitivity.csv",
        lever_sensitivity(flights, calibration),
    )
    print(
        json.dumps(
            {
                "flight_count": overall["flight_count"],
                "paired_rows": overall["paired_rows"],
                "macro_3d_rmse_m": overall["macro_error_3d_rmse_m"],
                "macro_3d_p95_m": overall["macro_error_3d_p95_m"],
                "output_dir": str(output_dir),
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()