shuishen
22 hours ago 2ae460fc4a4c2419cf44329783d49a739e2a04ea
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
"""Generate small, auditable trajectory-analysis demo inputs."""
 
from __future__ import annotations
 
import argparse
import csv
import json
import math
import sys
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
 
 
def parse_args() -> argparse.Namespace:
    root = Path(__file__).resolve().parents[2]
    parser = argparse.ArgumentParser(description="Generate trajectory demo inputs.")
    parser.add_argument(
        "--output",
        type=Path,
        default=root / "shared" / "data" / "raw" / "15-trajectory-analysis",
    )
    parser.add_argument("--overwrite", action="store_true")
    return parser.parse_args()
 
 
def feature_collection(features: list[dict[str, Any]]) -> dict[str, Any]:
    return {"type": "FeatureCollection", "features": features}
 
 
def line_feature(track_id: str, coordinates: list[list[float]]) -> dict[str, Any]:
    return {
        "type": "Feature",
        "properties": {"track_id": track_id},
        "geometry": {"type": "LineString", "coordinates": coordinates},
    }
 
 
def write_json(path: Path, payload: dict[str, Any]) -> None:
    path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
 
 
def write_case(
    output_dir: Path,
    case_id: str,
    description: str,
    rows: list[dict[str, str]],
    routes: list[dict[str, Any]],
    zones: list[dict[str, Any]],
) -> None:
    csv_name = f"{case_id}_observations.csv"
    routes_name = f"{case_id}_routes.geojson"
    zones_name = f"{case_id}_zones.geojson"
    with (output_dir / csv_name).open("w", newline="", encoding="utf-8") as stream:
        writer = csv.DictWriter(
            stream,
            fieldnames=["track_id", "entity_type", "timestamp", "longitude", "latitude"],
        )
        writer.writeheader()
        writer.writerows(rows)
    write_json(output_dir / routes_name, feature_collection(routes))
    write_json(output_dir / zones_name, feature_collection(zones))
    write_json(
        output_dir / f"{case_id}.case.json",
        {
            "case_id": case_id,
            "description": description,
            "crs": "EPSG:4326",
            "observations": csv_name,
            "reference_routes": routes_name,
            "zones": zones_name,
        },
    )
 
 
def observation(
    track_id: str,
    entity_type: str,
    timestamp: datetime,
    longitude: float,
    latitude: float,
) -> dict[str, str]:
    return {
        "track_id": track_id,
        "entity_type": entity_type,
        "timestamp": timestamp.isoformat().replace("+00:00", "Z"),
        "longitude": f"{longitude:.7f}",
        "latitude": f"{latitude:.7f}",
    }
 
 
def build_normal_case() -> tuple[list[dict[str, str]], list[dict[str, Any]]]:
    started = datetime(2026, 8, 14, 1, 0, tzinfo=UTC)
    rows: list[dict[str, str]] = []
    routes: list[dict[str, Any]] = []
    for track_id, entity_type, base_lat in (
        ("drone-normal-01", "drone", 31.2000),
        ("vehicle-normal-01", "vehicle", 31.1995),
    ):
        coordinates: list[list[float]] = []
        for index in range(16):
            lon = 121.4700 + index * 0.00012
            lat = base_lat + math.sin(index / 2) * 0.000006
            coordinates.append([lon, base_lat])
            rows.append(observation(track_id, entity_type, started + timedelta(seconds=10 * index), lon, lat))
        routes.append(line_feature(track_id, coordinates))
    return rows, routes
 
 
def build_difficult_case() -> tuple[list[dict[str, str]], list[dict[str, Any]]]:
    started = datetime(2026, 8, 14, 2, 0, tzinfo=UTC)
    rows: list[dict[str, str]] = []
    routes: list[dict[str, Any]] = []
 
    car_route = [[121.4700 + index * 0.00010, 31.2000] for index in range(20)]
    routes.append(line_feature("vehicle-difficult-01", car_route))
    for index in range(20):
        if index <= 5:
            lon, lat = 121.4700 + index * 0.00010, 31.2000
        elif index <= 13:
            lon, lat = 121.4705, 31.2000
        else:
            lon, lat = 121.4705 + (index - 13) * 0.00010, 31.20055
        rows.append(
            observation(
                "vehicle-difficult-01", "vehicle", started + timedelta(seconds=10 * index), lon, lat
            )
        )
    # One duplicate is intentional: the analyzer must deduplicate it and report the cleanup.
    rows.append(observation("vehicle-difficult-01", "vehicle", started + timedelta(seconds=100), 121.4705, 31.2000))
 
    for track_id, base_lat, offset in (
        ("person-group-01", 31.19935, -0.000035),
        ("person-group-02", 31.19965, 0.000035),
    ):
        coordinates: list[list[float]] = []
        for index in range(13):
            lon = 121.4700 + index * 0.00011
            if 4 <= index <= 9:
                lat = 31.19950 + offset
            else:
                lat = base_lat
            coordinates.append([lon, lat])
            rows.append(observation(track_id, "person", started + timedelta(seconds=10 * index), lon, lat))
        routes.append(line_feature(track_id, coordinates))
 
    # Deliberately reverse the rows so sorting is exercised on the difficult case.
    rows.reverse()
    return rows, routes
 
 
def main() -> int:
    args = parse_args()
    output_dir = args.output.resolve()
    expected = output_dir / "normal.case.json"
    if expected.exists() and not args.overwrite:
        print(f"Demo inputs already exist: {output_dir}. Use --overwrite to replace them.", file=sys.stderr)
        return 2
    output_dir.mkdir(parents=True, exist_ok=True)
    zone = {
        "type": "Feature",
        "properties": {"zone_id": "restricted-01", "zone_type": "restricted"},
        "geometry": {
            "type": "Polygon",
            "coordinates": [[
                [121.47035, 31.20030],
                [121.47125, 31.20030],
                [121.47125, 31.20080],
                [121.47035, 31.20080],
                [121.47035, 31.20030],
            ]],
        },
    }
    normal_rows, normal_routes = build_normal_case()
    write_case(
        output_dir,
        "normal",
        "Two continuously moving tracks following their routes without rule events.",
        normal_rows,
        normal_routes,
        [zone],
    )
    difficult_rows, difficult_routes = build_difficult_case()
    write_case(
        output_dir,
        "difficult",
        "Unsorted observations with a duplicate, a stop, route deviation, restricted-zone entry and gathering.",
        difficult_rows,
        difficult_routes,
        [zone],
    )
    print(f"Generated normal and difficult demo inputs in {output_dir}")
    return 0
 
 
if __name__ == "__main__":
    raise SystemExit(main())