RastaAI / app /services /feature_extractor.py
devmurtaza's picture
Claude Sonnet 4.6
Initial RastaAI deployment (code only)
0ddcb86
Raw History Blame Contribute Delete
2.81 kB
"""Convert a raw routing candidate into a feature vector for ML inference.
Output dict matches the column order used by `training/preprocess.py` so the
preprocessor + model can consume it directly.
"""
from __future__ import annotations
from datetime import datetime
from typing import Dict, Any, Tuple
import math
from app.utils.geometry import polyline_length_km, haversine_km
from app.services.traffic_service import estimate_traffic_level, realised_speed_kmh
Coord = Tuple[float, float]
ROAD_TYPES = ["motorway", "highway", "primary", "urban", "mixed"]
def infer_road_type(distance_km: float, turns: int, avg_speed_kmh: float) -> str:
if avg_speed_kmh >= 90 and distance_km > 50:
return "motorway"
if avg_speed_kmh >= 75:
return "highway"
if avg_speed_kmh >= 55:
return "primary"
if turns > 30 or avg_speed_kmh < 35:
return "urban"
return "mixed"
def road_quality_score(road_type: str) -> float:
return {
"motorway": 0.95,
"highway": 0.85,
"primary": 0.7,
"mixed": 0.6,
"urban": 0.5,
}.get(road_type, 0.6)
def vehicle_fuel_factor(vehicle_type: str) -> Tuple[float, float]:
"""Return (base_consumption_l_per_100km, speed_optimum_kmh)."""
return {
"car": (8.0, 80.0),
"motorbike": (3.2, 70.0),
"truck": (22.0, 70.0),
"rickshaw": (4.5, 50.0),
}.get(vehicle_type, (8.0, 80.0))
async def extract_features(
candidate: Dict[str, Any],
origin: Coord,
destination: Coord,
departure: datetime,
vehicle_type: str,
weather_severity: float,
) -> Dict[str, Any]:
poly = candidate["polyline"]
distance_km = candidate.get("distance_km") or polyline_length_km(poly)
duration_min = candidate["duration_min"]
turns = candidate.get("turns", 0)
nominal_speed = distance_km / (duration_min / 60.0) if duration_min > 0 else 60.0
traffic_level = await estimate_traffic_level(origin, destination, departure, nominal_speed)
road_type = infer_road_type(distance_km, turns, nominal_speed)
realised_speed = realised_speed_kmh(nominal_speed, traffic_level)
straight = max(haversine_km(origin, destination), 1e-6)
detour_ratio = distance_km / straight
return {
"distance_km": distance_km,
"nominal_speed_kmh": nominal_speed,
"realised_speed_kmh": realised_speed,
"turns": turns,
"turns_per_km": turns / max(distance_km, 1e-6),
"traffic_level": traffic_level,
"road_type": road_type,
"road_quality": road_quality_score(road_type),
"hour_of_day": departure.hour,
"day_of_week": departure.weekday(),
"weather_severity": weather_severity,
"vehicle_type": vehicle_type,
"detour_ratio": detour_ratio,
}