| |
| """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 |
| |
| |
| |
| 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() |
|
|