|
| 1 | +""" |
| 2 | +Pytest tests for tp_lib path-calculation and detections bindings. |
| 3 | +
|
| 4 | +Tests the Python API for: |
| 5 | +- PathConfig construction & validation |
| 6 | +- calculate_train_path on a tiny synthetic network |
| 7 | +- PreparedDetections / prepare_detections workflow |
| 8 | +- detection_provenance(), warnings, mode |
| 9 | +""" |
| 10 | + |
| 11 | +import json |
| 12 | +import pytest |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | + |
| 16 | +try: |
| 17 | + from tp_lib import ( |
| 18 | + calculate_train_path, |
| 19 | + PathConfig, |
| 20 | + PathResult, |
| 21 | + TrainPath, |
| 22 | + AssociatedNetElement, |
| 23 | + prepare_detections, |
| 24 | + PreparedDetections, |
| 25 | + ProjectedPosition, |
| 26 | + ) |
| 27 | + TP_LIB_AVAILABLE = True |
| 28 | +except ImportError: |
| 29 | + TP_LIB_AVAILABLE = False |
| 30 | + |
| 31 | + |
| 32 | +pytestmark = pytest.mark.skipif( |
| 33 | + not TP_LIB_AVAILABLE, reason="tp_lib extension not built" |
| 34 | +) |
| 35 | + |
| 36 | + |
| 37 | +# ============================================================================ |
| 38 | +# Fixtures: a tiny two-segment network with GNSS trace running along it |
| 39 | +# ============================================================================ |
| 40 | + |
| 41 | +# Coordinates along ~50.85N, 4.35E in Brussels area. |
| 42 | +# Two adjacent LineStrings forming a single corridor: |
| 43 | +# NE001: (4.350, 50.850) -> (4.355, 50.850) |
| 44 | +# NE002: (4.355, 50.850) -> (4.360, 50.850) |
| 45 | +# Connected end-to-end via a NetRelation. |
| 46 | + |
| 47 | + |
| 48 | +@pytest.fixture |
| 49 | +def network_geojson(tmp_path): |
| 50 | + path = tmp_path / "network.geojson" |
| 51 | + data = { |
| 52 | + "type": "FeatureCollection", |
| 53 | + "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, |
| 54 | + "features": [ |
| 55 | + { |
| 56 | + "type": "Feature", |
| 57 | + "properties": {"id": "NE001", "kind": "netelement"}, |
| 58 | + "geometry": { |
| 59 | + "type": "LineString", |
| 60 | + "coordinates": [[4.350, 50.850], [4.355, 50.850]], |
| 61 | + }, |
| 62 | + }, |
| 63 | + { |
| 64 | + "type": "Feature", |
| 65 | + "properties": {"id": "NE002", "kind": "netelement"}, |
| 66 | + "geometry": { |
| 67 | + "type": "LineString", |
| 68 | + "coordinates": [[4.355, 50.850], [4.360, 50.850]], |
| 69 | + }, |
| 70 | + }, |
| 71 | + { |
| 72 | + "type": "Feature", |
| 73 | + "properties": { |
| 74 | + "id": "NR001", |
| 75 | + "type": "netrelation", |
| 76 | + "navigability": "both", |
| 77 | + "netelementA": "NE001", |
| 78 | + "positionOnA": 1, |
| 79 | + "netelementB": "NE002", |
| 80 | + "positionOnB": 0, |
| 81 | + }, |
| 82 | + "geometry": None, |
| 83 | + }, |
| 84 | + ], |
| 85 | + } |
| 86 | + path.write_text(json.dumps(data)) |
| 87 | + return str(path) |
| 88 | + |
| 89 | + |
| 90 | +@pytest.fixture |
| 91 | +def gnss_csv(tmp_path): |
| 92 | + """Five GNSS samples along the corridor, 5s apart.""" |
| 93 | + path = tmp_path / "gnss.csv" |
| 94 | + lines = ["latitude,longitude,timestamp"] |
| 95 | + # Move from x=4.3505 to 4.3595 in 5 steps |
| 96 | + timestamps = [ |
| 97 | + "2025-12-09T14:30:00+01:00", |
| 98 | + "2025-12-09T14:30:05+01:00", |
| 99 | + "2025-12-09T14:30:10+01:00", |
| 100 | + "2025-12-09T14:30:15+01:00", |
| 101 | + "2025-12-09T14:30:20+01:00", |
| 102 | + ] |
| 103 | + xs = [4.3505, 4.3525, 4.3550, 4.3575, 4.3595] |
| 104 | + for x, ts in zip(xs, timestamps): |
| 105 | + lines.append(f"50.850000,{x},{ts}") |
| 106 | + path.write_text("\n".join(lines) + "\n") |
| 107 | + return str(path) |
| 108 | + |
| 109 | + |
| 110 | +@pytest.fixture |
| 111 | +def punctual_detection_csv(tmp_path): |
| 112 | + """Punctual detection anchored to NE001 at intrinsic 0.5, mid-trace.""" |
| 113 | + path = tmp_path / "detections.csv" |
| 114 | + path.write_text( |
| 115 | + "id,timestamp,netelement_id,intrinsic\n" |
| 116 | + "D1,2025-12-09T14:30:10+01:00,NE001,0.5\n" |
| 117 | + ) |
| 118 | + return str(path) |
| 119 | + |
| 120 | + |
| 121 | +# ============================================================================ |
| 122 | +# PathConfig |
| 123 | +# ============================================================================ |
| 124 | + |
| 125 | + |
| 126 | +def test_path_config_defaults(): |
| 127 | + cfg = PathConfig() |
| 128 | + assert cfg.distance_scale == 10.0 |
| 129 | + assert cfg.heading_scale == 2.0 |
| 130 | + assert cfg.cutoff_distance == 500.0 |
| 131 | + assert cfg.heading_cutoff == 10.0 |
| 132 | + assert cfg.probability_threshold == 0.02 |
| 133 | + assert cfg.max_candidates == 3 |
| 134 | + assert cfg.path_only is False |
| 135 | + assert cfg.beta == 50.0 |
| 136 | + assert cfg.edge_zone_distance == 50.0 |
| 137 | + assert cfg.turn_scale == 30.0 |
| 138 | + assert cfg.detection_cutoff_distance == 2.5 |
| 139 | + assert cfg.resampling_distance is None |
| 140 | + |
| 141 | + |
| 142 | +def test_path_config_custom(): |
| 143 | + cfg = PathConfig( |
| 144 | + distance_scale=20.0, |
| 145 | + heading_scale=5.0, |
| 146 | + cutoff_distance=100.0, |
| 147 | + max_candidates=5, |
| 148 | + probability_threshold=0.05, |
| 149 | + ) |
| 150 | + assert cfg.distance_scale == 20.0 |
| 151 | + assert cfg.heading_scale == 5.0 |
| 152 | + assert cfg.cutoff_distance == 100.0 |
| 153 | + assert cfg.max_candidates == 5 |
| 154 | + assert cfg.probability_threshold == 0.05 |
| 155 | + |
| 156 | + |
| 157 | +def test_path_config_repr(): |
| 158 | + cfg = PathConfig() |
| 159 | + r = repr(cfg) |
| 160 | + assert "PathConfig" in r |
| 161 | + assert "distance_scale" in r |
| 162 | + |
| 163 | + |
| 164 | +# ============================================================================ |
| 165 | +# calculate_train_path — happy path |
| 166 | +# ============================================================================ |
| 167 | + |
| 168 | + |
| 169 | +def test_calculate_train_path_basic(gnss_csv, network_geojson): |
| 170 | + result = calculate_train_path( |
| 171 | + gnss_file=gnss_csv, |
| 172 | + gnss_crs="EPSG:4326", |
| 173 | + network_file=network_geojson, |
| 174 | + ) |
| 175 | + assert isinstance(result, PathResult) |
| 176 | + assert result.mode in ("topology_based", "fallback_independent") |
| 177 | + assert isinstance(result.warnings, list) |
| 178 | + assert isinstance(result.projected_positions, list) |
| 179 | + |
| 180 | + # Path should be found |
| 181 | + assert result.path is not None |
| 182 | + assert isinstance(result.path, TrainPath) |
| 183 | + assert 0.0 <= result.path.overall_probability <= 1.0 |
| 184 | + |
| 185 | + # Segments |
| 186 | + segs = result.path.segments |
| 187 | + assert len(segs) >= 1 |
| 188 | + for s in segs: |
| 189 | + assert isinstance(s, AssociatedNetElement) |
| 190 | + assert s.netelement_id in ("NE001", "NE002") |
| 191 | + assert 0.0 <= s.start_intrinsic <= 1.0 |
| 192 | + assert 0.0 <= s.end_intrinsic <= 1.0 |
| 193 | + assert 0.0 <= s.probability <= 1.0 |
| 194 | + |
| 195 | + # Projected positions: count depends on internal filtering; we only |
| 196 | + # require that whatever is returned is shaped correctly. |
| 197 | + assert isinstance(result.projected_positions, list) |
| 198 | + for pos in result.projected_positions: |
| 199 | + assert isinstance(pos, ProjectedPosition) |
| 200 | + assert pos.netelement_id in ("NE001", "NE002") |
| 201 | + |
| 202 | + |
| 203 | +def test_calculate_train_path_with_custom_config(gnss_csv, network_geojson): |
| 204 | + cfg = PathConfig( |
| 205 | + cutoff_distance=200.0, |
| 206 | + max_candidates=2, |
| 207 | + probability_threshold=0.01, |
| 208 | + ) |
| 209 | + result = calculate_train_path( |
| 210 | + gnss_file=gnss_csv, |
| 211 | + gnss_crs="EPSG:4326", |
| 212 | + network_file=network_geojson, |
| 213 | + config=cfg, |
| 214 | + ) |
| 215 | + assert isinstance(result, PathResult) |
| 216 | + |
| 217 | + |
| 218 | +def test_path_result_repr_and_provenance(gnss_csv, network_geojson): |
| 219 | + result = calculate_train_path( |
| 220 | + gnss_file=gnss_csv, |
| 221 | + gnss_crs="EPSG:4326", |
| 222 | + network_file=network_geojson, |
| 223 | + ) |
| 224 | + r = repr(result) |
| 225 | + assert "PathResult" in r |
| 226 | + # No detections supplied → empty provenance |
| 227 | + prov = result.detection_provenance() |
| 228 | + assert isinstance(prov, list) |
| 229 | + assert prov == [] |
| 230 | + |
| 231 | + |
| 232 | +# ============================================================================ |
| 233 | +# calculate_train_path — error cases |
| 234 | +# ============================================================================ |
| 235 | + |
| 236 | + |
| 237 | +def test_calculate_train_path_missing_gnss(network_geojson): |
| 238 | + with pytest.raises(IOError): |
| 239 | + calculate_train_path( |
| 240 | + gnss_file="/nonexistent/gnss.csv", |
| 241 | + gnss_crs="EPSG:4326", |
| 242 | + network_file=network_geojson, |
| 243 | + ) |
| 244 | + |
| 245 | + |
| 246 | +def test_calculate_train_path_missing_network(gnss_csv): |
| 247 | + with pytest.raises(IOError): |
| 248 | + calculate_train_path( |
| 249 | + gnss_file=gnss_csv, |
| 250 | + gnss_crs="EPSG:4326", |
| 251 | + network_file="/nonexistent/network.geojson", |
| 252 | + ) |
| 253 | + |
| 254 | + |
| 255 | +def test_calculate_train_path_invalid_config(gnss_csv, network_geojson): |
| 256 | + """A negative max_candidates of 0 (or invalid value) should fail at build().""" |
| 257 | + cfg = PathConfig(probability_threshold=2.0) # outside [0, 1] |
| 258 | + with pytest.raises((ValueError, RuntimeError)): |
| 259 | + calculate_train_path( |
| 260 | + gnss_file=gnss_csv, |
| 261 | + gnss_crs="EPSG:4326", |
| 262 | + network_file=network_geojson, |
| 263 | + config=cfg, |
| 264 | + ) |
| 265 | + |
| 266 | + |
| 267 | +# ============================================================================ |
| 268 | +# Detections |
| 269 | +# ============================================================================ |
| 270 | + |
| 271 | + |
| 272 | +def test_prepare_detections_punctual( |
| 273 | + punctual_detection_csv, gnss_csv, network_geojson |
| 274 | +): |
| 275 | + prepared = prepare_detections( |
| 276 | + detections_file=punctual_detection_csv, |
| 277 | + kind="punctual", |
| 278 | + gnss_file=gnss_csv, |
| 279 | + gnss_crs="EPSG:4326", |
| 280 | + network_file=network_geojson, |
| 281 | + ) |
| 282 | + assert isinstance(prepared, PreparedDetections) |
| 283 | + assert prepared.anchor_count >= 1 |
| 284 | + assert isinstance(prepared.warnings, list) |
| 285 | + |
| 286 | + records = prepared.records() |
| 287 | + assert isinstance(records, list) |
| 288 | + assert len(records) >= 1 |
| 289 | + rec = records[0] |
| 290 | + assert rec["kind"] == "punctual" |
| 291 | + assert rec["status"] in ("applied", "resolved", "discarded") |
| 292 | + assert "source_file" in rec |
| 293 | + assert "source_row" in rec |
| 294 | + assert "timestamp" in rec |
| 295 | + |
| 296 | + |
| 297 | +def test_prepare_detections_invalid_kind( |
| 298 | + punctual_detection_csv, gnss_csv, network_geojson |
| 299 | +): |
| 300 | + with pytest.raises(ValueError): |
| 301 | + prepare_detections( |
| 302 | + detections_file=punctual_detection_csv, |
| 303 | + kind="bogus", |
| 304 | + gnss_file=gnss_csv, |
| 305 | + gnss_crs="EPSG:4326", |
| 306 | + network_file=network_geojson, |
| 307 | + ) |
| 308 | + |
| 309 | + |
| 310 | +def test_calculate_train_path_with_detections( |
| 311 | + gnss_csv, network_geojson, punctual_detection_csv |
| 312 | +): |
| 313 | + prepared = prepare_detections( |
| 314 | + detections_file=punctual_detection_csv, |
| 315 | + kind="punctual", |
| 316 | + gnss_file=gnss_csv, |
| 317 | + gnss_crs="EPSG:4326", |
| 318 | + network_file=network_geojson, |
| 319 | + ) |
| 320 | + |
| 321 | + result = calculate_train_path( |
| 322 | + gnss_file=gnss_csv, |
| 323 | + gnss_crs="EPSG:4326", |
| 324 | + network_file=network_geojson, |
| 325 | + detections=prepared, |
| 326 | + ) |
| 327 | + assert isinstance(result, PathResult) |
| 328 | + # Provenance is now populated from the supplied detections (shape only) |
| 329 | + prov = result.detection_provenance() |
| 330 | + assert isinstance(prov, list) |
| 331 | + |
| 332 | + |
| 333 | +def test_prepared_detections_repr( |
| 334 | + punctual_detection_csv, gnss_csv, network_geojson |
| 335 | +): |
| 336 | + prepared = prepare_detections( |
| 337 | + detections_file=punctual_detection_csv, |
| 338 | + kind="punctual", |
| 339 | + gnss_file=gnss_csv, |
| 340 | + gnss_crs="EPSG:4326", |
| 341 | + network_file=network_geojson, |
| 342 | + ) |
| 343 | + r = repr(prepared) |
| 344 | + assert "PreparedDetections" in r |
| 345 | + assert "anchors=" in r |
0 commit comments