Files
f1-circuits/models/geo_json/geometry.py
T
jschoubben d514eb57a3 Name an unknown circuit, layout or year with a 404 instead of a 500
The circuit and track routes walked circuits.json with chained lookups, so an unknown country, locality, circuit
or layout, or a year no layout covers, raised and answered 500 (/circuits/photos.json among them). One lookup now
names the first unknown part and the API answers it 404. numpy loads only where a script uses it, so the models,
and this lookup's test, need the standard library alone.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:13:34 +01:00

57 lines
2.0 KiB
Python

from dataclasses import dataclass
from typing import List, Dict, Any
@dataclass
class GeoJSONGeometry:
type: str
coordinates: List[tuple[float, float]]
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'GeoJSONGeometry':
return cls(
type=data['type'],
coordinates=data['coordinates']
)
def find_longest_straight(self, window_size=5) -> (List[float], List[float]):
"""Find the longest approximately straight section of the track, including wrap-around."""
import numpy as np # only here: the models themselves load with the standard library (the service's tests)
max_distance = 0
best_start_idx = 0
n = len(self.coordinates)
# Helper function to check straightness
def is_straight(points, start, end, length):
direction = (end - start) / length
distances = []
for point in points:
projection = start + np.dot(point - start, direction) * direction
distance = np.linalg.norm(point - projection)
distances.append(distance)
return max(distances) < length * 0.05 # 5% tolerance
# Check all possible segments, including wrap-around
for i in range(n):
# Get window_size points, handling wrap-around
segment = []
for j in range(window_size):
idx = (i + j) % n
segment.append(np.array(self.coordinates[idx]))
start = np.array(segment[0])
end = np.array(segment[-1])
length = np.linalg.norm(end - start)
if length > max_distance:
# Check if all points are roughly on the line
if is_straight(segment, start, end, length):
max_distance = length
best_start_idx = i
# Return indices that might wrap around
end_idx = (best_start_idx + window_size) % len(self.coordinates)
return self.coordinates[best_start_idx], self.coordinates[end_idx]