Upload 11 files
Browse files- analysis/Curve.py +844 -0
- analysis/CurveDetector.py +415 -0
- analysis/__init__.py +3 -0
- analysis/__pycache__/Curve.cpython-313.pyc +0 -0
- analysis/__pycache__/CurveDetector.cpython-313.pyc +0 -0
- analysis/__pycache__/__init__.cpython-313.pyc +0 -0
- analysis/__pycache__/dataset_normalization.cpython-313.pyc +0 -0
- analysis/__pycache__/utils_for_array.cpython-313.pyc +0 -0
- analysis/dataset_builder.py +470 -0
- analysis/dataset_normalization.py +520 -0
- analysis/utils_for_array.py +30 -0
analysis/Curve.py
ADDED
|
@@ -0,0 +1,844 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import List, Optional, Any, Tuple
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import warnings
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Curve:
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
corner_id: int,
|
| 13 |
+
current_corner_dist: float,
|
| 14 |
+
lower_bound: float,
|
| 15 |
+
upper_bound: float,
|
| 16 |
+
compound: str,
|
| 17 |
+
life: int,
|
| 18 |
+
stint: int,
|
| 19 |
+
time: List[float],
|
| 20 |
+
rpm: List[float],
|
| 21 |
+
speed: List[float],
|
| 22 |
+
throttle: List[float],
|
| 23 |
+
brake: List[float],
|
| 24 |
+
distance: List[float],
|
| 25 |
+
acc_x: List[float],
|
| 26 |
+
acc_y: List[float],
|
| 27 |
+
acc_z: List[float],
|
| 28 |
+
x: List[float],
|
| 29 |
+
y: List[float],
|
| 30 |
+
z: List[float]
|
| 31 |
+
):
|
| 32 |
+
self.corner_id = corner_id
|
| 33 |
+
self.current_corner_dist = current_corner_dist
|
| 34 |
+
self.lower_bound = lower_bound
|
| 35 |
+
self.upper_bound = upper_bound
|
| 36 |
+
self.time = np.asarray(time)
|
| 37 |
+
self.rpm = np.asarray(rpm)
|
| 38 |
+
self.speed = np.asarray(speed)
|
| 39 |
+
self.throttle = np.asarray(throttle)
|
| 40 |
+
self.brake = np.asarray(brake)
|
| 41 |
+
self.distance = np.asarray(distance)
|
| 42 |
+
self.acc_x = np.asarray(acc_x)
|
| 43 |
+
self.acc_y = np.asarray(acc_y)
|
| 44 |
+
self.acc_z = np.asarray(acc_z)
|
| 45 |
+
self.x = np.asarray(x)
|
| 46 |
+
self.y = np.asarray(y)
|
| 47 |
+
self.z = np.asarray(z)
|
| 48 |
+
self.compound = compound
|
| 49 |
+
self.life = life
|
| 50 |
+
self.stint = stint
|
| 51 |
+
self.latent_variable = None
|
| 52 |
+
self.num_cluster = None
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def from_norm_data(
|
| 56 |
+
cls,
|
| 57 |
+
sample: np.ndarray,
|
| 58 |
+
mask: np.ndarray,
|
| 59 |
+
mean: np.ndarray,
|
| 60 |
+
std: np.ndarray,
|
| 61 |
+
latent_variable: Optional[List[float]] = None,
|
| 62 |
+
num_cluster: Optional[int] = None,
|
| 63 |
+
):
|
| 64 |
+
"""
|
| 65 |
+
sample: vettore 1D con layout:
|
| 66 |
+
0: life
|
| 67 |
+
1:51 speed
|
| 68 |
+
51:101 rpm
|
| 69 |
+
101:151 throttle
|
| 70 |
+
151:201 brake
|
| 71 |
+
201:251 acc_x
|
| 72 |
+
251:301 acc_y
|
| 73 |
+
301:351 acc_z
|
| 74 |
+
352,353: compound one-hot (hard/medium) altrimenti soft
|
| 75 |
+
mask: boolean mask compatibile (stesse slice)
|
| 76 |
+
"""
|
| 77 |
+
compound = ""
|
| 78 |
+
# compound
|
| 79 |
+
if sample[352] != 0:
|
| 80 |
+
compound = "HARD"
|
| 81 |
+
elif sample[353] != 0:
|
| 82 |
+
compound = "INTERMEDIATE"
|
| 83 |
+
elif sample[354] != 0:
|
| 84 |
+
compound = "WET"
|
| 85 |
+
elif sample[355] != 0:
|
| 86 |
+
compound = "MEDIUM"
|
| 87 |
+
else:
|
| 88 |
+
compound = "SOFT"
|
| 89 |
+
|
| 90 |
+
bool_mask = mask.astype(bool)
|
| 91 |
+
|
| 92 |
+
life = int(sample[0]) # se life non è mascherato, meglio così
|
| 93 |
+
life = cls._denormalize_value(cls, life, mean[0], std[0])
|
| 94 |
+
|
| 95 |
+
speed = cls._extract_and_denormalize(cls, 1, 51, sample, bool_mask, mean, std)
|
| 96 |
+
rpm = cls._extract_and_denormalize(cls, 51, 101, sample, bool_mask, mean, std)
|
| 97 |
+
throttle = cls._extract_and_denormalize(cls, 101, 151, sample, bool_mask, mean, std)
|
| 98 |
+
brake = cls._extract_and_denormalize(cls, 151, 201, sample, bool_mask, mean, std)
|
| 99 |
+
acc_x = cls._extract_and_denormalize(cls, 201, 251, sample, bool_mask, mean, std)
|
| 100 |
+
acc_y = cls._extract_and_denormalize(cls, 251, 301, sample, bool_mask, mean, std)
|
| 101 |
+
acc_z = cls._extract_and_denormalize(cls, 301, 351, sample, bool_mask, mean, std)
|
| 102 |
+
|
| 103 |
+
# Create the instance
|
| 104 |
+
instance = cls(
|
| 105 |
+
corner_id=-1,
|
| 106 |
+
current_corner_dist=-1,
|
| 107 |
+
lower_bound=-1,
|
| 108 |
+
upper_bound=-1,
|
| 109 |
+
compound=compound,
|
| 110 |
+
life=life,
|
| 111 |
+
stint=-1,
|
| 112 |
+
time=list(),
|
| 113 |
+
rpm=rpm,
|
| 114 |
+
speed=speed,
|
| 115 |
+
throttle=throttle,
|
| 116 |
+
brake=brake,
|
| 117 |
+
distance=list(),
|
| 118 |
+
acc_x=acc_x,
|
| 119 |
+
acc_y=acc_y,
|
| 120 |
+
acc_z=acc_z,
|
| 121 |
+
x=list(),
|
| 122 |
+
y=list(),
|
| 123 |
+
z=list()
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Set optional attributes
|
| 127 |
+
instance.latent_variable = latent_variable
|
| 128 |
+
instance.num_cluster = num_cluster
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
return instance
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
#########################################################
|
| 136 |
+
# Metodi privati #
|
| 137 |
+
#########################################################
|
| 138 |
+
|
| 139 |
+
def _denormalize_array(self, arr: np.ndarray, mean: float, std: float) -> np.ndarray:
|
| 140 |
+
return (arr * std) + mean
|
| 141 |
+
|
| 142 |
+
def _denormalize_value(self, value: float, mean: float, std: float) -> float:
|
| 143 |
+
return (value * std) + mean
|
| 144 |
+
|
| 145 |
+
def _extract_and_denormalize(
|
| 146 |
+
self,
|
| 147 |
+
start: int,
|
| 148 |
+
end: int,
|
| 149 |
+
sample: np.ndarray,
|
| 150 |
+
bool_mask: np.ndarray,
|
| 151 |
+
mean: np.ndarray,
|
| 152 |
+
std: np.ndarray
|
| 153 |
+
) -> list:
|
| 154 |
+
"""
|
| 155 |
+
Estrae una porzione dell'array sample[start:end], applica la maschera e denormalizza.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
start: indice di inizio (incluso)
|
| 159 |
+
end: indice di fine (escluso)
|
| 160 |
+
sample: array completo dei dati normalizzati
|
| 161 |
+
bool_mask: maschera booleana per filtrare i valori validi
|
| 162 |
+
mean: array delle medie per la denormalizzazione
|
| 163 |
+
std: array delle deviazioni standard per la denormalizzazione
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
Lista dei valori estratti, filtrati e denormalizzati
|
| 167 |
+
"""
|
| 168 |
+
extracted = sample[start:end][bool_mask[start:end]].tolist()
|
| 169 |
+
return self._denormalize_array(self, np.asarray(extracted), mean[start], std[start]).tolist()
|
| 170 |
+
|
| 171 |
+
def print(self):
|
| 172 |
+
print(f"[!] apex:{self.apex_dist}; start: {self.distance[0]} -> end: {self.distance[-1]}")
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
#########################################################
|
| 177 |
+
# Metriche semplici #
|
| 178 |
+
#########################################################
|
| 179 |
+
|
| 180 |
+
def lateral_g(self) -> np.ndarray:
|
| 181 |
+
"""G laterali (curva)"""
|
| 182 |
+
return self.acc_y / 9.81
|
| 183 |
+
|
| 184 |
+
def longitudinal_g(self) -> np.ndarray:
|
| 185 |
+
"""G longitudinali (positivo=accelerazione, negativo=frenata)"""
|
| 186 |
+
return self.acc_x / 9.81
|
| 187 |
+
|
| 188 |
+
def vertical_g(self) -> np.ndarray:
|
| 189 |
+
"""G verticali"""
|
| 190 |
+
return self.acc_z / 9.81
|
| 191 |
+
|
| 192 |
+
def total_g_xy(self) -> np.ndarray:
|
| 193 |
+
"""G totali sul piano XY (grip utilizzato)"""
|
| 194 |
+
acc_total = np.sqrt(self.acc_x**2 + self.acc_y**2)
|
| 195 |
+
return acc_total / 9.81
|
| 196 |
+
|
| 197 |
+
def brake_intensity(self) -> np.ndarray:
|
| 198 |
+
"""Intensità frenata (0 quando non frena, alto quando frena forte)"""
|
| 199 |
+
return self.brake * np.abs(np.minimum(self.acc_x, 0)) #confronta acc_x con zero e ritorna il più piccolo
|
| 200 |
+
|
| 201 |
+
def throttle_rate(self) -> np.ndarray:
|
| 202 |
+
"""Velocità di applicazione throttle (quanto velocemente apre/chiude)"""
|
| 203 |
+
return np.gradient(self.throttle)
|
| 204 |
+
|
| 205 |
+
def brake_time_percent(self) -> float:
|
| 206 |
+
"""Percentuale tempo in frenata"""
|
| 207 |
+
return (np.sum(self.brake) / len(self.brake)) * 100
|
| 208 |
+
|
| 209 |
+
def full_throttle_percent(self) -> float:
|
| 210 |
+
"""Percentuale tempo a gas spalancato (>95%)"""
|
| 211 |
+
return (np.sum(self.throttle > 95) / len(self.throttle)) * 100
|
| 212 |
+
|
| 213 |
+
def avg_speed(self) -> float:
|
| 214 |
+
"""Velocità media"""
|
| 215 |
+
return np.mean(self.speed)
|
| 216 |
+
|
| 217 |
+
def max_speed(self) -> float:
|
| 218 |
+
"""Velocità massima"""
|
| 219 |
+
return np.max(self.speed)
|
| 220 |
+
|
| 221 |
+
def tire_wear_total(self) -> float:
|
| 222 |
+
"""Degrado totale gomme durante il periodo analizzato"""
|
| 223 |
+
if isinstance(self.life, (int, float, np.number)):
|
| 224 |
+
return 0.0
|
| 225 |
+
return self.life[0] - self.life[-1] if len(self.life) > 0 else 0
|
| 226 |
+
|
| 227 |
+
#########################################################
|
| 228 |
+
# Metriche più complesse #
|
| 229 |
+
#########################################################
|
| 230 |
+
|
| 231 |
+
def grip_usage_percent(self, max_g: float = 6.5) -> np.ndarray:
|
| 232 |
+
"""
|
| 233 |
+
Percentuale utilizzo cerchio di aderenza
|
| 234 |
+
max_g: massimo G teorico raggiungibile (default 6.5)
|
| 235 |
+
Ritorna: array con % utilizzo grip momento per momento
|
| 236 |
+
"""
|
| 237 |
+
return (self.total_g_xy() / max_g) * 100
|
| 238 |
+
|
| 239 |
+
def aggressivity_index(self) -> np.ndarray:
|
| 240 |
+
"""
|
| 241 |
+
Indice aggressività relativo al grip disponibile.
|
| 242 |
+
Stima quanto stai usando del grip residuo della gomma.
|
| 243 |
+
"""
|
| 244 |
+
# Stima degradazione grip: perde circa 1.5-2% per giro
|
| 245 |
+
DEGRADATION_PER_LAP = 0.02 # 2% perdita grip per giro
|
| 246 |
+
|
| 247 |
+
# Grip residuo stimato (da 1.0 a ~0.4 per gomme molto vecchie)
|
| 248 |
+
grip_remaining = max(1.0 - (self.life * DEGRADATION_PER_LAP), 0.4)
|
| 249 |
+
|
| 250 |
+
# G massimi teorici (es. 6.5G) scalati per grip residuo
|
| 251 |
+
MAX_G = 6.5
|
| 252 |
+
available_g = MAX_G * grip_remaining
|
| 253 |
+
|
| 254 |
+
# Quanto stai usando del grip disponibile
|
| 255 |
+
acc_total = np.sqrt(self.acc_x**2 + self.acc_y**2)
|
| 256 |
+
return (acc_total / available_g) * 100 # percentuale utilizzo
|
| 257 |
+
|
| 258 |
+
def smoothness_index(self, window: int = 20) -> float:
|
| 259 |
+
"""
|
| 260 |
+
Indice di fluidità guida
|
| 261 |
+
Basso (< 0.3) = guida fluida, gestione
|
| 262 |
+
Alto (> 0.5) = guida nervosa, spinta al limite
|
| 263 |
+
"""
|
| 264 |
+
acc_x = np.asarray(self.acc_x)
|
| 265 |
+
acc_y = np.asarray(self.acc_y)
|
| 266 |
+
acc_total = np.sqrt(acc_x**2 + acc_y**2)
|
| 267 |
+
|
| 268 |
+
if len(acc_total) < window:
|
| 269 |
+
window = max(len(acc_total) // 2, 2)
|
| 270 |
+
|
| 271 |
+
# Rolling standard deviation
|
| 272 |
+
rolling_std = np.array([np.std(acc_total[max(0, i-window):i+1]) for i in range(len(acc_total))])
|
| 273 |
+
mean_acc = np.mean(acc_total)
|
| 274 |
+
|
| 275 |
+
return np.mean(rolling_std) / mean_acc if mean_acc > 0 else 0
|
| 276 |
+
|
| 277 |
+
def corner_speed_index(self, lateral_g_threshold: float = 0.3) -> float:
|
| 278 |
+
"""
|
| 279 |
+
Velocità media nelle curve (dove G laterali > threshold)
|
| 280 |
+
Alto = entra veloce in curva (spingendo)
|
| 281 |
+
"""
|
| 282 |
+
in_corner = np.abs(self.lateral_g()) > lateral_g_threshold
|
| 283 |
+
if not np.any(in_corner):
|
| 284 |
+
return 0.0
|
| 285 |
+
return np.mean(self.speed[in_corner])
|
| 286 |
+
|
| 287 |
+
def corner_aggression(self, lateral_g_threshold: float = 0.3) -> float:
|
| 288 |
+
"""
|
| 289 |
+
Aggressività in curva = velocità × G laterali
|
| 290 |
+
Più alto = più aggressivo in curva
|
| 291 |
+
"""
|
| 292 |
+
lateral_g = self.lateral_g()
|
| 293 |
+
in_corner = np.abs(lateral_g) > lateral_g_threshold
|
| 294 |
+
if not np.any(in_corner):
|
| 295 |
+
return 0.0
|
| 296 |
+
|
| 297 |
+
avg_speed = np.mean(self.speed[in_corner])
|
| 298 |
+
avg_lat_g = np.mean(np.abs(lateral_g[in_corner]))
|
| 299 |
+
|
| 300 |
+
return avg_speed * avg_lat_g
|
| 301 |
+
|
| 302 |
+
def tire_stress_score(self) -> float:
|
| 303 |
+
"""
|
| 304 |
+
Score di stress sulle gomme
|
| 305 |
+
Combina accelerazione totale, velocità e usura
|
| 306 |
+
Gomme più vecchie = stress amplificato (più rischioso)
|
| 307 |
+
"""
|
| 308 |
+
acc_total = np.sqrt(self.acc_x**2 + self.acc_y**2)
|
| 309 |
+
# Moltiplicatore usura: da 1.0 (gomma nuova) a ~2.0 (30 giri)
|
| 310 |
+
wear_multiplier = 1 + (self.life / 30)
|
| 311 |
+
stress = acc_total * self.speed * wear_multiplier
|
| 312 |
+
return np.mean(stress)
|
| 313 |
+
|
| 314 |
+
def braking_aggression(self) -> float:
|
| 315 |
+
"""
|
| 316 |
+
Aggressività in frenata - Versione migliorata
|
| 317 |
+
Un pilota che spinge:
|
| 318 |
+
- Frena TARDI (alta velocità all'inizio frenata)
|
| 319 |
+
- Frena FORTE (alta decelerazione media)
|
| 320 |
+
- Frena BREVE (rilascio rapido)
|
| 321 |
+
"""
|
| 322 |
+
brake = np.asarray(self.brake)
|
| 323 |
+
brake_mask = brake == 1
|
| 324 |
+
if not np.any(brake_mask):
|
| 325 |
+
return 0.0
|
| 326 |
+
|
| 327 |
+
# 1. Decelerazione MEDIA durante frenata (non solo massima)
|
| 328 |
+
avg_decel_g = np.mean(np.abs(self.longitudinal_g()[brake_mask]))
|
| 329 |
+
|
| 330 |
+
# 2. Velocità all'ingresso in frenata (più alta = più aggressivo)
|
| 331 |
+
speed_at_brake = np.mean(self.speed[brake_mask])
|
| 332 |
+
speed_factor = speed_at_brake / 300 # normalizza su 300 km/h
|
| 333 |
+
|
| 334 |
+
# 3. "Brevità" frenata: meno tempo = più aggressivo (inversione)
|
| 335 |
+
brake_brevity = 1 - (self.brake_time_percent() / 100)
|
| 336 |
+
|
| 337 |
+
# Score combinato (pesi da calibrare)
|
| 338 |
+
score = (avg_decel_g * 20) * speed_factor * (0.5 + brake_brevity)
|
| 339 |
+
|
| 340 |
+
return np.clip(score, 0, 100)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def pushing_score(self) -> float:
|
| 345 |
+
"""
|
| 346 |
+
SCORE PRINCIPALE: indica se sta spingendo (0-100)
|
| 347 |
+
|
| 348 |
+
< 30: GESTIONE - Pilota conservativo, gestisce gomme/macchina
|
| 349 |
+
30-60: RITMO - Guida veloce ma controllata
|
| 350 |
+
> 60: SPINTA - Sta spingendo al limite
|
| 351 |
+
> 80: QUALIFICA - Massima spinta, un giro secco
|
| 352 |
+
"""
|
| 353 |
+
# Grip usage assoluto (G totali vs max teorico)
|
| 354 |
+
grip_score = np.clip(np.mean(self.grip_usage_percent()), 0, 100)
|
| 355 |
+
|
| 356 |
+
# Aggressivity: quanto stai usando del grip DISPONIBILE (considera usura gomme)
|
| 357 |
+
aggressivity_score = np.clip(np.mean(self.aggressivity_index()), 0, 100)
|
| 358 |
+
|
| 359 |
+
# Smoothness: alto smoothness = guida nervosa = spinta alta
|
| 360 |
+
# (smoothness_index alto significa variazioni frequenti nelle accelerazioni)
|
| 361 |
+
smooth = self.smoothness_index()
|
| 362 |
+
smoothness_score = np.clip(smooth * 100, 0, 100)
|
| 363 |
+
|
| 364 |
+
# Throttle usage
|
| 365 |
+
throttle_score = self.full_throttle_percent()
|
| 366 |
+
|
| 367 |
+
# Corner aggression normalizzato
|
| 368 |
+
corner_agg = self.corner_aggression()
|
| 369 |
+
corner_score = np.clip(corner_agg * 0.5, 0, 100)
|
| 370 |
+
|
| 371 |
+
# Braking aggression
|
| 372 |
+
brake_agg = self.braking_aggression()
|
| 373 |
+
brake_score = np.clip(brake_agg, 0, 100)
|
| 374 |
+
|
| 375 |
+
# Fattore velocità: penalizza giri lenti (outlap, inlap, gestione estrema)
|
| 376 |
+
# Reference speed per curve F1: ~120 km/h media in curva durante spinta
|
| 377 |
+
avg_spd = self.avg_speed()
|
| 378 |
+
REFERENCE_SPEED = 120.0
|
| 379 |
+
speed_factor = np.clip(avg_spd / REFERENCE_SPEED, 0.0, 1.0)
|
| 380 |
+
|
| 381 |
+
# Media ponderata - pesi ribilanciati:
|
| 382 |
+
# - grip e aggressivity pesano di più (sono la misura diretta dei G)
|
| 383 |
+
# - corner_score peso aumentato (riflette velocità in curva)
|
| 384 |
+
# - smoothness ridotto (meno affidabile come indicatore)
|
| 385 |
+
raw_score = (
|
| 386 |
+
grip_score * 0.25 + # G assoluti - peso principale
|
| 387 |
+
aggressivity_score * 0.25 + # G relativi al grip disponibile
|
| 388 |
+
throttle_score * 0.10 + # Uso gas
|
| 389 |
+
corner_score * 0.20 + # Aggressività in curva
|
| 390 |
+
brake_score * 0.10 + # Aggressività frenata
|
| 391 |
+
smoothness_score * 0.10 # Variabilità guida
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# Applica penalità velocità: score finale scalato per speed_factor
|
| 395 |
+
total = raw_score * speed_factor
|
| 396 |
+
|
| 397 |
+
return np.clip(total, 0, 100)
|
| 398 |
+
|
| 399 |
+
def get_driving_mode(self) -> str:
|
| 400 |
+
"""Restituisce il modo di guida attuale"""
|
| 401 |
+
score = self.pushing_score()
|
| 402 |
+
|
| 403 |
+
if score < 30:
|
| 404 |
+
return "GESTIONE"
|
| 405 |
+
elif score < 50:
|
| 406 |
+
return "RITMO MEDIO"
|
| 407 |
+
elif score < 70:
|
| 408 |
+
return "SPINTA"
|
| 409 |
+
else:
|
| 410 |
+
return "MASSIMO ATTACCO"
|
| 411 |
+
|
| 412 |
+
#########################################################
|
| 413 |
+
# Grafici #
|
| 414 |
+
#########################################################
|
| 415 |
+
|
| 416 |
+
def plot_g_forces_map(self, figsize: Tuple[int, int] = (12, 10)):
|
| 417 |
+
"""
|
| 418 |
+
Grafico 1: Mappa delle forze G (cerchio di aderenza)
|
| 419 |
+
Mostra come il pilota usa il grip disponibile
|
| 420 |
+
"""
|
| 421 |
+
fig, axes = plt.subplots(2, 2, figsize=figsize)
|
| 422 |
+
fig.suptitle('ANALISI FORZE G E UTILIZZO GRIP', fontsize=16, fontweight='bold')
|
| 423 |
+
|
| 424 |
+
# 1. Cerchio di aderenza (G plot)
|
| 425 |
+
ax = axes[0, 0]
|
| 426 |
+
scatter = ax.scatter(self.lateral_g(), self.longitudinal_g(),
|
| 427 |
+
c=self.speed, cmap='plasma', s=10, alpha=0.6)
|
| 428 |
+
|
| 429 |
+
# Cerchio teorico massimo
|
| 430 |
+
theta = np.linspace(0, 2*np.pi, 100)
|
| 431 |
+
max_g = 5.0
|
| 432 |
+
ax.plot(max_g * np.cos(theta), max_g * np.sin(theta),
|
| 433 |
+
'r--', linewidth=2, alpha=0.3, label=f'Limite teorico ({max_g}G)')
|
| 434 |
+
|
| 435 |
+
ax.set_xlabel('G Laterali', fontweight='bold')
|
| 436 |
+
ax.set_ylabel('G Longitudinali', fontweight='bold')
|
| 437 |
+
ax.set_title('Cerchio di Aderenza')
|
| 438 |
+
ax.grid(True, alpha=0.3)
|
| 439 |
+
ax.axhline(0, color='k', linewidth=0.5)
|
| 440 |
+
ax.axvline(0, color='k', linewidth=0.5)
|
| 441 |
+
ax.legend()
|
| 442 |
+
plt.colorbar(scatter, ax=ax, label='Velocità (km/h)')
|
| 443 |
+
ax.set_aspect('equal')
|
| 444 |
+
|
| 445 |
+
# 2. G totali nel tempo
|
| 446 |
+
ax = axes[0, 1]
|
| 447 |
+
time = np.arange(len(self.total_g_xy()))
|
| 448 |
+
ax.plot(time, self.total_g_xy(), color='#e74c3c', linewidth=1.5, label='G Totali')
|
| 449 |
+
ax.fill_between(time, 0, self.total_g_xy(), alpha=0.3, color='#e74c3c')
|
| 450 |
+
ax.set_xlabel('Campioni', fontweight='bold')
|
| 451 |
+
ax.set_ylabel('G Totali', fontweight='bold')
|
| 452 |
+
ax.set_title('G Totali nel Tempo')
|
| 453 |
+
ax.grid(True, alpha=0.3)
|
| 454 |
+
ax.legend()
|
| 455 |
+
|
| 456 |
+
# 3. Utilizzo grip %
|
| 457 |
+
ax = axes[1, 0]
|
| 458 |
+
grip_usage = self.grip_usage_percent()
|
| 459 |
+
ax.plot(time, grip_usage, color='#3498db', linewidth=1.5)
|
| 460 |
+
ax.fill_between(time, 0, grip_usage, alpha=0.3, color='#3498db')
|
| 461 |
+
ax.axhline(80, color='orange', linestyle='--', linewidth=2, alpha=0.5, label='Soglia rischio')
|
| 462 |
+
ax.axhline(90, color='red', linestyle='--', linewidth=2, alpha=0.5, label='Limite')
|
| 463 |
+
ax.set_xlabel('Campioni', fontweight='bold')
|
| 464 |
+
ax.set_ylabel('Utilizzo Grip (%)', fontweight='bold')
|
| 465 |
+
ax.set_title('Percentuale Utilizzo Grip')
|
| 466 |
+
ax.set_ylim(0, 100)
|
| 467 |
+
ax.grid(True, alpha=0.3)
|
| 468 |
+
ax.legend()
|
| 469 |
+
|
| 470 |
+
# 4. Distribuzione G laterali vs longitudinali
|
| 471 |
+
ax = axes[1, 1]
|
| 472 |
+
ax.hist2d(self.lateral_g(), self.longitudinal_g(),
|
| 473 |
+
bins=50, cmap='YlOrRd', alpha=0.8)
|
| 474 |
+
ax.set_xlabel('G Laterali', fontweight='bold')
|
| 475 |
+
ax.set_ylabel('G Longitudinali', fontweight='bold')
|
| 476 |
+
ax.set_title('Distribuzione Forze G (Heatmap)')
|
| 477 |
+
ax.grid(True, alpha=0.3)
|
| 478 |
+
|
| 479 |
+
try:
|
| 480 |
+
with warnings.catch_warnings():
|
| 481 |
+
warnings.simplefilter("ignore", UserWarning)
|
| 482 |
+
fig.tight_layout()
|
| 483 |
+
except Exception:
|
| 484 |
+
pass
|
| 485 |
+
return fig
|
| 486 |
+
|
| 487 |
+
def plot_driver_inputs(self, figsize: Tuple[int, int] = (14, 8)):
|
| 488 |
+
"""
|
| 489 |
+
Grafico 2: Input del pilota (throttle, brake, steering proxy)
|
| 490 |
+
"""
|
| 491 |
+
fig, axes = plt.subplots(3, 1, figsize=figsize, sharex=True)
|
| 492 |
+
fig.suptitle('INPUT DEL PILOTA', fontsize=16, fontweight='bold')
|
| 493 |
+
|
| 494 |
+
time = np.arange(len(self.throttle))
|
| 495 |
+
|
| 496 |
+
# 1. Throttle
|
| 497 |
+
ax = axes[0]
|
| 498 |
+
ax.fill_between(time, 0, self.throttle, color='#2ecc71', alpha=0.7, label='Throttle')
|
| 499 |
+
ax.set_ylabel('Throttle (%)', fontweight='bold')
|
| 500 |
+
ax.set_ylim(0, 100)
|
| 501 |
+
ax.grid(True, alpha=0.3)
|
| 502 |
+
ax.legend(loc='upper right')
|
| 503 |
+
ax.set_title(f'Gas Spalancato: {self.full_throttle_percent():.1f}% del tempo')
|
| 504 |
+
|
| 505 |
+
# 2. Brake
|
| 506 |
+
ax = axes[1]
|
| 507 |
+
ax.fill_between(time, 0, self.brake * 100, color='#e74c3c', alpha=0.7, label='Brake')
|
| 508 |
+
ax.set_ylabel('Brake (On/Off)', fontweight='bold')
|
| 509 |
+
ax.set_ylim(0, 110)
|
| 510 |
+
ax.grid(True, alpha=0.3)
|
| 511 |
+
ax.legend(loc='upper right')
|
| 512 |
+
ax.set_title(f'Tempo in Frenata: {self.brake_time_percent():.1f}%')
|
| 513 |
+
|
| 514 |
+
# 3. G Laterali (proxy per steering)
|
| 515 |
+
ax = axes[2]
|
| 516 |
+
ax.plot(time, self.lateral_g(), color='#9b59b6', linewidth=1, label='G Laterali')
|
| 517 |
+
ax.fill_between(time, 0, self.lateral_g(), where=self.lateral_g()>=0,
|
| 518 |
+
alpha=0.3, color='#9b59b6', interpolate=True)
|
| 519 |
+
ax.fill_between(time, 0, self.lateral_g(), where=self.lateral_g()<=0,
|
| 520 |
+
alpha=0.3, color='#e67e22', interpolate=True)
|
| 521 |
+
ax.set_xlabel('Campioni', fontweight='bold')
|
| 522 |
+
ax.set_ylabel('G Laterali', fontweight='bold')
|
| 523 |
+
ax.grid(True, alpha=0.3)
|
| 524 |
+
ax.legend(loc='upper right')
|
| 525 |
+
ax.axhline(0, color='k', linewidth=0.5)
|
| 526 |
+
|
| 527 |
+
try:
|
| 528 |
+
with warnings.catch_warnings():
|
| 529 |
+
warnings.simplefilter("ignore", UserWarning)
|
| 530 |
+
fig.tight_layout()
|
| 531 |
+
except Exception:
|
| 532 |
+
pass
|
| 533 |
+
return fig
|
| 534 |
+
|
| 535 |
+
def plot_tire_management(self, figsize: Tuple[int, int] = (14, 6)):
|
| 536 |
+
"""
|
| 537 |
+
Grafico 3: Gestione gomme
|
| 538 |
+
"""
|
| 539 |
+
fig, axes = plt.subplots(1, 3, figsize=figsize)
|
| 540 |
+
fig.suptitle('GESTIONE GOMME', fontsize=16, fontweight='bold')
|
| 541 |
+
|
| 542 |
+
# Determina la lunghezza per l'asse temporale
|
| 543 |
+
telemetry_len = len(self.speed)
|
| 544 |
+
time = np.arange(telemetry_len)
|
| 545 |
+
|
| 546 |
+
# Gestione life (può essere scalare o array)
|
| 547 |
+
life_data = np.asarray(self.life)
|
| 548 |
+
if life_data.ndim == 0:
|
| 549 |
+
life_plot = np.full(telemetry_len, self.life)
|
| 550 |
+
else:
|
| 551 |
+
life_plot = life_data
|
| 552 |
+
if len(life_plot) != telemetry_len:
|
| 553 |
+
# Se le lunghezze non coincidono, cerchiamo di interpolare o adattare
|
| 554 |
+
life_plot = np.interp(np.linspace(0, len(life_plot)-1, telemetry_len),
|
| 555 |
+
np.arange(len(life_plot)), life_plot)
|
| 556 |
+
|
| 557 |
+
# 1. Vita gomme nel tempo
|
| 558 |
+
ax = axes[0]
|
| 559 |
+
ax.plot(time, life_plot, color='#e74c3c', linewidth=2, marker='o',
|
| 560 |
+
markersize=2, label='Vita Gomme')
|
| 561 |
+
ax.fill_between(time, 0, life_plot, alpha=0.3, color='#e74c3c')
|
| 562 |
+
ax.axhline(20, color='orange', linestyle='--', alpha=0.5, label='Soglia critica')
|
| 563 |
+
ax.set_xlabel('Campioni', fontweight='bold')
|
| 564 |
+
ax.set_ylabel('Vita Gomme (%)', fontweight='bold')
|
| 565 |
+
ax.set_title(f'Degrado: {self.tire_wear_total():.1f}%')
|
| 566 |
+
ax.grid(True, alpha=0.3)
|
| 567 |
+
ax.legend()
|
| 568 |
+
ax.set_ylim(0, 100)
|
| 569 |
+
|
| 570 |
+
# 2. Aggressivity Index
|
| 571 |
+
ax = axes[1]
|
| 572 |
+
agg_idx = self.aggressivity_index()
|
| 573 |
+
ax.plot(time, agg_idx, color='#f39c12', linewidth=1.5)
|
| 574 |
+
ax.fill_between(time, 0, agg_idx, alpha=0.3, color='#f39c12')
|
| 575 |
+
ax.set_xlabel('Campioni', fontweight='bold')
|
| 576 |
+
ax.set_ylabel('Aggressivity Index', fontweight='bold')
|
| 577 |
+
ax.set_title('Stress su Gomme vs Degrado')
|
| 578 |
+
ax.grid(True, alpha=0.3)
|
| 579 |
+
|
| 580 |
+
# 3. Correlazione: Grip usage vs Tire life
|
| 581 |
+
ax = axes[2]
|
| 582 |
+
grip_usage = self.grip_usage_percent()
|
| 583 |
+
|
| 584 |
+
# Assicuriamoci che grip_usage e life_plot abbiano la stessa dimensione
|
| 585 |
+
scatter = ax.scatter(life_plot, grip_usage, c=self.speed,
|
| 586 |
+
cmap='viridis', s=10, alpha=0.6)
|
| 587 |
+
ax.set_xlabel('Vita Gomme (%)', fontweight='bold')
|
| 588 |
+
ax.set_ylabel('Utilizzo Grip (%)', fontweight='bold')
|
| 589 |
+
ax.set_title('Grip Usage vs Tire Life')
|
| 590 |
+
ax.grid(True, alpha=0.3)
|
| 591 |
+
plt.colorbar(scatter, ax=ax, label='Velocità')
|
| 592 |
+
|
| 593 |
+
try:
|
| 594 |
+
with warnings.catch_warnings():
|
| 595 |
+
warnings.simplefilter("ignore", UserWarning)
|
| 596 |
+
fig.tight_layout()
|
| 597 |
+
except Exception:
|
| 598 |
+
pass
|
| 599 |
+
return fig
|
| 600 |
+
|
| 601 |
+
def plot_pushing_analysis(self, figsize: Tuple[int, int] = (14, 10)):
|
| 602 |
+
"""
|
| 603 |
+
Grafico 4: ANALISI PRINCIPALE - Sta spingendo o gestendo?
|
| 604 |
+
"""
|
| 605 |
+
fig = plt.figure(figsize=figsize)
|
| 606 |
+
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
|
| 607 |
+
|
| 608 |
+
pushing_score = self.pushing_score()
|
| 609 |
+
driving_mode = self.get_driving_mode()
|
| 610 |
+
|
| 611 |
+
fig.suptitle(f'PUSHING ANALYSIS - Score: {pushing_score:.1f}/100 - {driving_mode}',
|
| 612 |
+
fontsize=18, fontweight='bold')
|
| 613 |
+
|
| 614 |
+
# 1. Pushing Score Gauge (grande, in alto)
|
| 615 |
+
ax_gauge = fig.add_subplot(gs[0, :])
|
| 616 |
+
self._plot_gauge(ax_gauge, pushing_score)
|
| 617 |
+
|
| 618 |
+
# 2. Metriche chiave
|
| 619 |
+
ax = fig.add_subplot(gs[1, 0])
|
| 620 |
+
metrics = {
|
| 621 |
+
'Grip Usage': np.mean(self.grip_usage_percent()),
|
| 622 |
+
'Throttle': self.full_throttle_percent(),
|
| 623 |
+
'Smoothness': (1 - self.smoothness_index()) * 100,
|
| 624 |
+
'Corner Agg': np.clip(self.corner_aggression() * 0.5, 0, 100),
|
| 625 |
+
'Brake Agg': np.clip(self.braking_aggression(), 0, 100)
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
colors = ['#3498db', '#2ecc71', '#9b59b6', '#e67e22', '#e74c3c']
|
| 629 |
+
bars = ax.barh(list(metrics.keys()), list(metrics.values()), color=colors, alpha=0.7)
|
| 630 |
+
ax.set_xlabel('Score', fontweight='bold')
|
| 631 |
+
ax.set_title('Componenti Pushing Score')
|
| 632 |
+
ax.set_xlim(0, 100)
|
| 633 |
+
ax.grid(True, alpha=0.3, axis='x')
|
| 634 |
+
|
| 635 |
+
# Aggiungi valori sulle barre
|
| 636 |
+
for i, (bar, val) in enumerate(zip(bars, metrics.values())):
|
| 637 |
+
ax.text(val + 2, i, f'{val:.1f}', va='center', fontweight='bold')
|
| 638 |
+
|
| 639 |
+
# 3. Speed vs G totali
|
| 640 |
+
ax = fig.add_subplot(gs[1, 1])
|
| 641 |
+
scatter = ax.scatter(self.speed, self.total_g_xy(),
|
| 642 |
+
c=self.throttle, cmap='RdYlGn', s=15, alpha=0.6)
|
| 643 |
+
ax.set_xlabel('Velocità (km/h)', fontweight='bold')
|
| 644 |
+
ax.set_ylabel('G Totali', fontweight='bold')
|
| 645 |
+
ax.set_title('Velocità vs G Forces')
|
| 646 |
+
ax.grid(True, alpha=0.3)
|
| 647 |
+
plt.colorbar(scatter, ax=ax, label='Throttle %')
|
| 648 |
+
|
| 649 |
+
# 4. Brake vs Throttle scatter
|
| 650 |
+
ax = fig.add_subplot(gs[1, 2])
|
| 651 |
+
brake_points = self.brake == 1
|
| 652 |
+
coast_points = (self.throttle < 10) & (self.brake == 0)
|
| 653 |
+
throttle_points = self.throttle > 10
|
| 654 |
+
|
| 655 |
+
if np.any(brake_points):
|
| 656 |
+
ax.scatter(self.speed[brake_points], self.total_g_xy()[brake_points],
|
| 657 |
+
color='red', s=10, alpha=0.5, label='Brake')
|
| 658 |
+
if np.any(throttle_points):
|
| 659 |
+
ax.scatter(self.speed[throttle_points], self.total_g_xy()[throttle_points],
|
| 660 |
+
color='green', s=10, alpha=0.5, label='Throttle')
|
| 661 |
+
if np.any(coast_points):
|
| 662 |
+
ax.scatter(self.speed[coast_points], self.total_g_xy()[coast_points],
|
| 663 |
+
color='gray', s=10, alpha=0.3, label='Coast')
|
| 664 |
+
|
| 665 |
+
ax.set_xlabel('Velocità (km/h)', fontweight='bold')
|
| 666 |
+
ax.set_ylabel('G Totali', fontweight='bold')
|
| 667 |
+
ax.set_title('Fasi di Guida')
|
| 668 |
+
handles, labels = ax.get_legend_handles_labels()
|
| 669 |
+
if labels:
|
| 670 |
+
ax.legend()
|
| 671 |
+
ax.grid(True, alpha=0.3)
|
| 672 |
+
|
| 673 |
+
# 5. Timeline pushing intensity
|
| 674 |
+
ax = fig.add_subplot(gs[2, :])
|
| 675 |
+
time = np.arange(len(self.speed))
|
| 676 |
+
|
| 677 |
+
# Calcola pushing intensity istantaneo
|
| 678 |
+
instant_push = self.grip_usage_percent()
|
| 679 |
+
|
| 680 |
+
ax.fill_between(time, 0, instant_push, alpha=0.6, color='#e74c3c', label='Grip Usage %')
|
| 681 |
+
ax.plot(time, self.speed / self.speed.max() * 100,
|
| 682 |
+
color='#3498db', linewidth=1.5, alpha=0.8, label='Velocità (norm)')
|
| 683 |
+
|
| 684 |
+
# Evidenzia zone di massima spinta
|
| 685 |
+
high_push = instant_push > 70
|
| 686 |
+
if np.any(high_push):
|
| 687 |
+
ax.fill_between(time, 0, 100, where=high_push,
|
| 688 |
+
alpha=0.2, color='red', label='Zona Spinta Max')
|
| 689 |
+
|
| 690 |
+
ax.set_xlabel('Campioni (Tempo)', fontweight='bold')
|
| 691 |
+
ax.set_ylabel('Intensità (%)', fontweight='bold')
|
| 692 |
+
ax.set_title('Timeline Intensità Spinta')
|
| 693 |
+
ax.set_ylim(0, 100)
|
| 694 |
+
handles, labels = ax.get_legend_handles_labels()
|
| 695 |
+
if labels:
|
| 696 |
+
ax.legend(loc='upper right')
|
| 697 |
+
ax.grid(True, alpha=0.3)
|
| 698 |
+
|
| 699 |
+
try:
|
| 700 |
+
with warnings.catch_warnings():
|
| 701 |
+
warnings.simplefilter("ignore", UserWarning)
|
| 702 |
+
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
|
| 703 |
+
except Exception:
|
| 704 |
+
pass
|
| 705 |
+
return fig
|
| 706 |
+
|
| 707 |
+
def _plot_gauge(self, ax, value):
|
| 708 |
+
"""Disegna un gauge per il pushing score"""
|
| 709 |
+
# Sfondo gauge
|
| 710 |
+
theta = np.linspace(0, np.pi, 100)
|
| 711 |
+
|
| 712 |
+
# Arco di sfondo
|
| 713 |
+
ax.plot(np.cos(theta), np.sin(theta), 'lightgray', linewidth=20, solid_capstyle='round')
|
| 714 |
+
|
| 715 |
+
# Arco colorato in base al valore
|
| 716 |
+
if value < 30:
|
| 717 |
+
color = '#2ecc71' # Verde
|
| 718 |
+
elif value < 50:
|
| 719 |
+
color = '#f39c12' # Giallo
|
| 720 |
+
elif value < 70:
|
| 721 |
+
color = '#e67e22' # Arancione
|
| 722 |
+
else:
|
| 723 |
+
color = '#e74c3c' # Rosso
|
| 724 |
+
|
| 725 |
+
# Disegna l'arco fino al valore
|
| 726 |
+
theta_val = np.linspace(0, np.pi * (value/100), 50)
|
| 727 |
+
ax.plot(np.cos(theta_val), np.sin(theta_val), color, linewidth=20, solid_capstyle='round')
|
| 728 |
+
|
| 729 |
+
# Testo centrale
|
| 730 |
+
ax.text(0, -0.3, f'{value:.1f}', ha='center', va='center',
|
| 731 |
+
fontsize=48, fontweight='bold', color=color)
|
| 732 |
+
ax.text(0, -0.5, 'PUSHING SCORE', ha='center', va='center',
|
| 733 |
+
fontsize=14, color='gray')
|
| 734 |
+
|
| 735 |
+
# Etichette
|
| 736 |
+
ax.text(-1, 0, '0', ha='center', va='center', fontsize=12, fontweight='bold')
|
| 737 |
+
ax.text(1, 0, '100', ha='center', va='center', fontsize=12, fontweight='bold')
|
| 738 |
+
ax.text(-0.7, 0.7, 'GESTIONE', ha='center', va='center', fontsize=10, color='#2ecc71')
|
| 739 |
+
ax.text(0.7, 0.7, 'SPINTA', ha='center', va='center', fontsize=10, color='#e74c3c')
|
| 740 |
+
|
| 741 |
+
ax.set_xlim(-1.5, 1.5)
|
| 742 |
+
ax.set_ylim(-0.7, 1.2)
|
| 743 |
+
ax.axis('off')
|
| 744 |
+
ax.set_aspect('equal')
|
| 745 |
+
|
| 746 |
+
def plot_all(self, save_path: Optional[str] = None):
|
| 747 |
+
"""
|
| 748 |
+
Genera tutti i grafici
|
| 749 |
+
save_path: se specificato, salva i grafici invece di mostrarli
|
| 750 |
+
"""
|
| 751 |
+
if not save_path:
|
| 752 |
+
plt.close('all')
|
| 753 |
+
|
| 754 |
+
print("Generazione grafici in corso...\n")
|
| 755 |
+
|
| 756 |
+
# Grafico 1: G Forces
|
| 757 |
+
print("1/4 - Analisi Forze G...")
|
| 758 |
+
fig1 = self.plot_g_forces_map()
|
| 759 |
+
if save_path:
|
| 760 |
+
fig1.savefig(f'{save_path}_g_forces.png', dpi=150, bbox_inches='tight')
|
| 761 |
+
print(f" ✓ Salvato: {save_path}_g_forces.png")
|
| 762 |
+
|
| 763 |
+
# Grafico 2: Driver Inputs
|
| 764 |
+
print("2/4 - Input del Pilota...")
|
| 765 |
+
fig2 = self.plot_driver_inputs()
|
| 766 |
+
if save_path:
|
| 767 |
+
fig2.savefig(f'{save_path}_inputs.png', dpi=150, bbox_inches='tight')
|
| 768 |
+
print(f" ✓ Salvato: {save_path}_inputs.png")
|
| 769 |
+
|
| 770 |
+
# Grafico 3: Tire Management
|
| 771 |
+
print("3/4 - Gestione Gomme...")
|
| 772 |
+
fig3 = self.plot_tire_management()
|
| 773 |
+
if save_path:
|
| 774 |
+
fig3.savefig(f'{save_path}_tires.png', dpi=150, bbox_inches='tight')
|
| 775 |
+
print(f" ✓ Salvato: {save_path}_tires.png")
|
| 776 |
+
|
| 777 |
+
# Grafico 4: Pushing Analysis
|
| 778 |
+
print("4/4 - Analisi Spinta...")
|
| 779 |
+
fig4 = self.plot_pushing_analysis()
|
| 780 |
+
if save_path:
|
| 781 |
+
fig4.savefig(f'{save_path}_pushing.png', dpi=150, bbox_inches='tight')
|
| 782 |
+
print(f" ✓ Salvato: {save_path}_pushing.png")
|
| 783 |
+
|
| 784 |
+
print("\nTutti i grafici generati con successo!")
|
| 785 |
+
|
| 786 |
+
if not save_path:
|
| 787 |
+
plt.show()
|
| 788 |
+
input("\n[INVIO per continuare...]")
|
| 789 |
+
plt.close('all')
|
| 790 |
+
else:
|
| 791 |
+
plt.close('all')
|
| 792 |
+
|
| 793 |
+
def print_summary(self):
|
| 794 |
+
"""Stampa un report testuale completo"""
|
| 795 |
+
pushing_score = self.pushing_score()
|
| 796 |
+
mode = self.get_driving_mode()
|
| 797 |
+
|
| 798 |
+
print("=" * 60)
|
| 799 |
+
print("TELEMETRY ANALYSIS REPORT".center(60))
|
| 800 |
+
print("=" * 60)
|
| 801 |
+
print()
|
| 802 |
+
print(f"PUSHING SCORE: {pushing_score:.1f}/100")
|
| 803 |
+
print(f"DRIVING MODE: {mode}")
|
| 804 |
+
print()
|
| 805 |
+
print("-" * 60)
|
| 806 |
+
print("METRICHE SEMPLICI:")
|
| 807 |
+
print("-" * 60)
|
| 808 |
+
print(f" - Velocità Media: {self.avg_speed():.1f} km/h")
|
| 809 |
+
print(f" - Velocità Massima: {self.max_speed():.1f} km/h")
|
| 810 |
+
print(f" - Max G Laterali: {np.max(np.abs(self.lateral_g())):.2f} G")
|
| 811 |
+
print(f" - Max G Longitudinali: {np.max(self.longitudinal_g()):.2f} G")
|
| 812 |
+
print(f" - Max G Totali: {np.max(self.total_g_xy()):.2f} G")
|
| 813 |
+
print(f" - Tempo in Frenata: {self.brake_time_percent():.1f}%")
|
| 814 |
+
print(f" - Gas Spalancato: {self.full_throttle_percent():.1f}%")
|
| 815 |
+
print(f" - Degrado Gomme: {self.tire_wear_total():.1f}%")
|
| 816 |
+
print()
|
| 817 |
+
print("-" * 60)
|
| 818 |
+
print("METRICHE COMPLESSE:")
|
| 819 |
+
print("-" * 60)
|
| 820 |
+
print(f" • Utilizzo Grip Medio: {np.mean(self.grip_usage_percent()):.1f}%")
|
| 821 |
+
print(f" • Smoothness Index: {self.smoothness_index():.3f}")
|
| 822 |
+
print(f" • Aggressività Curve: {self.corner_aggression():.1f}")
|
| 823 |
+
print(f" • Aggressività Frenata: {self.braking_aggression():.1f}")
|
| 824 |
+
print(f" • Velocità in Curva: {self.corner_speed_index():.1f} km/h")
|
| 825 |
+
print(f" • Tire Stress Score: {self.tire_stress_score():.1f}")
|
| 826 |
+
print()
|
| 827 |
+
print("=" * 60)
|
| 828 |
+
print()
|
| 829 |
+
|
| 830 |
+
# Interpretazione
|
| 831 |
+
if pushing_score < 30:
|
| 832 |
+
print("INTERPRETAZIONE:")
|
| 833 |
+
print(" Il pilota sta GESTENDO. Guida conservativa,")
|
| 834 |
+
print(" probabilmente per preservare gomme o macchina.")
|
| 835 |
+
elif pushing_score < 50:
|
| 836 |
+
print("INTERPRETAZIONE:")
|
| 837 |
+
print(" Ritmo di GARA. Il pilota spinge ma in modo controllato.")
|
| 838 |
+
elif pushing_score < 70:
|
| 839 |
+
print("INTERPRETAZIONE:")
|
| 840 |
+
print(" Il pilota sta SPINGENDO. Vicino al limite della mac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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from src.analysis.Curve import Curve
|
| 5 |
+
from src.analysis.utils_for_array import *
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CurveDetector:
|
| 13 |
+
# ================== PARAMETRI DA TARARE (default) ==================
|
| 14 |
+
ACC_ENTER_THR_DEFAULT = 3.0 # entra in curva se |acc_y| > di questo
|
| 15 |
+
ACC_EXIT_THR_DEFAULT = 2.5 # esci se |acc_y| < di questo (leggermente più basso = isteresi)
|
| 16 |
+
SMOOTH_WIN_DEFAULT = 3 # smoothing su acc_y
|
| 17 |
+
MIN_SAMPLES_IN_CURVE_DEFAULT = 5 # minimo punti per dire che è davvero curva
|
| 18 |
+
MAX_SAMPLES_IN_CURVE_DEFAULT = 25 # grandezza massima curva
|
| 19 |
+
# ===================================================================
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
telemetry_filename: str,
|
| 24 |
+
corners_filename: str,
|
| 25 |
+
acc_enter_thr: float = None,
|
| 26 |
+
acc_exit_thr: float = None,
|
| 27 |
+
smooth_win: int = None,
|
| 28 |
+
min_samples_in_curve: int = None,
|
| 29 |
+
max_samples_in_curve: int = None,
|
| 30 |
+
):
|
| 31 |
+
|
| 32 |
+
self.ACC_ENTER_THR = acc_enter_thr if acc_enter_thr is not None else self.ACC_ENTER_THR_DEFAULT
|
| 33 |
+
self.ACC_EXIT_THR = acc_exit_thr if acc_exit_thr is not None else self.ACC_EXIT_THR_DEFAULT
|
| 34 |
+
self.SMOOTH_WIN = smooth_win if smooth_win is not None else self.SMOOTH_WIN_DEFAULT
|
| 35 |
+
self.MIN_SAMPLES_IN_CURVE = (
|
| 36 |
+
min_samples_in_curve if min_samples_in_curve is not None else self.MIN_SAMPLES_IN_CURVE_DEFAULT
|
| 37 |
+
)
|
| 38 |
+
self.MAX_SAMPLES_IN_CURVE = (
|
| 39 |
+
max_samples_in_curve if max_samples_in_curve is not None else self.MAX_SAMPLES_IN_CURVE_DEFAULT
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
self.telemetry_filename = telemetry_filename
|
| 44 |
+
self.corners_filename = corners_filename
|
| 45 |
+
|
| 46 |
+
# --- Tire Info Extraction ---
|
| 47 |
+
self.compound = "UNKNOWN"
|
| 48 |
+
self.tire_life = 0
|
| 49 |
+
self.stint = 0
|
| 50 |
+
|
| 51 |
+
# --- 1) carico telemetria ---
|
| 52 |
+
with open(telemetry_filename, "r") as f:
|
| 53 |
+
tel_data = json.load(f)
|
| 54 |
+
|
| 55 |
+
tel = tel_data["tel"]
|
| 56 |
+
self.rpm = tel["rpm"]
|
| 57 |
+
self.speed = tel["speed"]
|
| 58 |
+
self.gear = tel["gear"]
|
| 59 |
+
self.acc_x = tel["acc_x"]
|
| 60 |
+
self.acc_z = tel["acc_z"]
|
| 61 |
+
self.x = tel["x"]
|
| 62 |
+
self.y = tel["y"]
|
| 63 |
+
self.z = tel["z"]
|
| 64 |
+
self.time = tel["time"]
|
| 65 |
+
self.acc_y = tel["acc_y"]
|
| 66 |
+
self.tel_dist = tel["distance"]
|
| 67 |
+
self.throttle = tel["throttle"]
|
| 68 |
+
self.brake = tel["brake"]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# --- 2) carico corner map ---
|
| 72 |
+
with open(corners_filename, "r") as f:
|
| 73 |
+
corner_map = json.load(f)
|
| 74 |
+
|
| 75 |
+
self.corner_numbers = corner_map["CornerNumber"]
|
| 76 |
+
self.corner_distances = corner_map["Distance"]
|
| 77 |
+
self.corner_X = corner_map["X"]
|
| 78 |
+
self.corner_Y = corner_map["Y"]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# -------------------------------------------------------------
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def distanza(self, p1, p2):
|
| 85 |
+
if len(p1) != len(p2):
|
| 86 |
+
raise ValueError("I due punti devono avere la stessa dimensione")
|
| 87 |
+
somma = 0
|
| 88 |
+
|
| 89 |
+
for a, b in zip(p1, p2):
|
| 90 |
+
somma += (b - a) ** 2
|
| 91 |
+
return math.sqrt(somma)
|
| 92 |
+
|
| 93 |
+
def nearest_point_index(self,xs, ys, cx, cy):
|
| 94 |
+
"""Ritorna (idx, dist) del punto (xs[idx], ys[idx]) più vicino a (cx, cy)."""
|
| 95 |
+
best_idx = None
|
| 96 |
+
best_dist = float("inf")
|
| 97 |
+
for idx, (x, y) in enumerate(zip(xs, ys)):
|
| 98 |
+
d = self.distanza((x, y), (cx, cy))
|
| 99 |
+
if d < best_dist:
|
| 100 |
+
best_dist = d
|
| 101 |
+
best_idx = idx
|
| 102 |
+
return best_idx, best_dist
|
| 103 |
+
|
| 104 |
+
def compaund_and_life(self):
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
dir_path = os.path.dirname(self.telemetry_filename)
|
| 108 |
+
base_name = os.path.basename(self.telemetry_filename)
|
| 109 |
+
# Extract lap number from filename (e.g., "12_tel.json" -> 12)
|
| 110 |
+
parts = base_name.split("_")
|
| 111 |
+
if parts[0].isdigit():
|
| 112 |
+
current_lap = int(parts[0]) - 1
|
| 113 |
+
|
| 114 |
+
laptimes_path = os.path.join(dir_path, "laptimes.json")
|
| 115 |
+
if os.path.exists(laptimes_path):
|
| 116 |
+
with open(laptimes_path, "r") as f:
|
| 117 |
+
laptimes_data = json.load(f)
|
| 118 |
+
|
| 119 |
+
if "lap" in laptimes_data:
|
| 120 |
+
|
| 121 |
+
if current_lap != -1:
|
| 122 |
+
if "compound" in laptimes_data:
|
| 123 |
+
self.compound = laptimes_data["compound"][current_lap]
|
| 124 |
+
if "life" in laptimes_data:
|
| 125 |
+
self.tire_life = laptimes_data["life"][current_lap]
|
| 126 |
+
if "stint" in laptimes_data:
|
| 127 |
+
self.stint = laptimes_data["stint"][current_lap]
|
| 128 |
+
|
| 129 |
+
except Exception as e:
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def isApexInInterval(self, index_end, index_start):
|
| 135 |
+
if index_start > self.index_center_current_corner:
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
if index_end < self.index_center_current_corner:
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
return True
|
| 142 |
+
|
| 143 |
+
def getBounds(self, curve_number, corner_point, prev_corner, next_corner, n_corners):
|
| 144 |
+
DEFAULT_FIRST_DISTANCE_CURVE = 150
|
| 145 |
+
DEFAULT_LAST_DISTANCE_CURVE = 250
|
| 146 |
+
|
| 147 |
+
if curve_number == 0:
|
| 148 |
+
lower_bound = corner_point - DEFAULT_FIRST_DISTANCE_CURVE
|
| 149 |
+
else:
|
| 150 |
+
lower_bound = 0.5 * (prev_corner + corner_point)
|
| 151 |
+
|
| 152 |
+
if curve_number == n_corners - 1:
|
| 153 |
+
upper_bound = corner_point + DEFAULT_LAST_DISTANCE_CURVE
|
| 154 |
+
else:
|
| 155 |
+
upper_bound = 0.5 * (corner_point + next_corner)
|
| 156 |
+
|
| 157 |
+
return lower_bound, upper_bound
|
| 158 |
+
|
| 159 |
+
def getCurveWindow(self, start_win_idx, end_win_idx, curve_number):
|
| 160 |
+
in_curve = False
|
| 161 |
+
curve_start_idx = None
|
| 162 |
+
curve_end_idx = None
|
| 163 |
+
|
| 164 |
+
for idx in range(start_win_idx, end_win_idx + 1):
|
| 165 |
+
acc_smooth = avg_in_window(self.acc_y, idx, self.SMOOTH_WIN)
|
| 166 |
+
if not in_curve:
|
| 167 |
+
if acc_smooth >= self.ACC_ENTER_THR:
|
| 168 |
+
in_curve = True
|
| 169 |
+
curve_start_idx = idx
|
| 170 |
+
else:
|
| 171 |
+
if acc_smooth <= self.ACC_EXIT_THR:
|
| 172 |
+
if not self.isApexInInterval( idx, curve_start_idx):
|
| 173 |
+
in_curve = False
|
| 174 |
+
curve_start_idx = None
|
| 175 |
+
else:
|
| 176 |
+
curve_end_idx = idx
|
| 177 |
+
break
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# se sono arrivato alla fine finestra e sono ancora "in curva"
|
| 181 |
+
if in_curve and curve_end_idx is None:
|
| 182 |
+
curve_end_idx = end_win_idx
|
| 183 |
+
|
| 184 |
+
if curve_start_idx is not None:
|
| 185 |
+
if not self.isApexInInterval(curve_end_idx, curve_start_idx):
|
| 186 |
+
curve_end_idx = None
|
| 187 |
+
curve_start_idx = None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
return curve_start_idx, curve_end_idx
|
| 192 |
+
|
| 193 |
+
def calcolo_curve(self) -> list:
|
| 194 |
+
|
| 195 |
+
self.compaund_and_life()
|
| 196 |
+
|
| 197 |
+
detected_corners = []
|
| 198 |
+
|
| 199 |
+
n_corners = len(self.corner_distances)
|
| 200 |
+
|
| 201 |
+
for i in range(0,n_corners):
|
| 202 |
+
|
| 203 |
+
self.index_center_current_corner, _ = self.nearest_point_index(self.x,self.y ,self.corner_X[i],self.corner_Y[i])
|
| 204 |
+
current_corner_distance = self.tel_dist[self.index_center_current_corner]
|
| 205 |
+
|
| 206 |
+
prev_center_curve = 0
|
| 207 |
+
next_center_curve = 0
|
| 208 |
+
|
| 209 |
+
if (i > 0):
|
| 210 |
+
prev_index_center_current_corner, _ = self.nearest_point_index(self.x,self.y ,self.corner_X[i-1],self.corner_Y[i-1])
|
| 211 |
+
prev_center_curve = self.tel_dist[prev_index_center_current_corner]
|
| 212 |
+
if (i < n_corners - 1):
|
| 213 |
+
next_index_center_current_corner, _ = self.nearest_point_index(self.x,self.y ,self.corner_X[i+1],self.corner_Y[i+1])
|
| 214 |
+
next_center_curve = self.tel_dist[next_index_center_current_corner]
|
| 215 |
+
|
| 216 |
+
lower_bound, upper_bound = self.getBounds(i, current_corner_distance, prev_center_curve, next_center_curve, n_corners)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
start_win_idx = find_frist_value(self.tel_dist, lower_bound)
|
| 220 |
+
end_win_idx = find_last_value(self.tel_dist, upper_bound)
|
| 221 |
+
|
| 222 |
+
curve_start_idx, curve_end_idx = self.getCurveWindow(start_win_idx, end_win_idx, i)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
if curve_start_idx is not None and curve_end_idx is not None:
|
| 226 |
+
lenght_curve = curve_end_idx - curve_start_idx + 1
|
| 227 |
+
if lenght_curve >= self.MIN_SAMPLES_IN_CURVE:
|
| 228 |
+
|
| 229 |
+
distance_from_start = self.index_center_current_corner - curve_start_idx
|
| 230 |
+
distance_from_end = curve_end_idx - self.index_center_current_corner
|
| 231 |
+
|
| 232 |
+
MARGIN_BEFORE = 25
|
| 233 |
+
MARGIN_AFTER = 25
|
| 234 |
+
|
| 235 |
+
# se la curva inizia troppo lontano dall'apice → avvicino lo start
|
| 236 |
+
if distance_from_start > MARGIN_BEFORE:
|
| 237 |
+
curve_start_idx = self.index_center_current_corner - MARGIN_BEFORE
|
| 238 |
+
|
| 239 |
+
# se la curva finisce troppo lontano dall'apice → avvicino l'end
|
| 240 |
+
if distance_from_end > MARGIN_AFTER:
|
| 241 |
+
curve_end_idx = self.index_center_current_corner + MARGIN_AFTER
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
curve = Curve(
|
| 246 |
+
corner_id=self.corner_numbers[i],
|
| 247 |
+
current_corner_dist=current_corner_distance,
|
| 248 |
+
lower_bound=lower_bound,
|
| 249 |
+
upper_bound=upper_bound,
|
| 250 |
+
compound=self.compound,
|
| 251 |
+
life= self.tire_life,
|
| 252 |
+
stint= self.stint,
|
| 253 |
+
time=self.time[curve_start_idx:curve_end_idx],
|
| 254 |
+
rpm=self.rpm[curve_start_idx:curve_end_idx],
|
| 255 |
+
speed=self.speed[curve_start_idx:curve_end_idx],
|
| 256 |
+
throttle=self.throttle[curve_start_idx:curve_end_idx],
|
| 257 |
+
brake=self.brake[curve_start_idx:curve_end_idx],
|
| 258 |
+
distance=self.tel_dist[curve_start_idx:curve_end_idx],
|
| 259 |
+
acc_x=self.acc_x[curve_start_idx:curve_end_idx],
|
| 260 |
+
acc_y=self.acc_y[curve_start_idx:curve_end_idx],
|
| 261 |
+
acc_z=self.acc_z[curve_start_idx:curve_end_idx],
|
| 262 |
+
x=self.x[curve_start_idx:curve_end_idx],
|
| 263 |
+
y=self.y[curve_start_idx:curve_end_idx],
|
| 264 |
+
z=self.z[curve_start_idx:curve_end_idx],
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
detected_corners.append(curve)
|
| 268 |
+
|
| 269 |
+
return detected_corners
|
| 270 |
+
|
| 271 |
+
def grafico(self, detected_corners, block=True):
|
| 272 |
+
|
| 273 |
+
fig, ax1 = plt.subplots(figsize=(12, 5))
|
| 274 |
+
|
| 275 |
+
# acc_y
|
| 276 |
+
ax1.plot(self.time, self.acc_y, color='tab:blue', label='Acc Y (m/s²)')
|
| 277 |
+
ax1.set_xlabel('Tempo (s)')
|
| 278 |
+
ax1.set_ylabel('Acc Y (m/s²)', color='tab:blue')
|
| 279 |
+
ax1.tick_params(axis='y', labelcolor='tab:blue')
|
| 280 |
+
|
| 281 |
+
# secondo asse: throttle/brake
|
| 282 |
+
ax2 = ax1.twinx()
|
| 283 |
+
ax2.plot(self.time, self.throttle, color='tab:red', alpha=0.5, label='Throttle (%)')
|
| 284 |
+
ax2.plot(self.time, self.brake, color='tab:green', alpha=0.5, label='Brake (%)')
|
| 285 |
+
ax2.set_ylabel('Throttle / Brake (%)', color='tab:red')
|
| 286 |
+
ax2.tick_params(axis='y', labelcolor='tab:red')
|
| 287 |
+
|
| 288 |
+
i=0
|
| 289 |
+
for c in detected_corners:
|
| 290 |
+
# verticale del punto TEORICO (apice curva)
|
| 291 |
+
|
| 292 |
+
theo_idx, _ = self.nearest_point_index(self.x, self.y, self.corner_X[i], self.corner_Y[i])
|
| 293 |
+
ax1.axvline(self.time[theo_idx], color='black', linestyle='--', linewidth=1, alpha=0.5)
|
| 294 |
+
i+=1
|
| 295 |
+
# finestra di ricerca [lower_bound, upper_bound]
|
| 296 |
+
left_idx = find_frist_value(self.tel_dist, c.lower_bound)
|
| 297 |
+
right_idx = find_last_value(self.tel_dist, c.upper_bound)
|
| 298 |
+
ax1.axvspan(self.time[left_idx], self.time[right_idx], color='gray', alpha=0.05)
|
| 299 |
+
|
| 300 |
+
# evidenzia la curva trovata (se presente)
|
| 301 |
+
if len(c.time) > 0:
|
| 302 |
+
ax1.axvspan(c.time[0], c.time[-1], color='orange', alpha=0.2)
|
| 303 |
+
|
| 304 |
+
# legenda
|
| 305 |
+
l1, lab1 = ax1.get_legend_handles_labels()
|
| 306 |
+
l2, lab2 = ax2.get_legend_handles_labels()
|
| 307 |
+
ax1.legend(l1 + l2, lab1 + lab2, loc='upper right')
|
| 308 |
+
|
| 309 |
+
ax1.set_title("Raffinamento curve con finestra per distanza")
|
| 310 |
+
fig.tight_layout()
|
| 311 |
+
plt.show(block=block)
|
| 312 |
+
|
| 313 |
+
def plot_curve_trajectories(self, detected_corners, show_apex=True, block=True):
|
| 314 |
+
"""
|
| 315 |
+
Disegna la traiettoria XY del giro completo e, sopra,
|
| 316 |
+
evidenzia per ogni curva il tratto effettivo percorso dal pilota.
|
| 317 |
+
|
| 318 |
+
Parametri
|
| 319 |
+
----------
|
| 320 |
+
detected_corners : list[Curve]
|
| 321 |
+
Lista di oggetti Curve restituiti da calcolo_curve().
|
| 322 |
+
show_apex : bool
|
| 323 |
+
Se True, marca anche il punto dell'apice per ogni curva.
|
| 324 |
+
"""
|
| 325 |
+
fig, ax = plt.subplots(figsize=(8, 8))
|
| 326 |
+
|
| 327 |
+
# Disegno l'intero giro in grigio chiaro
|
| 328 |
+
ax.plot(self.x, self.y, linewidth=1, alpha=0.3, label="Giro completo")
|
| 329 |
+
|
| 330 |
+
# Per ogni curva, evidenzio la traiettoria dentro la curva
|
| 331 |
+
|
| 332 |
+
for c in detected_corners:
|
| 333 |
+
|
| 334 |
+
# Traiettoria effettiva nella curva (già slice dell'intera telemetria)
|
| 335 |
+
ax.plot(c.x, c.y, linewidth=2, label=f"Curva {c.corner_id}")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
i=0
|
| 340 |
+
for curve in self.corner_X:
|
| 341 |
+
try:
|
| 342 |
+
apex_idx_local = find_frist_value(c.distance, c.current_corner_dist)
|
| 343 |
+
apex_x = c.x[apex_idx_local]
|
| 344 |
+
apex_y = c.y[apex_idx_local]
|
| 345 |
+
apex_x = self.corner_X[i]
|
| 346 |
+
apex_y = self.corner_Y [i]
|
| 347 |
+
i+=1
|
| 348 |
+
ax.scatter(apex_x, apex_y, s=40, marker="x", color="red")
|
| 349 |
+
ax.text(
|
| 350 |
+
apex_x,
|
| 351 |
+
apex_y,
|
| 352 |
+
f"{i}",
|
| 353 |
+
fontsize=8,
|
| 354 |
+
color="red",
|
| 355 |
+
ha="left",
|
| 356 |
+
va="bottom",
|
| 357 |
+
)
|
| 358 |
+
except Exception:
|
| 359 |
+
# Se qualcosa va storto, semplicemente non disegno il marker
|
| 360 |
+
pass
|
| 361 |
+
# i=0
|
| 362 |
+
# for curve in self.corner_distances:
|
| 363 |
+
# try:
|
| 364 |
+
# apex_idx_local = find_frist_value(self.tel_dist, curve)
|
| 365 |
+
# print(f"{self.tel_dist[apex_idx_local]} distanza pilota")
|
| 366 |
+
# print(f"{self.tel_dist[apex_idx_local]} distanza pilota")
|
| 367 |
+
# apex_x = self.x[apex_idx_local]
|
| 368 |
+
# apex_y = self.y[apex_idx_local]
|
| 369 |
+
# print(f"n:{apex_x}, {apex_y}")
|
| 370 |
+
# i+=1
|
| 371 |
+
# ax.scatter(apex_x, apex_y, s=40, marker="x", color="blue")
|
| 372 |
+
# ax.text(
|
| 373 |
+
# apex_x,
|
| 374 |
+
# apex_y,
|
| 375 |
+
# f"{i}",
|
| 376 |
+
# fontsize=8,
|
| 377 |
+
# color="red",
|
| 378 |
+
# ha="left",
|
| 379 |
+
# va="bottom",
|
| 380 |
+
# )
|
| 381 |
+
# except Exception:
|
| 382 |
+
# # Se qualcosa va storto, semplicemente non disegno il marker
|
| 383 |
+
# pass
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# --- nel tuo plotting ---
|
| 387 |
+
i = 0
|
| 388 |
+
for cx, cy in zip(self.corner_X, self.corner_Y):
|
| 389 |
+
try:
|
| 390 |
+
apex_idx_local, dmin = self.nearest_point_index(self.x, self.y, cx, cy)
|
| 391 |
+
|
| 392 |
+
# print(f"{apex_idx_local} indice (dist={dmin})")
|
| 393 |
+
apex_x = self.x[apex_idx_local]
|
| 394 |
+
apex_y = self.y[apex_idx_local]
|
| 395 |
+
# print(f"n:{apex_x}, {apex_y}")
|
| 396 |
+
|
| 397 |
+
i += 1
|
| 398 |
+
ax.scatter(apex_x, apex_y, s=40, marker="x", color="green")
|
| 399 |
+
ax.text(apex_x, apex_y, f"{i}", fontsize=8, color="red", ha="left", va="bottom")
|
| 400 |
+
except Exception:
|
| 401 |
+
pass
|
| 402 |
+
|
| 403 |
+
ax.set_xlabel("X (m)")
|
| 404 |
+
ax.set_ylabel("Y (m)")
|
| 405 |
+
ax.set_title("Traiettoria in curva (XY)")
|
| 406 |
+
|
| 407 |
+
# Scala uguale sugli assi per non deformare la pista
|
| 408 |
+
ax.set_aspect("equal", adjustable="box")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
plt.tight_layout()
|
| 412 |
+
plt.show(block=block)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
|
analysis/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Analysis subpackage - Data analysis and curve detection
|
| 2 |
+
from src.analysis.Curve import Curve
|
| 3 |
+
from src.analysis.CurveDetector import CurveDetector
|
analysis/__pycache__/Curve.cpython-313.pyc
ADDED
|
Binary file (42.3 kB). View file
|
|
|
analysis/__pycache__/CurveDetector.cpython-313.pyc
ADDED
|
Binary file (16.1 kB). View file
|
|
|
analysis/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (280 Bytes). View file
|
|
|
analysis/__pycache__/dataset_normalization.cpython-313.pyc
ADDED
|
Binary file (16.9 kB). View file
|
|
|
analysis/__pycache__/utils_for_array.cpython-313.pyc
ADDED
|
Binary file (1.49 kB). View file
|
|
|
analysis/dataset_builder.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import logging
|
| 6 |
+
import gc
|
| 7 |
+
from dataclasses import dataclass, field
|
| 8 |
+
from typing import List, Optional, Dict, Any
|
| 9 |
+
|
| 10 |
+
from src.analysis.CurveDetector import CurveDetector
|
| 11 |
+
|
| 12 |
+
# ============================================================================
|
| 13 |
+
# CONSTANTS
|
| 14 |
+
# ============================================================================
|
| 15 |
+
BASE_DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data"))
|
| 16 |
+
|
| 17 |
+
DEFAULT_OUTPUT_FILE = os.path.join(BASE_DATA_DIR, "dataset", "dataset_curves.csv")
|
| 18 |
+
MAX_POINTS = 50
|
| 19 |
+
PADDING_VALUE = -1000
|
| 20 |
+
|
| 21 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ============================================================================
|
| 26 |
+
# CONFIGURATION
|
| 27 |
+
# ============================================================================
|
| 28 |
+
@dataclass
|
| 29 |
+
class DatasetConfig:
|
| 30 |
+
"""
|
| 31 |
+
Configuration for dataset building.
|
| 32 |
+
|
| 33 |
+
Attributes:
|
| 34 |
+
years: List of years to include (e.g., [2024, 2025]). If None, includes all available.
|
| 35 |
+
drivers: List of driver codes to include (e.g., ["LEC", "HAM"]). If None, includes all.
|
| 36 |
+
sessions: List of sessions to process (e.g., ["Race", "Qualifying"]).
|
| 37 |
+
output_file: Path to the output CSV file.
|
| 38 |
+
max_points: Maximum number of data points per curve.
|
| 39 |
+
padding_value: Value used for padding shorter curves.
|
| 40 |
+
"""
|
| 41 |
+
years: Optional[List[int]] = None
|
| 42 |
+
drivers: Optional[List[str]] = None
|
| 43 |
+
sessions: List[str] = field(default_factory=lambda: ["Race"])
|
| 44 |
+
output_file: str = DEFAULT_OUTPUT_FILE
|
| 45 |
+
max_points: int = MAX_POINTS
|
| 46 |
+
padding_value: float = PADDING_VALUE
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ============================================================================
|
| 50 |
+
# UTILITY FUNCTIONS
|
| 51 |
+
# ============================================================================
|
| 52 |
+
def get_padded_array(arr: Any, max_len: int = MAX_POINTS, padding: float = PADDING_VALUE) -> np.ndarray:
|
| 53 |
+
"""
|
| 54 |
+
Pads or truncates an array to a fixed length.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
arr: Input array (list or numpy array).
|
| 58 |
+
max_len: Target length for the output array.
|
| 59 |
+
padding: Value used for padding.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
Numpy array of length max_len.
|
| 63 |
+
"""
|
| 64 |
+
if not isinstance(arr, (list, np.ndarray)):
|
| 65 |
+
arr = []
|
| 66 |
+
|
| 67 |
+
arr = np.array(arr)
|
| 68 |
+
|
| 69 |
+
if len(arr) == 0:
|
| 70 |
+
return np.full(max_len, padding)
|
| 71 |
+
|
| 72 |
+
if len(arr) > max_len:
|
| 73 |
+
return arr[:max_len]
|
| 74 |
+
|
| 75 |
+
return np.pad(arr, (0, max_len - len(arr)), 'constant', constant_values=padding)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def get_data_directories(years: Optional[List[int]] = None) -> List[str]:
|
| 79 |
+
"""
|
| 80 |
+
Gets data directories based on specified years.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
years: List of years to include. If None, scans for all available years.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
List of absolute paths to data directories.
|
| 87 |
+
"""
|
| 88 |
+
if years is None:
|
| 89 |
+
# Find all available year directories
|
| 90 |
+
directories = []
|
| 91 |
+
if os.path.exists(BASE_DATA_DIR):
|
| 92 |
+
for item in os.listdir(BASE_DATA_DIR):
|
| 93 |
+
item_path = os.path.join(BASE_DATA_DIR, item)
|
| 94 |
+
if os.path.isdir(item_path) and "-main" in item:
|
| 95 |
+
directories.append(item_path)
|
| 96 |
+
return sorted(directories)
|
| 97 |
+
|
| 98 |
+
# Build paths for specific years
|
| 99 |
+
return [
|
| 100 |
+
os.path.join(BASE_DATA_DIR, f"{year}-main")
|
| 101 |
+
for year in years
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def find_corners_file(session_path: str) -> Optional[str]:
|
| 106 |
+
"""
|
| 107 |
+
Finds the corners file in a session directory.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
session_path: Path to the session directory.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
Path to corners file, or None if not found.
|
| 114 |
+
"""
|
| 115 |
+
corners_file = os.path.join(session_path, "corners.json")
|
| 116 |
+
|
| 117 |
+
if os.path.exists(corners_file):
|
| 118 |
+
return corners_file
|
| 119 |
+
|
| 120 |
+
# Look for alternative corners files
|
| 121 |
+
candidates = [
|
| 122 |
+
f for f in os.listdir(session_path)
|
| 123 |
+
if f.startswith("corners") and f.endswith(".json")
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
if candidates:
|
| 127 |
+
return os.path.join(session_path, candidates[0])
|
| 128 |
+
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# ============================================================================
|
| 133 |
+
# CURVE PROCESSING
|
| 134 |
+
# ============================================================================
|
| 135 |
+
def extract_curve_data(
|
| 136 |
+
curve,
|
| 137 |
+
detector: CurveDetector,
|
| 138 |
+
gp_name: str,
|
| 139 |
+
session: str,
|
| 140 |
+
driver: str,
|
| 141 |
+
lap_num: int,
|
| 142 |
+
config: DatasetConfig
|
| 143 |
+
) -> Dict[str, Any]:
|
| 144 |
+
"""
|
| 145 |
+
Extracts data from a single curve into a dictionary.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
curve: Curve object containing telemetry data.
|
| 149 |
+
detector: CurveDetector instance with compound/tire info.
|
| 150 |
+
gp_name: Name of the Grand Prix.
|
| 151 |
+
session: Session name (Race, Qualifying, etc.).
|
| 152 |
+
driver: Driver code.
|
| 153 |
+
lap_num: Lap number.
|
| 154 |
+
config: Dataset configuration.
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
Dictionary with curve data flattened for DataFrame.
|
| 158 |
+
"""
|
| 159 |
+
# Basic metadata
|
| 160 |
+
curve_entry = {
|
| 161 |
+
"GrandPrix": gp_name,
|
| 162 |
+
"Session": session,
|
| 163 |
+
"Driver": driver,
|
| 164 |
+
"Lap": lap_num,
|
| 165 |
+
"CornerID": curve.corner_id,
|
| 166 |
+
"Compound": detector.compound,
|
| 167 |
+
"TireLife": detector.tire_life,
|
| 168 |
+
"Stint": detector.stint
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
# Telemetry arrays to process
|
| 172 |
+
arrays_to_process = {
|
| 173 |
+
"speed": curve.speed,
|
| 174 |
+
"rpm": curve.rpm,
|
| 175 |
+
"throttle": curve.throttle,
|
| 176 |
+
"brake": curve.brake,
|
| 177 |
+
"acc_x": curve.acc_x,
|
| 178 |
+
"acc_y": curve.acc_y,
|
| 179 |
+
"acc_z": curve.acc_z,
|
| 180 |
+
"x": curve.x,
|
| 181 |
+
"y": curve.y,
|
| 182 |
+
"z": curve.z,
|
| 183 |
+
"distance": curve.distance,
|
| 184 |
+
"time": curve.time
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
# Pad and flatten each array into columns
|
| 188 |
+
for name, arr in arrays_to_process.items():
|
| 189 |
+
padded = get_padded_array(arr, config.max_points, config.padding_value)
|
| 190 |
+
for i, value in enumerate(padded):
|
| 191 |
+
curve_entry[f"{name}_{i}"] = value
|
| 192 |
+
|
| 193 |
+
return curve_entry
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def process_lap_telemetry(
|
| 197 |
+
telemetry_file: str,
|
| 198 |
+
corners_file: str,
|
| 199 |
+
gp_name: str,
|
| 200 |
+
session: str,
|
| 201 |
+
driver: str,
|
| 202 |
+
lap_num: int,
|
| 203 |
+
config: DatasetConfig
|
| 204 |
+
) -> List[Dict[str, Any]]:
|
| 205 |
+
"""
|
| 206 |
+
Processes a single lap's telemetry file.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
telemetry_file: Path to telemetry JSON file.
|
| 210 |
+
corners_file: Path to corners JSON file.
|
| 211 |
+
gp_name: Grand Prix name.
|
| 212 |
+
session: Session name.
|
| 213 |
+
driver: Driver code.
|
| 214 |
+
lap_num: Lap number.
|
| 215 |
+
config: Dataset configuration.
|
| 216 |
+
|
| 217 |
+
Returns:
|
| 218 |
+
List of curve data dictionaries.
|
| 219 |
+
"""
|
| 220 |
+
curves_data = []
|
| 221 |
+
|
| 222 |
+
detector = CurveDetector(
|
| 223 |
+
telemetry_filename=telemetry_file,
|
| 224 |
+
corners_filename=corners_file
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
curves = detector.calcolo_curve()
|
| 228 |
+
|
| 229 |
+
for curve in curves:
|
| 230 |
+
curve_data = extract_curve_data(
|
| 231 |
+
curve, detector, gp_name, session, driver, lap_num, config
|
| 232 |
+
)
|
| 233 |
+
curves_data.append(curve_data)
|
| 234 |
+
|
| 235 |
+
return curves_data
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def process_driver(
|
| 239 |
+
driver_path: str,
|
| 240 |
+
corners_file: str,
|
| 241 |
+
gp_name: str,
|
| 242 |
+
session: str,
|
| 243 |
+
driver: str,
|
| 244 |
+
config: DatasetConfig
|
| 245 |
+
) -> List[Dict[str, Any]]:
|
| 246 |
+
"""
|
| 247 |
+
Processes all laps for a single driver.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
driver_path: Path to driver's telemetry directory.
|
| 251 |
+
corners_file: Path to corners JSON file.
|
| 252 |
+
gp_name: Grand Prix name.
|
| 253 |
+
session: Session name.
|
| 254 |
+
driver: Driver code.
|
| 255 |
+
config: Dataset configuration.
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
List of curve data dictionaries.
|
| 259 |
+
"""
|
| 260 |
+
driver_curves_data = []
|
| 261 |
+
|
| 262 |
+
for filename in os.listdir(driver_path):
|
| 263 |
+
if not filename.endswith("_tel.json"):
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
parts = filename.split("_")
|
| 267 |
+
if not parts[0].isdigit():
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
try:
|
| 271 |
+
lap_num = int(parts[0])
|
| 272 |
+
telemetry_file = os.path.join(driver_path, filename)
|
| 273 |
+
|
| 274 |
+
lap_data = process_lap_telemetry(
|
| 275 |
+
telemetry_file, corners_file, gp_name, session, driver, lap_num, config
|
| 276 |
+
)
|
| 277 |
+
driver_curves_data.extend(lap_data)
|
| 278 |
+
|
| 279 |
+
except Exception as e:
|
| 280 |
+
logger.debug(f"Error processing {filename} for {driver}: {e}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
return driver_curves_data
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def process_session(
|
| 287 |
+
gp_path: str,
|
| 288 |
+
session: str,
|
| 289 |
+
config: DatasetConfig
|
| 290 |
+
) -> List[Dict[str, Any]]:
|
| 291 |
+
"""
|
| 292 |
+
Processes a single session (Race, Qualifying, etc.) for a Grand Prix.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
gp_path: Path to Grand Prix directory.
|
| 296 |
+
session: Session name to process.
|
| 297 |
+
config: Dataset configuration.
|
| 298 |
+
|
| 299 |
+
Returns:
|
| 300 |
+
List of curve data dictionaries.
|
| 301 |
+
"""
|
| 302 |
+
gp_name = os.path.basename(gp_path)
|
| 303 |
+
session_path = os.path.join(gp_path, session)
|
| 304 |
+
|
| 305 |
+
if not os.path.exists(session_path):
|
| 306 |
+
return []
|
| 307 |
+
|
| 308 |
+
corners_file = find_corners_file(session_path)
|
| 309 |
+
if not corners_file:
|
| 310 |
+
logger.warning(f"No corners file found for {gp_name}/{session}, skipping.")
|
| 311 |
+
return []
|
| 312 |
+
|
| 313 |
+
logger.info(f"Processing {gp_name} - {session}...")
|
| 314 |
+
|
| 315 |
+
session_curves_data = []
|
| 316 |
+
|
| 317 |
+
# Determine which drivers to process
|
| 318 |
+
available_drivers = [
|
| 319 |
+
d for d in os.listdir(session_path)
|
| 320 |
+
if os.path.isdir(os.path.join(session_path, d))
|
| 321 |
+
]
|
| 322 |
+
|
| 323 |
+
if config.drivers is not None:
|
| 324 |
+
drivers_to_process = [d for d in config.drivers if d in available_drivers]
|
| 325 |
+
else:
|
| 326 |
+
drivers_to_process = available_drivers
|
| 327 |
+
|
| 328 |
+
for driver in drivers_to_process:
|
| 329 |
+
driver_path = os.path.join(session_path, driver)
|
| 330 |
+
|
| 331 |
+
driver_data = process_driver(
|
| 332 |
+
driver_path, corners_file, gp_name, session, driver, config
|
| 333 |
+
)
|
| 334 |
+
session_curves_data.extend(driver_data)
|
| 335 |
+
|
| 336 |
+
return session_curves_data
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def process_grand_prix(gp_path: str, config: DatasetConfig) -> List[Dict[str, Any]]:
|
| 340 |
+
"""
|
| 341 |
+
Processes all configured sessions for a Grand Prix.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
gp_path: Path to Grand Prix directory.
|
| 345 |
+
config: Dataset configuration.
|
| 346 |
+
|
| 347 |
+
Returns:
|
| 348 |
+
List of curve data dictionaries.
|
| 349 |
+
"""
|
| 350 |
+
gp_curves_data = []
|
| 351 |
+
|
| 352 |
+
for session in config.sessions:
|
| 353 |
+
session_data = process_session(gp_path, session, config)
|
| 354 |
+
gp_curves_data.extend(session_data)
|
| 355 |
+
|
| 356 |
+
return gp_curves_data
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# ============================================================================
|
| 360 |
+
# MAIN BUILDER
|
| 361 |
+
# ============================================================================
|
| 362 |
+
def build_dataset(config: Optional[DatasetConfig] = None) -> int:
|
| 363 |
+
"""
|
| 364 |
+
Builds the complete dataset based on configuration.
|
| 365 |
+
|
| 366 |
+
Args:
|
| 367 |
+
config: Dataset configuration. Uses defaults if None.
|
| 368 |
+
|
| 369 |
+
Returns:
|
| 370 |
+
Total number of curves extracted.
|
| 371 |
+
"""
|
| 372 |
+
if config is None:
|
| 373 |
+
config = DatasetConfig()
|
| 374 |
+
|
| 375 |
+
# Ensure output directory exists
|
| 376 |
+
output_dir = os.path.dirname(config.output_file)
|
| 377 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 378 |
+
|
| 379 |
+
# Remove existing output file
|
| 380 |
+
if os.path.exists(config.output_file):
|
| 381 |
+
os.remove(config.output_file)
|
| 382 |
+
print(f"Removed existing output file: {config.output_file}")
|
| 383 |
+
|
| 384 |
+
total_curves = 0
|
| 385 |
+
header_written = False
|
| 386 |
+
|
| 387 |
+
# Get data directories
|
| 388 |
+
data_dirs = get_data_directories(config.years)
|
| 389 |
+
|
| 390 |
+
for data_dir in data_dirs:
|
| 391 |
+
if not os.path.exists(data_dir):
|
| 392 |
+
print(f"Data directory not found, skipping: {data_dir}")
|
| 393 |
+
continue
|
| 394 |
+
|
| 395 |
+
print(f"\n--- Processing data directory: {data_dir} ---")
|
| 396 |
+
|
| 397 |
+
# Find Grand Prix directories
|
| 398 |
+
gp_dirs = sorted([
|
| 399 |
+
item for item in os.listdir(data_dir)
|
| 400 |
+
if os.path.isdir(os.path.join(data_dir, item)) and "Grand Prix" in item
|
| 401 |
+
])
|
| 402 |
+
|
| 403 |
+
for gp_name in gp_dirs:
|
| 404 |
+
gp_path = os.path.join(data_dir, gp_name)
|
| 405 |
+
|
| 406 |
+
# Process Grand Prix
|
| 407 |
+
gp_data = process_grand_prix(gp_path, config)
|
| 408 |
+
|
| 409 |
+
if not gp_data:
|
| 410 |
+
continue
|
| 411 |
+
|
| 412 |
+
# Convert to DataFrame and save incrementally
|
| 413 |
+
print(f"Creating DataFrame...")
|
| 414 |
+
df = pd.DataFrame(gp_data)
|
| 415 |
+
|
| 416 |
+
try:
|
| 417 |
+
print(f"Saving to CSV...")
|
| 418 |
+
df.to_csv(
|
| 419 |
+
config.output_file,
|
| 420 |
+
mode='a',
|
| 421 |
+
index=False,
|
| 422 |
+
chunksize=10000,
|
| 423 |
+
header=not header_written
|
| 424 |
+
)
|
| 425 |
+
header_written = True
|
| 426 |
+
|
| 427 |
+
count = len(df)
|
| 428 |
+
total_curves += count
|
| 429 |
+
print(f"Saved {count} curves from {gp_name}. Total so far: {total_curves}")
|
| 430 |
+
|
| 431 |
+
# Free memory
|
| 432 |
+
del df
|
| 433 |
+
del gp_data
|
| 434 |
+
gc.collect()
|
| 435 |
+
|
| 436 |
+
except Exception as e:
|
| 437 |
+
print(f"Error saving CSV for {gp_name}: {e}")
|
| 438 |
+
|
| 439 |
+
if total_curves == 0:
|
| 440 |
+
print("No curves extracted.")
|
| 441 |
+
else:
|
| 442 |
+
print(f"Finished processing. Total curves extracted: {total_curves}. Saved to {config.output_file}")
|
| 443 |
+
|
| 444 |
+
return total_curves
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# ============================================================================
|
| 448 |
+
# CLI ENTRY POINT
|
| 449 |
+
# ============================================================================
|
| 450 |
+
def main():
|
| 451 |
+
"""
|
| 452 |
+
Main entry point with example configuration.
|
| 453 |
+
Modify the config below to customize data extraction.
|
| 454 |
+
"""
|
| 455 |
+
# === CONFIGURATION ===
|
| 456 |
+
# Customize these settings as needed:
|
| 457 |
+
|
| 458 |
+
config = DatasetConfig(
|
| 459 |
+
years=[2024, 2025], # Years to include (None for all available)
|
| 460 |
+
drivers=None, # Driver codes to include (None for all)
|
| 461 |
+
sessions=["Qualifying", "Race"], # Sessions to process
|
| 462 |
+
output_file=DEFAULT_OUTPUT_FILE, # Output CSV path
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# === RUN ===
|
| 466 |
+
build_dataset(config)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
if __name__ == "__main__":
|
| 470 |
+
main()
|
analysis/dataset_normalization.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Tuple, Optional, List, Dict
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# =============================================================================
|
| 9 |
+
# CONFIGURATION
|
| 10 |
+
# =============================================================================
|
| 11 |
+
@dataclass
|
| 12 |
+
class NormalizationConfig:
|
| 13 |
+
"""Configuration for normalization operations."""
|
| 14 |
+
|
| 15 |
+
# ----- Constants -----
|
| 16 |
+
padding_value: float = -1000.0
|
| 17 |
+
max_samples_per_curve: int = 50
|
| 18 |
+
compound_categories: tuple = ('HARD', 'INTERMEDIATE', 'WET', 'MEDIUM', 'SOFT')
|
| 19 |
+
|
| 20 |
+
# ----- Dataset Paths (for script mode) -----
|
| 21 |
+
input_csv_path: str = "data/dataset/dataset_curves.csv"
|
| 22 |
+
output_dir: str = "data/dataset"
|
| 23 |
+
output_filename: str = "normalized_dataset.npz"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Default config instance
|
| 27 |
+
DEFAULT_CONFIG = NormalizationConfig()
|
| 28 |
+
|
| 29 |
+
# Export constants for backward compatibility
|
| 30 |
+
PADDING_VALUE = DEFAULT_CONFIG.padding_value
|
| 31 |
+
COMPOUND_CATEGORIES = list(DEFAULT_CONFIG.compound_categories)
|
| 32 |
+
MAX_SAMPLES_PER_CURVE = DEFAULT_CONFIG.max_samples_per_curve
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# =============================================================================
|
| 36 |
+
# SINGLE CURVE NORMALIZATION (for inference)
|
| 37 |
+
# =============================================================================
|
| 38 |
+
def pad_or_truncate(
|
| 39 |
+
arr,
|
| 40 |
+
target_length: int,
|
| 41 |
+
padding_value: float = PADDING_VALUE
|
| 42 |
+
) -> list:
|
| 43 |
+
"""
|
| 44 |
+
Pad or truncate an array to a target length.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
arr: Input array or list
|
| 48 |
+
target_length: Desired length
|
| 49 |
+
padding_value: Value to use for padding
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
List with exactly target_length elements
|
| 53 |
+
"""
|
| 54 |
+
if hasattr(arr, 'tolist'):
|
| 55 |
+
arr = arr.tolist()
|
| 56 |
+
elif not isinstance(arr, list):
|
| 57 |
+
arr = list(arr)
|
| 58 |
+
|
| 59 |
+
if len(arr) >= target_length:
|
| 60 |
+
return arr[:target_length]
|
| 61 |
+
return arr + [padding_value] * (target_length - len(arr))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def curve_to_raw_features(
|
| 65 |
+
curve,
|
| 66 |
+
config: NormalizationConfig = None
|
| 67 |
+
) -> np.ndarray:
|
| 68 |
+
"""
|
| 69 |
+
Convert a Curve object to a raw (non-normalized) feature vector.
|
| 70 |
+
|
| 71 |
+
Layout:
|
| 72 |
+
0: life
|
| 73 |
+
1:51 speed (50 columns)
|
| 74 |
+
51:101 rpm (50 columns)
|
| 75 |
+
101:151 throttle (50 columns)
|
| 76 |
+
151:201 brake (50 columns)
|
| 77 |
+
201:251 acc_x (50 columns)
|
| 78 |
+
251:301 acc_y (50 columns)
|
| 79 |
+
301:351 acc_z (50 columns)
|
| 80 |
+
351-355: Compound one-hot (HARD, INTERMEDIATE, WET, MEDIUM, SOFT)
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
curve: Curve object from CurveDetector
|
| 84 |
+
config: Normalization configuration
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
Raw feature vector as numpy array
|
| 88 |
+
"""
|
| 89 |
+
if config is None:
|
| 90 |
+
config = DEFAULT_CONFIG
|
| 91 |
+
|
| 92 |
+
max_samples = config.max_samples_per_curve
|
| 93 |
+
padding = config.padding_value
|
| 94 |
+
categories = config.compound_categories
|
| 95 |
+
|
| 96 |
+
# Prepare raw features with padding
|
| 97 |
+
life = curve.life if hasattr(curve, 'life') else 0
|
| 98 |
+
speed = pad_or_truncate(curve.speed, max_samples, padding)
|
| 99 |
+
rpm = pad_or_truncate(curve.rpm, max_samples, padding)
|
| 100 |
+
throttle = pad_or_truncate(curve.throttle, max_samples, padding)
|
| 101 |
+
brake = pad_or_truncate(curve.brake, max_samples, padding)
|
| 102 |
+
acc_x = pad_or_truncate(curve.acc_x, max_samples, padding)
|
| 103 |
+
acc_y = pad_or_truncate(curve.acc_y, max_samples, padding)
|
| 104 |
+
acc_z = pad_or_truncate(curve.acc_z, max_samples, padding)
|
| 105 |
+
|
| 106 |
+
# Compound one-hot encoding
|
| 107 |
+
compound_one_hot = [
|
| 108 |
+
1.0 if curve.compound == cat else 0.0
|
| 109 |
+
for cat in categories
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
# Build raw feature vector
|
| 113 |
+
raw_features = (
|
| 114 |
+
[life] + speed + rpm + throttle + brake +
|
| 115 |
+
acc_x + acc_y + acc_z + compound_one_hot
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
return np.array(raw_features, dtype=np.float64)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def normalize_sample(
|
| 122 |
+
raw_features: np.ndarray,
|
| 123 |
+
mean: np.ndarray,
|
| 124 |
+
std: np.ndarray,
|
| 125 |
+
padding_value: float = PADDING_VALUE
|
| 126 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 127 |
+
"""
|
| 128 |
+
Normalize a single sample (feature vector) using pre-computed mean and std.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
raw_features: Raw feature vector as numpy array
|
| 132 |
+
mean: Mean values for normalization
|
| 133 |
+
std: Std values for normalization
|
| 134 |
+
padding_value: Value used for padding
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
Tuple of (normalized_features, mask)
|
| 138 |
+
"""
|
| 139 |
+
# Build mask (1 = valid, 0 = padding)
|
| 140 |
+
mask = np.array([
|
| 141 |
+
0.0 if val == padding_value else 1.0
|
| 142 |
+
for val in raw_features
|
| 143 |
+
], dtype=np.float64)
|
| 144 |
+
|
| 145 |
+
# Z-score normalization
|
| 146 |
+
normalized = np.zeros_like(raw_features, dtype=np.float64)
|
| 147 |
+
for i in range(len(raw_features)):
|
| 148 |
+
if raw_features[i] != padding_value and std[i] != 0:
|
| 149 |
+
normalized[i] = (raw_features[i] - mean[i]) / std[i]
|
| 150 |
+
elif raw_features[i] == padding_value:
|
| 151 |
+
normalized[i] = 0.0 # Padding becomes 0
|
| 152 |
+
|
| 153 |
+
return normalized, mask
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def normalize_curve(
|
| 157 |
+
curve,
|
| 158 |
+
mean: np.ndarray,
|
| 159 |
+
std: np.ndarray,
|
| 160 |
+
config: NormalizationConfig = None
|
| 161 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 162 |
+
"""
|
| 163 |
+
Convert a Curve object to a normalized feature vector.
|
| 164 |
+
|
| 165 |
+
This is the main function to use for normalizing a single curve
|
| 166 |
+
during inference (e.g., in evaluate.py).
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
curve: Curve object from CurveDetector
|
| 170 |
+
mean: Mean values for normalization (from dataset)
|
| 171 |
+
std: Std values for normalization (from dataset)
|
| 172 |
+
config: Normalization configuration
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
Tuple of (normalized_features, mask) as numpy arrays
|
| 176 |
+
"""
|
| 177 |
+
if config is None:
|
| 178 |
+
config = DEFAULT_CONFIG
|
| 179 |
+
|
| 180 |
+
# Get raw features
|
| 181 |
+
raw_features = curve_to_raw_features(curve, config)
|
| 182 |
+
|
| 183 |
+
# Normalize using normalize_sample
|
| 184 |
+
normalized, mask = normalize_sample(
|
| 185 |
+
raw_features, mean, std, config.padding_value
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
return normalized, mask
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def normalize_telemetry_json(
|
| 192 |
+
telemetry_path: str,
|
| 193 |
+
corners_path: str,
|
| 194 |
+
dataset_path: str,
|
| 195 |
+
config: NormalizationConfig = None
|
| 196 |
+
) -> list:
|
| 197 |
+
"""
|
| 198 |
+
Load telemetry JSON, detect curves, and normalize them.
|
| 199 |
+
|
| 200 |
+
This is the HIGH-LEVEL function that does everything in one call:
|
| 201 |
+
1. Loads normalization stats from dataset
|
| 202 |
+
2. Detects curves from telemetry JSON
|
| 203 |
+
3. Normalizes each curve
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
telemetry_path: Path to telemetry JSON file (e.g., "4_tel.json")
|
| 207 |
+
corners_path: Path to corners JSON file (e.g., "corners.json")
|
| 208 |
+
dataset_path: Path to normalized dataset .npz file (for mean/std)
|
| 209 |
+
config: Normalization configuration
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
List of dicts containing:
|
| 213 |
+
- 'curve': Original Curve object
|
| 214 |
+
- 'normalized': Normalized feature vector (np.ndarray)
|
| 215 |
+
- 'mask': Padding mask (np.ndarray)
|
| 216 |
+
|
| 217 |
+
"""
|
| 218 |
+
from src.analysis.CurveDetector import CurveDetector
|
| 219 |
+
|
| 220 |
+
if config is None:
|
| 221 |
+
config = DEFAULT_CONFIG
|
| 222 |
+
|
| 223 |
+
# Load normalization stats
|
| 224 |
+
data, mask, mean, std, columns = load_normalized_data(dataset_path)
|
| 225 |
+
|
| 226 |
+
# Detect curves
|
| 227 |
+
detector = CurveDetector(telemetry_path, corners_path)
|
| 228 |
+
curves = detector.calcolo_curve()
|
| 229 |
+
|
| 230 |
+
# Normalize each curve
|
| 231 |
+
results = []
|
| 232 |
+
for curve in curves:
|
| 233 |
+
normalized, curve_mask = normalize_curve(curve, mean, std, config)
|
| 234 |
+
results.append({
|
| 235 |
+
'curve': curve,
|
| 236 |
+
'normalized': normalized,
|
| 237 |
+
'mask': curve_mask
|
| 238 |
+
})
|
| 239 |
+
|
| 240 |
+
return results
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# =============================================================================
|
| 244 |
+
# DATASET NORMALIZATION (for training data preparation)
|
| 245 |
+
# =============================================================================
|
| 246 |
+
def one_hot_encode_compound(
|
| 247 |
+
df: pd.DataFrame,
|
| 248 |
+
categories: List[str] = None
|
| 249 |
+
) -> pd.DataFrame:
|
| 250 |
+
"""
|
| 251 |
+
Perform one-hot encoding on the 'Compound' column.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
df: Input DataFrame
|
| 255 |
+
categories: List of compound categories to encode
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
DataFrame with 'Compound' column replaced by one-hot encoded columns
|
| 259 |
+
"""
|
| 260 |
+
if categories is None:
|
| 261 |
+
categories = COMPOUND_CATEGORIES
|
| 262 |
+
|
| 263 |
+
if 'Compound' not in df.columns:
|
| 264 |
+
return df
|
| 265 |
+
|
| 266 |
+
df = df.copy()
|
| 267 |
+
compound_dummies = pd.get_dummies(df['Compound'], prefix='Compound', dtype=float)
|
| 268 |
+
|
| 269 |
+
# Add missing columns and enforce order
|
| 270 |
+
for cat in categories:
|
| 271 |
+
col = f"Compound_{cat}"
|
| 272 |
+
if col not in compound_dummies.columns:
|
| 273 |
+
compound_dummies[col] = 0.0
|
| 274 |
+
|
| 275 |
+
compound_dummies = compound_dummies[[f"Compound_{cat}" for cat in categories]]
|
| 276 |
+
|
| 277 |
+
df = pd.concat([df, compound_dummies], axis=1)
|
| 278 |
+
df = df.drop('Compound', axis=1)
|
| 279 |
+
|
| 280 |
+
return df
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def create_padding_mask(
|
| 284 |
+
df: pd.DataFrame,
|
| 285 |
+
padding_value: float = PADDING_VALUE
|
| 286 |
+
) -> pd.DataFrame:
|
| 287 |
+
"""
|
| 288 |
+
Create a mask where 1 = valid data, 0 = padding.
|
| 289 |
+
"""
|
| 290 |
+
return (df != padding_value).astype(float)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def compute_grouped_stats(
|
| 294 |
+
df: pd.DataFrame,
|
| 295 |
+
skip_prefixes: List[str] = None
|
| 296 |
+
) -> Tuple[pd.Series, pd.Series]:
|
| 297 |
+
"""
|
| 298 |
+
Compute mean and std for each column, grouping columns with same prefix.
|
| 299 |
+
|
| 300 |
+
Columns ending with _<number> are grouped together and share the same
|
| 301 |
+
mean/std computed from all values in the group.
|
| 302 |
+
"""
|
| 303 |
+
skip_prefixes = skip_prefixes or ["Compound"]
|
| 304 |
+
|
| 305 |
+
mean_dict: Dict[str, float] = {}
|
| 306 |
+
std_dict: Dict[str, float] = {}
|
| 307 |
+
|
| 308 |
+
grouped_cols: Dict[str, List[str]] = {}
|
| 309 |
+
single_cols: List[str] = []
|
| 310 |
+
|
| 311 |
+
# Identify column groups (columns ending with _<number>)
|
| 312 |
+
for col in df.columns:
|
| 313 |
+
match = re.match(r"^(.*)_\d+$", col)
|
| 314 |
+
if match:
|
| 315 |
+
prefix = match.group(1)
|
| 316 |
+
if prefix not in grouped_cols:
|
| 317 |
+
grouped_cols[prefix] = []
|
| 318 |
+
grouped_cols[prefix].append(col)
|
| 319 |
+
else:
|
| 320 |
+
single_cols.append(col)
|
| 321 |
+
|
| 322 |
+
# Process groups - compute global mean/std across all columns in group
|
| 323 |
+
for prefix, cols in grouped_cols.items():
|
| 324 |
+
group_data = df[cols].values.flatten()
|
| 325 |
+
g_mean = np.nanmean(group_data)
|
| 326 |
+
g_std = np.nanstd(group_data)
|
| 327 |
+
|
| 328 |
+
if g_std == 0 or np.isnan(g_std):
|
| 329 |
+
g_std = 1.0
|
| 330 |
+
|
| 331 |
+
for col in cols:
|
| 332 |
+
mean_dict[col] = g_mean
|
| 333 |
+
std_dict[col] = g_std
|
| 334 |
+
|
| 335 |
+
# Process single columns
|
| 336 |
+
for col in single_cols:
|
| 337 |
+
# Skip normalization for specified prefixes
|
| 338 |
+
if any(skip in col for skip in skip_prefixes):
|
| 339 |
+
mean_dict[col] = 0.0
|
| 340 |
+
std_dict[col] = 1.0
|
| 341 |
+
continue
|
| 342 |
+
|
| 343 |
+
val_mean = df[col].mean()
|
| 344 |
+
val_std = df[col].std()
|
| 345 |
+
|
| 346 |
+
if pd.isna(val_std) or val_std == 0:
|
| 347 |
+
val_std = 1.0
|
| 348 |
+
if pd.isna(val_mean):
|
| 349 |
+
val_mean = 0.0
|
| 350 |
+
|
| 351 |
+
mean_dict[col] = val_mean
|
| 352 |
+
std_dict[col] = val_std
|
| 353 |
+
|
| 354 |
+
mean = pd.Series(mean_dict)[df.columns]
|
| 355 |
+
std = pd.Series(std_dict)[df.columns]
|
| 356 |
+
|
| 357 |
+
return mean, std
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def normalize_dataframe(
|
| 361 |
+
df: pd.DataFrame,
|
| 362 |
+
config: NormalizationConfig = None,
|
| 363 |
+
apply_one_hot: bool = True,
|
| 364 |
+
skip_prefixes: List[str] = None,
|
| 365 |
+
return_stats: bool = True
|
| 366 |
+
) -> Tuple[pd.DataFrame, pd.DataFrame, Optional[pd.Series], Optional[pd.Series]]:
|
| 367 |
+
"""
|
| 368 |
+
Normalize a DataFrame using z-score normalization.
|
| 369 |
+
|
| 370 |
+
This is the main function to use for normalizing an entire dataset
|
| 371 |
+
(e.g., for training data preparation).
|
| 372 |
+
|
| 373 |
+
Performs:
|
| 374 |
+
1. One-hot encoding of 'Compound' column (if present and apply_one_hot=True)
|
| 375 |
+
2. Creation of padding mask
|
| 376 |
+
3. Grouped z-score normalization
|
| 377 |
+
|
| 378 |
+
Args:
|
| 379 |
+
df: Input DataFrame to normalize
|
| 380 |
+
config: Normalization configuration
|
| 381 |
+
apply_one_hot: Whether to apply one-hot encoding to 'Compound' column
|
| 382 |
+
skip_prefixes: Column prefixes to skip during normalization
|
| 383 |
+
return_stats: Whether to return mean and std
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
Tuple of:
|
| 387 |
+
- Normalized DataFrame (padding replaced with 0.0)
|
| 388 |
+
- Mask DataFrame (1=valid, 0=padding)
|
| 389 |
+
- Mean Series (if return_stats=True, else None)
|
| 390 |
+
- Std Series (if return_stats=True, else None)
|
| 391 |
+
"""
|
| 392 |
+
if config is None:
|
| 393 |
+
config = DEFAULT_CONFIG
|
| 394 |
+
|
| 395 |
+
df = df.copy()
|
| 396 |
+
categories = list(config.compound_categories)
|
| 397 |
+
padding_value = config.padding_value
|
| 398 |
+
|
| 399 |
+
# Apply one-hot encoding if needed
|
| 400 |
+
if apply_one_hot:
|
| 401 |
+
df = one_hot_encode_compound(df, categories)
|
| 402 |
+
|
| 403 |
+
# Create mask before replacing padding
|
| 404 |
+
mask = create_padding_mask(df, padding_value)
|
| 405 |
+
|
| 406 |
+
# Replace padding with NaN for stats calculation
|
| 407 |
+
df_for_stats = df.replace(padding_value, np.nan)
|
| 408 |
+
|
| 409 |
+
# Compute grouped statistics
|
| 410 |
+
mean, std = compute_grouped_stats(df_for_stats, skip_prefixes)
|
| 411 |
+
|
| 412 |
+
# Apply z-score normalization
|
| 413 |
+
df_normalized = (df_for_stats - mean) / std
|
| 414 |
+
df_normalized = df_normalized.fillna(0.0)
|
| 415 |
+
|
| 416 |
+
if return_stats:
|
| 417 |
+
return df_normalized, mask, mean, std
|
| 418 |
+
else:
|
| 419 |
+
return df_normalized, mask, None, None
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def denormalize_dataframe(
|
| 423 |
+
df: pd.DataFrame,
|
| 424 |
+
mean: pd.Series,
|
| 425 |
+
std: pd.Series,
|
| 426 |
+
mask: Optional[pd.DataFrame] = None,
|
| 427 |
+
padding_value: float = PADDING_VALUE
|
| 428 |
+
) -> pd.DataFrame:
|
| 429 |
+
"""
|
| 430 |
+
Denormalize a DataFrame using stored mean and std.
|
| 431 |
+
"""
|
| 432 |
+
df_denorm = (df * std) + mean
|
| 433 |
+
|
| 434 |
+
if mask is not None:
|
| 435 |
+
df_denorm = df_denorm.where(mask == 1, padding_value)
|
| 436 |
+
|
| 437 |
+
return df_denorm
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
# =============================================================================
|
| 441 |
+
# I/O FUNCTIONS
|
| 442 |
+
# =============================================================================
|
| 443 |
+
def save_normalized_data(
|
| 444 |
+
df_normalized: pd.DataFrame,
|
| 445 |
+
mask: pd.DataFrame,
|
| 446 |
+
mean: pd.Series,
|
| 447 |
+
std: pd.Series,
|
| 448 |
+
output_path: str
|
| 449 |
+
) -> None:
|
| 450 |
+
"""Save normalized data to .npz file."""
|
| 451 |
+
np.savez(
|
| 452 |
+
output_path,
|
| 453 |
+
data=df_normalized.values,
|
| 454 |
+
mask=mask.values,
|
| 455 |
+
mean=mean.values,
|
| 456 |
+
std=std.values,
|
| 457 |
+
columns=df_normalized.columns.values
|
| 458 |
+
)
|
| 459 |
+
print(f"Saved normalized data to {output_path}")
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def load_normalized_data(
|
| 463 |
+
input_path: str
|
| 464 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 465 |
+
"""
|
| 466 |
+
Load normalized data from .npz file.
|
| 467 |
+
|
| 468 |
+
Returns:
|
| 469 |
+
Tuple of (data, mask, mean, std, columns)
|
| 470 |
+
"""
|
| 471 |
+
loaded = np.load(input_path, allow_pickle=True)
|
| 472 |
+
return (
|
| 473 |
+
loaded['data'],
|
| 474 |
+
loaded['mask'],
|
| 475 |
+
loaded['mean'],
|
| 476 |
+
loaded['std'],
|
| 477 |
+
loaded['columns']
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# =============================================================================
|
| 482 |
+
# SCRIPT MODE: Run as standalone script
|
| 483 |
+
# =============================================================================
|
| 484 |
+
if __name__ == "__main__":
|
| 485 |
+
# Configuration
|
| 486 |
+
config = NormalizationConfig(
|
| 487 |
+
input_csv_path="data/dataset/dataset_curves.csv",
|
| 488 |
+
output_dir="data/dataset",
|
| 489 |
+
output_filename="normalized_dataset.npz"
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
# Load dataset
|
| 493 |
+
print(f"Loading CSV from {config.input_csv_path}...")
|
| 494 |
+
df = pd.read_csv(
|
| 495 |
+
config.input_csv_path,
|
| 496 |
+
sep=",",
|
| 497 |
+
encoding="utf-8",
|
| 498 |
+
decimal="."
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
# Remove unnecessary columns
|
| 502 |
+
df = df.drop(df.columns[:5], axis=1)
|
| 503 |
+
df = df.drop(df.columns[2], axis=1)
|
| 504 |
+
|
| 505 |
+
# Remove X, Y, Z columns
|
| 506 |
+
df = df.drop(df.columns[352:502], axis=1)
|
| 507 |
+
|
| 508 |
+
# Remove time and distance columns
|
| 509 |
+
df = df.drop(df.columns[352:], axis=1)
|
| 510 |
+
|
| 511 |
+
# Normalize
|
| 512 |
+
print("Normalizing dataset...")
|
| 513 |
+
df_normalized, mask, mean, std = normalize_dataframe(df, config)
|
| 514 |
+
|
| 515 |
+
print(f"Normalized Data Shape: {df_normalized.shape}")
|
| 516 |
+
print(f"Mask Shape: {mask.shape}")
|
| 517 |
+
|
| 518 |
+
# Save
|
| 519 |
+
output_path = f"{config.output_dir}/{config.output_filename}"
|
| 520 |
+
save_normalized_data(df_normalized, mask, mean, std, output_path)
|
analysis/utils_for_array.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def avg_in_window(arr, i, win):
|
| 5 |
+
start = max(0, i - win)
|
| 6 |
+
end = min(len(arr), i + win + 1)
|
| 7 |
+
vals = [abs(a) for a in arr[start:end]]
|
| 8 |
+
return sum(vals) / len(vals)
|
| 9 |
+
|
| 10 |
+
def find_frist_value(array, value):
|
| 11 |
+
#primo indice dove array[i] >= value
|
| 12 |
+
for i, d in enumerate(array):
|
| 13 |
+
if d >= value:
|
| 14 |
+
return i
|
| 15 |
+
return len(array) - 1
|
| 16 |
+
|
| 17 |
+
#Ritorna una indice
|
| 18 |
+
def find_closest_value(array, value):
|
| 19 |
+
array = np.asarray(array)
|
| 20 |
+
return np.abs(array - value).argmin()
|
| 21 |
+
|
| 22 |
+
def find_last_value(array, value):
|
| 23 |
+
#ultimo indice dove array[i] <= value
|
| 24 |
+
last = 0
|
| 25 |
+
for i, d in enumerate(array):
|
| 26 |
+
if d <= value:
|
| 27 |
+
last = i
|
| 28 |
+
else:
|
| 29 |
+
break
|
| 30 |
+
return last
|