-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraceAnalysis.py
More file actions
6929 lines (6035 loc) · 375 KB
/
Copy pathraceAnalysis.py
File metadata and controls
6929 lines (6035 loc) · 375 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
import datetime
import json
from os import path
import os
import sys
import subprocess
# Keep the hosted Streamlit process from allowing native numerical libraries to
# claim every available CPU thread. Offline training workflows set their own
# parallelism and are not affected by these web-runtime defaults.
for _thread_env in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'):
os.environ.setdefault(_thread_env, '1')
import streamlit as st
import numpy as np
from pathlib import Path
import warnings
from model_artifacts import artifact_matches_fingerprint, build_data_fingerprint
# Pickled custom estimators refer to this module as ``raceAnalysis``. Streamlit
# executes the entrypoint as ``__main__``; aliasing it prevents pickle from
# importing and executing the complete app a second time during model loading.
if __name__ == "__main__":
sys.modules.setdefault("raceAnalysis", sys.modules[__name__])
# suppress pandas FutureWarning about silent downcasting on fillna; prefer
# explicit infer_objects where possible, otherwise silence the noisy warning
warnings.filterwarnings(
"ignore",
message=r"Downcasting object dtype arrays on \.fillna, \.ffill, \.bfill is deprecated",
category=FutureWarning,
)
from pandas.api.types import (
is_categorical_dtype,
is_datetime64_any_dtype,
is_numeric_dtype,
is_object_dtype,
is_bool_dtype
)
import altair as alt
import time
import numpy as np
#import scipy
from scipy.stats import linregress
from scipy.stats import truncnorm
import plotly.graph_objects as go
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from sklearn.impute import SimpleImputer
from sklearn.experimental import enable_iterative_imputer # noqa: F401 – must import before IterativeImputer
from sklearn.impute import IterativeImputer
from sklearn.preprocessing import RobustScaler, TargetEncoder
from sklearn.ensemble import VotingRegressor, StackingRegressor
from sklearn.base import BaseEstimator, RegressorMixin
from xgboost import XGBRegressor
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import roc_auc_score
import xgboost as xgb
try:
from lightgbm import LGBMRegressor
_LGBM_AVAILABLE = True
except (ImportError, OSError):
# libgomp.so.1 (OpenMP) missing on this platform – LightGBM disabled.
LGBMRegressor = None # type: ignore[assignment,misc]
_LGBM_AVAILABLE = False
from catboost import CatBoostRegressor
# Import the temporal leakage audit helper. The helper lives in `scripts/`.
# Try multiple import strategies to be robust when Streamlit changes sys.path.
import logging
# Debugging toggle: set environment variable F1_DEBUG=1 to enable detailed
# runtime diagnostics (prints shapes, feature lists, and model-reported feature counts).
DEBUG = os.environ.get('F1_DEBUG', '0') == '1'
RESEARCH_MODE = os.environ.get('F1_RESEARCH_MODE', '0').strip().lower() in {'1', 'true', 'yes'}
MEMORY_LOGGING = os.environ.get('F1_MEMORY_LOG', '0').strip().lower() in {'1', 'true', 'yes'}
logger = logging.getLogger('f1analysis')
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
def log_memory(label: str) -> None:
"""Log process RSS when explicitly enabled for deployment diagnostics."""
if not MEMORY_LOGGING:
return
try:
import psutil
rss_mb = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024
print(f"[MEMORY] {label}: {rss_mb:.1f} MB RSS", flush=True)
except Exception as exc:
logger.debug("Unable to collect RSS for %s: %s", label, exc)
# ── ROADMAP-3 constants ──────────────────────────────────────────────────────
# High-cardinality categorical columns that benefit from target encoding rather
# than one-hot encoding (3C). Only columns *present* in the feature set are
# target-encoded; absent columns fall back to OHE silently.
_HIGH_CARD_COLS = {
'constructorId', 'circuitId', 'resultsDriverName', 'resultsDriverId',
'constructorName', 'grandPrixName', 'grandPrixId',
}
# Circuit archetypes used by the track-type ensemble weighting (3E).
CIRCUIT_TYPES: dict[str, str] = {
# Street circuits
'monaco': 'street', 'baku': 'street', 'jeddah': 'street',
'albert_park': 'street', 'las_vegas': 'street', 'miami': 'street',
# High-speed circuits
'spa': 'high_speed', 'monza': 'high_speed', 'silverstone': 'high_speed',
'bahrain': 'high_speed', 'interlagos': 'high_speed', 'yas_marina': 'high_speed',
# Technical circuits
'suzuka': 'technical', 'red_bull_ring': 'technical', 'hungaroring': 'technical',
'zandvoort': 'technical', 'imola': 'technical', 'barcelona': 'technical',
# Mixed / default
'americas': 'mixed', 'mexico_city': 'mixed', 'shanghai': 'mixed',
'singapore': 'street', # longest street circuit — fits street weighting
'sochi': 'mixed',
}
# Per-circuit-type blend weights {model_label: weight} — sum of weights must ~= 1.
# Defaults are used when no calibrated JSON exists. Run
# python scripts/calibrate_circuit_weights.py
# to produce data_files/circuit_ensemble_weights.json which is loaded below.
_CIRCUIT_ENSEMBLE_WEIGHTS_DEFAULT: dict[str, dict] = {
'street': {'xgb': 0.30, 'lgbm': 0.25, 'cat': 0.45}, # CatBoost better on street
'high_speed': {'xgb': 0.45, 'lgbm': 0.35, 'cat': 0.20}, # XGBoost better on fast tracks
'technical': {'xgb': 0.35, 'lgbm': 0.40, 'cat': 0.25}, # LightGBM better on complex
'mixed': {'xgb': 0.33, 'lgbm': 0.33, 'cat': 0.34}, # Equal weight default
}
def _load_circuit_ensemble_weights() -> dict[str, dict]:
"""Load calibrated per-circuit-type blend weights from data_files/circuit_ensemble_weights.json.
Falls back to the hardcoded defaults if the JSON does not exist or is
malformed. The JSON is produced by ``scripts/calibrate_circuit_weights.py``.
"""
_json_path = os.path.join('data_files', 'circuit_ensemble_weights.json')
try:
with open(_json_path, 'r') as _fh:
_raw = json.load(_fh)
# Strip metadata key; keep only circuit-type entries
weights = {k: v for k, v in _raw.items()
if not k.startswith('_') and isinstance(v, dict)}
# Validate: each entry must have xgb/lgbm/cat keys
_required = {'xgb', 'lgbm', 'cat'}
weights = {k: v for k, v in weights.items()
if _required.issubset(v.keys())}
# Ensure canonical types are present; fill missing from default
for _ct, _dw in _CIRCUIT_ENSEMBLE_WEIGHTS_DEFAULT.items():
if _ct not in weights:
weights[_ct] = _dw
_src = os.path.basename(_json_path)
meta = _raw.get('_meta', {})
_delta = meta.get('delta_mae', None)
_note = f" d_MAE vs default = {_delta:+.4f}" if _delta is not None else ""
print(f"INFO: Loaded circuit ensemble weights from {_src} "
f"(types: {sorted(weights)}).{_note}")
return weights
except FileNotFoundError:
print("INFO: No circuit_ensemble_weights.json found — using hardcoded defaults. "
"Run scripts/calibrate_circuit_weights.py to calibrate.")
return dict(_CIRCUIT_ENSEMBLE_WEIGHTS_DEFAULT)
except Exception as _exc:
print(f"WARN: Failed to load circuit_ensemble_weights.json ({_exc}). "
"Falling back to hardcoded defaults.")
return dict(_CIRCUIT_ENSEMBLE_WEIGHTS_DEFAULT)
CIRCUIT_ENSEMBLE_WEIGHTS: dict[str, dict] = _load_circuit_ensemble_weights()
def get_circuit_type(circuit_ref: str | None) -> str:
"""Return the circuit archetype for *circuit_ref*, defaulting to 'mixed'."""
if not circuit_ref:
return 'mixed'
return CIRCUIT_TYPES.get(str(circuit_ref).lower().replace(' ', '_').replace('-', '_'), 'mixed')
# ── ROADMAP-3A wrapper classes ────────────────────────────────────────────────
class PositionGroupEnsemble(BaseEstimator, RegressorMixin):
"""Blend of sub-models trained on position segments (1–3, 4–10, 11+).
Uses a lightweight *router* XGBRegressor (trained on all data) to produce
an initial position estimate, then applies soft weighting: each sub-model
is weighted by the inverse of its sub-model's distance from the router
prediction. This avoids the catastrophic equal-weight averaging that pulls
all predictions toward the middle of the position range (~8th).
Exposes the standard sklearn ``predict(X)`` interface.
"""
def __init__(self, podium_model=None, points_model=None, outside_model=None,
router_model=None):
self.podium_model = podium_model
self.points_model = points_model
self.outside_model = outside_model
self.router_model = router_model
# canonical centre of each sub-model’s training range
_CENTRES = (2.0, 7.0, 15.0)
def predict(self, X):
"""Soft-route predictions to the most applicable sub-model."""
p1 = self.podium_model.predict(X)
p2 = self.points_model.predict(X)
p3 = self.outside_model.predict(X)
if self.router_model is not None:
# router gives a coarse estimate of the driver’s expected position
routing = self.router_model.predict(X)
else:
# fallback: use equal average of all three predictions as proxy
routing = (p1 + p2 + p3) / 3.0
# Soft weights: higher weight for sub-models whose canonical centre is
# closest to the router’s estimate.
c1, c2, c3 = self._CENTRES
w1 = 1.0 / (np.abs(routing - c1) + 1.0)
w2 = 1.0 / (np.abs(routing - c2) + 1.0)
w3 = 1.0 / (np.abs(routing - c3) + 1.0)
total = w1 + w2 + w3
return (w1 * p1 + w2 * p2 + w3 * p3) / total
# feature_importances_ proxy — average across sub-models where available
@property
def feature_importances_(self):
arrs = []
for m in (self.podium_model, self.points_model, self.outside_model):
if hasattr(m, 'feature_importances_'):
arrs.append(m.feature_importances_)
if arrs:
import numpy as _np
return _np.mean(arrs, axis=0)
return None
class TrackWeightedEnsemble(BaseEstimator, RegressorMixin):
"""Three sub-models (XGB / LGBM / CAT) blended with track-type-specific weights.
Use `predict_for_circuit(X, circuit_type)` for shared cached instances so
predictions do not mutate cross-session state.
"""
def __init__(self, xgb_model=None, lgbm_model=None, cat_model=None,
circuit_type: str = 'mixed'):
self.xgb_model = xgb_model
self.lgbm_model = lgbm_model
self.cat_model = cat_model
self.circuit_type = circuit_type
def set_circuit_type(self, circuit_type: str):
"""Update the circuit type (and thus blend weights) before prediction."""
self.circuit_type = circuit_type
return self
def predict(self, X):
return self.predict_for_circuit(X, self.circuit_type)
def predict_for_circuit(self, X, circuit_type: str):
"""Predict with per-call weights without mutating the shared model."""
weights = CIRCUIT_ENSEMBLE_WEIGHTS.get(
circuit_type, CIRCUIT_ENSEMBLE_WEIGHTS['mixed']
)
pred_xgb = self.xgb_model.predict(X)
pred_lgbm = self.lgbm_model.predict(X)
pred_cat = self.cat_model.predict(X)
return (
weights['xgb'] * pred_xgb +
weights['lgbm'] * pred_lgbm +
weights['cat'] * pred_cat
)
@property
def feature_importances_(self):
import numpy as _np
arrs = []
for m in (self.xgb_model, self.lgbm_model, self.cat_model):
if hasattr(m, 'feature_importances_'):
arrs.append(m.feature_importances_)
return _np.mean(arrs, axis=0) if arrs else None
# Attempt to import audit_temporal_leakage with fallbacks
audit_temporal_leakage = None # type: ignore
try:
import audit_temporal_leakage # type: ignore
except ModuleNotFoundError:
try:
# Add repository scripts directory to sys.path and retry
SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), 'scripts')
if SCRIPTS_DIR not in sys.path:
sys.path.insert(0, SCRIPTS_DIR)
import audit_temporal_leakage # type: ignore
except Exception:
try:
# Try module-style import if repo root is on sys.path
import scripts.audit_temporal_leakage as audit_temporal_leakage # type: ignore
except Exception:
audit_temporal_leakage = None
if DEBUG:
logger.debug('audit_temporal_leakage module not found; continuing without audit helpers')
EarlyStopping = xgb.callback.EarlyStopping
from footer import add_betting_oracle_footer
# SklearnCompatibleCatBoost lives in model_classes.py so that pickle.load
# resolves the class by importing that lightweight module instead of
# re-importing the entire raceAnalysis app (which would trigger duplicate
# widget-key errors and CachedWidgetWarning).
from model_classes import SklearnCompatibleCatBoost # noqa: F401 – re-exported for pkl back-compat
DATA_DIR = 'data_files/'
# Cache version - increment this when preprocessor logic changes
CACHE_VERSION = "v3.3" # Bumped: Drop NaN/inf rows instead of filling (matches precompute script)
@st.cache_data(max_entries=4, show_spinner=False)
def _cached_data_fingerprint(file_path, file_size, file_mtime_ns):
"""Hash a local data file, using stat fields only to invalidate this cache."""
del file_size, file_mtime_ns
return build_data_fingerprint(file_path)
def get_data_fingerprint(file_name='f1ForAnalysis.csv'):
"""Return a stable content fingerprint without using mtime as validity."""
file_path = Path(DATA_DIR) / file_name
stat = file_path.stat()
return _cached_data_fingerprint(str(file_path), stat.st_size, stat.st_mtime_ns)
# Preprocessor used when training the main position model. Set during training so
# prediction uses the exact same feature ordering and transforms (prevents
# feature-shape mismatches between training and prediction environments).
TRAINING_PREPROCESSOR = None
def is_preprocessor_valid(preprocessor, X):
"""Return True if every column the preprocessor was fitted on is present in X.
A stale preprocessor (e.g. from a pkl trained with a feature that has since
been removed) will have columns that are missing from the current data, which
causes sklearn to raise ValueError on transform(). This helper lets callers
detect and discard stale preprocessors before attempting the transform.
"""
if preprocessor is None:
return False
try:
# sklearn >= 1.0 stores feature_names_in_ after fit
if hasattr(preprocessor, 'feature_names_in_'):
missing = set(preprocessor.feature_names_in_) - set(X.columns)
if missing:
print(f"INFO: Preprocessor is incompatible — missing columns: {missing}. Will reload artifact.")
return False
return True
# Fallback: inspect each transformer's column list
if hasattr(preprocessor, 'transformers_'):
for _, _, cols in preprocessor.transformers_:
if isinstance(cols, list):
missing = set(cols) - set(X.columns)
if missing:
print(f"INFO: Preprocessor is incompatible — missing columns: {missing}. Will reload artifact.")
return False
return True
except Exception:
return False
def debug_log(msg, obj=None):
"""Helper to emit diagnostics both to Streamlit UI and logs when DEBUG is enabled."""
if not DEBUG:
return
try:
# Streamlit-friendly display
try:
st.write(f"DEBUG: {msg}")
if obj is not None:
st.write(obj)
except Exception:
pass
# Logger
if obj is None:
logger.debug(msg)
else:
logger.debug(f"%s -- %r", msg, obj)
except Exception:
pass
# Suppress numpy warnings about empty slices during calculations
warnings.filterwarnings('ignore', message='Mean of empty slice', category=RuntimeWarning, module='numpy')
warnings.filterwarnings('ignore', message='All-NaN slice encountered', category=RuntimeWarning, module='numpy')
# Suppress noisy numpy divide/invalid value RuntimeWarnings caused by correlation/stddev ops
warnings.filterwarnings('ignore', message='invalid value encountered in divide', category=RuntimeWarning, module='numpy')
# Also set numpy to ignore invalid operations to avoid repetitive RuntimeWarnings during UI calculations
np.seterr(invalid='ignore')
def compute_safe_correlation(full_df, cols, method='pearson'):
"""Compute correlation for `cols` from `full_df`, dropping constant or all-NaN columns.
Returns a square DataFrame indexed/columned by `cols`. Columns that were constant
or all-NaN will be present but filled with NaN so downstream code that expects
a fixed shape can still rename rows/columns safely.
"""
# Defensive: ensure cols exist and deduplicate while preserving order
cols = [c for c in cols if c in full_df.columns]
if not cols:
return pd.DataFrame()
seen = set()
cols_unique = []
for c in cols:
if c not in seen:
cols_unique.append(c)
seen.add(c)
# use the deduplicated ordered list for downstream operations
cols = cols_unique
sub = full_df[cols]
# select numeric columns for correlation
num = sub.select_dtypes(include=[np.number])
# columns with more than one unique non-null value
# Use pd.unique on the dropped-NA values to ensure we get a concrete length
# (avoids ambiguous truth values if nunique ever returns a non-scalar)
keep_cols = [
c for c in num.columns
if len(pd.unique(num[c].dropna())) > 1
]
# compute correlation only on keep_cols
if keep_cols:
with np.errstate(invalid='ignore', divide='ignore'):
corr_partial = num[keep_cols].corr(method=method)
else:
corr_partial = pd.DataFrame()
# build a full square matrix with original cols, fill with NaN
full_corr = pd.DataFrame(index=cols, columns=cols, dtype=float)
if not corr_partial.empty:
# place partial results into full matrix for the kept cols
for r in corr_partial.index:
for c in corr_partial.columns:
full_corr.at[r, c] = corr_partial.at[r, c]
return full_corr
def create_constructor_adjusted_driver_features(data):
"""
Create driver performance features that are adjusted by constructor performance.
This helps account for drivers who have changed teams.
"""
try:
# Check if required columns exist
required_cols = ['grandPrixYear', 'constructorName', 'resultsFinalPositionNumber']
if not all(col in data.columns for col in required_cols):
return data
# Handle Points column (could have different names)
points_col = None
for col in ['Points', 'Points_results_with_qualifying', 'points']:
if col in data.columns:
points_col = col
break
# Handle podium column
podium_col = None
for col in ['resultsPodium', 'podium', 'Podium']:
if col in data.columns:
podium_col = col
break
# Calculate constructor performance by year
agg_dict = {'resultsFinalPositionNumber': 'mean'}
col_names = ['grandPrixYear', 'constructorName', 'constructorAvgPosition']
if points_col:
agg_dict[points_col] = 'mean'
col_names.append('constructorAvgPoints')
if podium_col:
agg_dict[podium_col] = 'mean'
col_names.append('constructorPodiumRate')
# Sort by year + a race-ordering column so shift(1) gives accurate historical avg
sort_cols = ['grandPrixYear', 'constructorName']
for rc in ['round', 'Round', 'race_round', 'grandPrixRound', 'raceId_results', 'grandPrixRaceId']:
if rc in data.columns:
sort_cols.append(rc)
break
data_sorted = data.sort_values(sort_cols).copy()
# Compute historical (leakage-free) constructor avg using expanding mean shifted by 1
data_sorted['constructorAvgPosition'] = (
data_sorted.groupby(['grandPrixYear', 'constructorName'])['resultsFinalPositionNumber']
.transform(lambda x: x.shift(1).expanding().mean())
)
if points_col:
data_sorted['constructorAvgPoints'] = (
data_sorted.groupby(['grandPrixYear', 'constructorName'])[points_col]
.transform(lambda x: x.shift(1).expanding().mean())
)
if podium_col:
data_sorted['constructorPodiumRate'] = (
data_sorted.groupby(['grandPrixYear', 'constructorName'])[podium_col]
.transform(lambda x: x.shift(1).expanding().mean())
)
# driverVsConstructorPosition: driver pos vs historical constructor avg (leakage-free)
# Note: we intentionally do NOT include driverVsConstructorPosition as a model feature
# because it involves resultsFinalPositionNumber and risks encoding the target.
# constructorAvgPosition (historical) is the useful signal here.
return data_sorted
except Exception as e:
return data
def create_recent_performance_features(data, recent_races=5):
"""
Create features based on recent performance to weight newer data more heavily.
"""
try:
# Check if required columns exist
required_cols = ['resultsDriverId', 'grandPrixYear', 'resultsFinalPositionNumber']
if not all(col in data.columns for col in required_cols):
return data
# Check for round column (might have different names)
round_col = None
for col in ['round', 'Round', 'race_round', 'grandPrixRound']:
if col in data.columns:
round_col = col
break
if not round_col:
return data
# Handle Points column
points_col = None
for col in ['Points', 'Points_results_with_qualifying', 'points']:
if col in data.columns:
points_col = col
break
data_sorted = data.sort_values(['resultsDriverId', 'grandPrixYear', round_col]).copy()
# Calculate rolling averages for recent performance (leakage-free: shift(1) excludes current race)
for window in [3, 5, 10]:
data_sorted[f'recentAvgPosition_{window}'] = (
data_sorted.groupby('resultsDriverId')['resultsFinalPositionNumber']
.transform(lambda x: x.shift(1).rolling(window=window, min_periods=1).mean())
)
if points_col:
data_sorted[f'recentAvgPoints_{window}'] = (
data_sorted.groupby('resultsDriverId')[points_col]
.transform(lambda x: x.shift(1).rolling(window=window, min_periods=1).mean())
)
return data_sorted
except Exception as e:
return data
def create_constructor_compatibility_features(data):
"""
Create features that measure how well a driver performs with their current constructor
vs their career average.
"""
try:
# Check if required columns exist
required_cols = ['resultsDriverId', 'constructorName', 'resultsFinalPositionNumber']
if not all(col in data.columns for col in required_cols):
return data
# Handle Points and podium columns
points_col = None
for col in ['Points', 'Points_results_with_qualifying', 'points']:
if col in data.columns:
points_col = col
break
podium_col = None
for col in ['resultsPodium', 'podium', 'Podium']:
if col in data.columns:
podium_col = col
break
# Determine sort column for temporal ordering (leakage-free)
sort_cols = ['grandPrixYear', 'resultsDriverId']
for rc in ['round', 'Round', 'race_round', 'grandPrixRound', 'raceId_results', 'grandPrixRaceId']:
if rc in data.columns:
sort_cols.insert(1, rc)
break
data_sorted = data.sort_values(sort_cols).copy()
# Driver career averages — historical only (shift(1) before expanding mean, no leakage)
data_sorted['driverCareerAvgPosition'] = (
data_sorted.groupby('resultsDriverId')['resultsFinalPositionNumber']
.transform(lambda x: x.shift(1).expanding().mean())
)
if points_col:
data_sorted['driverCareerAvgPoints'] = (
data_sorted.groupby('resultsDriverId')[points_col]
.transform(lambda x: x.shift(1).expanding().mean())
)
if podium_col:
data_sorted['driverCareerPodiumRate'] = (
data_sorted.groupby('resultsDriverId')[podium_col]
.transform(lambda x: x.shift(1).expanding().mean())
)
# Driver-constructor averages — historical only (shift(1) before expanding mean)
data_sorted['driverConstructorAvgPosition'] = (
data_sorted.groupby(['resultsDriverId', 'constructorName'])['resultsFinalPositionNumber']
.transform(lambda x: x.shift(1).expanding().mean())
)
if points_col:
data_sorted['driverConstructorAvgPoints'] = (
data_sorted.groupby(['resultsDriverId', 'constructorName'])[points_col]
.transform(lambda x: x.shift(1).expanding().mean())
)
if podium_col:
data_sorted['driverConstructorPodiumRate'] = (
data_sorted.groupby(['resultsDriverId', 'constructorName'])[podium_col]
.transform(lambda x: x.shift(1).expanding().mean())
)
# Races with constructor up to (but not including) current race
data_sorted['racesWithConstructor'] = (
data_sorted.groupby(['resultsDriverId', 'constructorName']).cumcount()
)
data_enhanced = data_sorted
# Create compatibility metrics
if 'driverCareerAvgPosition' in data_enhanced.columns and 'driverConstructorAvgPosition' in data_enhanced.columns:
data_enhanced['constructorCompatibilityPosition'] = data_enhanced['driverCareerAvgPosition'] - data_enhanced['driverConstructorAvgPosition']
if points_col and 'driverCareerAvgPoints' in data_enhanced.columns and 'driverConstructorAvgPoints' in data_enhanced.columns:
data_enhanced['constructorCompatibilityPoints'] = data_enhanced['driverConstructorAvgPoints'] / (data_enhanced['driverCareerAvgPoints'] + 0.1)
# Weight by experience with constructor (more races = more reliable metric)
if 'racesWithConstructor' in data_enhanced.columns:
data_enhanced['constructorExperienceWeight'] = np.clip(data_enhanced['racesWithConstructor'] / 10, 0.1, 1.0)
return data_enhanced
except Exception as e:
return data
def _safe_numeric(value, default=10.0):
"""Convert nullable or non-numeric values to a float, falling back to a default."""
if pd.isna(value):
return float(default)
try:
return float(value)
except (TypeError, ValueError):
return float(default)
def simulate_rookie_predictions(data, all_active_driver_inputs, current_year, n_simulations=1000):
"""
Adjust rookie driver predictions using Monte Carlo simulation based on historical rookie results,
constructor strength, and practice position.
"""
# Identify rookie drivers (first F1 season or <5 starts)
# Calculate the number of races in the current season
current_season_race_count = raceSchedule[raceSchedule['year'] == current_year]['grandPrixId'].nunique()
# st.write("Current season race count:", current_season_race_count)
# Rookie mask: drivers with fewer starts than a full season
rookie_mask = all_active_driver_inputs['driverTotalRaceStarts'] < current_season_race_count
rookies = all_active_driver_inputs[rookie_mask].copy()
# Get the current race name
race_name = rookies['grandPrixName'].iloc[0] if 'grandPrixName' in rookies.columns and len(rookies) > 0 else None
# Historical rookie results at this track
historical_rookies = data[
(data['grandPrixName'] == race_name) &
(data['yearsActive'] <= 1) &
(data['grandPrixYear'] < current_year)
]
# If not enough historical rookies, fallback to all tracks
if len(historical_rookies) < 10:
historical_rookies = data[
(data['yearsActive'] <= 1) &
(data['grandPrixYear'] < current_year)
]
# For each rookie, simulate their predicted position
for idx, rookie in rookies.iterrows():
# Sample historical rookie final positions
hist_positions = historical_rookies['resultsFinalPositionNumber'].dropna()
if len(hist_positions) < 3:
# Fallback to all drivers if not enough rookie data
hist_positions = data['resultsFinalPositionNumber'].dropna()
mu, sigma = hist_positions.mean(), hist_positions.std()
# Truncate between 1 and 20 (F1 grid)
a, b = (1 - mu) / sigma, (20 - mu) / sigma
sampled_positions = truncnorm.rvs(a, b, loc=mu, scale=sigma, size=n_simulations)
# Adjust by constructor strength (lower rank = better team)
constructor_rank = _safe_numeric(rookie.get('constructorRank', 10), default=10.0)
constructor_adj = np.clip(1 + (constructor_rank - 10) * 0.2, 0.7, 1.3)
# Adjust by practice position (if available)
practice_adj = 1.0
practice_position = _safe_numeric(rookie.get('averagePracticePosition', np.nan), default=np.nan)
if not pd.isna(practice_position):
practice_adj = np.clip(practice_position / 10, 0.7, 1.3)
# Simulate predicted position
simulated_positions = sampled_positions * constructor_adj * practice_adj
predicted = np.median(simulated_positions)
# Assign to output DataFrame
# all_active_driver_inputs.at[idx, 'PredictedFinalPosition'] = predicted
# ...inside the for idx, rookie in rookies.iterrows(): loop...
col = 'PredictedFinalPosition'
if col in all_active_driver_inputs.columns:
dtype = all_active_driver_inputs[col].dtype
all_active_driver_inputs.at[idx, col] = dtype.type(predicted)
else:
all_active_driver_inputs.at[idx, col] = float(predicted)
col = 'PredictedFinalPositionStd'
std_value = float(np.std(simulated_positions))
if col in all_active_driver_inputs.columns:
dtype = all_active_driver_inputs[col].dtype
all_active_driver_inputs.at[idx, col] = dtype.type(std_value)
else:
all_active_driver_inputs.at[idx, col] = float(std_value)
# all_active_driver_inputs.at[idx, 'PredictedFinalPositionStd'] = np.std(simulated_positions)
return all_active_driver_inputs
def simulate_rookie_dnf(data, all_active_driver_inputs, current_year, n_simulations=1000):
"""
Adjust rookie DNF probability using Monte Carlo simulation based on historical rookie DNFs.
"""
# Calculate the number of races scheduled in the current season
current_season_race_count = raceSchedule[raceSchedule['year'] == current_year]['grandPrixId'].nunique()
# Identify rookies: fewer starts than a full season
rookie_mask = all_active_driver_inputs['driverTotalRaceStarts'] < current_season_race_count
rookies = all_active_driver_inputs[rookie_mask].copy()
# Get current race name
race_name = rookies['grandPrixName'].iloc[0] if 'grandPrixName' in rookies.columns and len(rookies) > 0 else None
# Historical rookie DNFs at this track
historical_rookies = data[
(data['grandPrixName'] == race_name) &
(data['yearsActive'] <= 1) &
(data['grandPrixYear'] < current_year)
]
# If not enough historical rookies, fallback to all tracks
if len(historical_rookies) < 10:
historical_rookies = data[
(data['yearsActive'] <= 1) &
(data['grandPrixYear'] < current_year)
]
# For each rookie, simulate DNF probability
for idx, rookie in rookies.iterrows():
# Sample historical rookie DNFs (1 if DNF, 0 if not)
hist_dnfs = historical_rookies['DNF'].dropna().astype(int)
if len(hist_dnfs) < 3:
# Fallback to all drivers if not enough rookie data
hist_dnfs = data['DNF'].dropna().astype(int)
# Monte Carlo simulation
sampled_dnfs = np.random.choice(hist_dnfs, size=n_simulations, replace=True)
# Adjust by constructor reliability (lower rank = better team)
constructor_rank = _safe_numeric(rookie.get('constructorRank', 10), default=10.0)
constructor_adj = np.clip(1 - (constructor_rank - 10) * 0.03, 0.85, 1.05)
# Adjust by practice reliability (if available)
practice_adj = 1.0
practice_position = _safe_numeric(rookie.get('averagePracticePosition', np.nan), default=np.nan)
if not pd.isna(practice_position):
practice_adj = np.clip(1 - (practice_position / 100), 0.85, 1.05)
# Simulate DNF probability
simulated_dnf_proba = sampled_dnfs * constructor_adj * practice_adj
predicted_dnf = np.mean(simulated_dnf_proba)
# Assign to output DataFrame
all_active_driver_inputs.at[idx, 'PredictedDNFProbability'] = predicted_dnf
all_active_driver_inputs.at[idx, 'PredictedDNFProbabilityStd'] = np.std(simulated_dnf_proba)
return all_active_driver_inputs
# Done to avoid getting an error on Github after upload
if os.environ.get('LOCAL_RUN') == '1':
import fastf1
fastf1.Cache.enable_cache(path.join(DATA_DIR, 'f1_cache'))
st.set_page_config(
page_title="Gridlocked - Formula 1 Betting & Analytics",
page_icon=path.join(DATA_DIR, 'favicon.png'),
layout="wide",
initial_sidebar_state="expanded"
)
log_memory('after application imports')
def km_to_miles(km):
return km * 0.621371
def get_dataframe_height(df, row_height=35, header_height=38, padding=2, max_height=600):
"""
Calculate the optimal height for a Streamlit dataframe based on number of rows.
Args:
df (pd.DataFrame): The dataframe to display
row_height (int): Height per row in pixels. Default: 35
header_height (int): Height of header row in pixels. Default: 38
padding (int): Extra padding in pixels. Default: 2
max_height (int): Maximum height cap in pixels. Default: 600 (None for no limit)
Returns:
int: Calculated height in pixels
Example:
height = get_dataframe_height(my_df)
st.dataframe(my_df, height=height)
"""
num_rows = len(df)
calculated_height = (num_rows * row_height) + header_height + padding
if max_height is not None:
return min(calculated_height, max_height)
return calculated_height
def display_model_performance(metrics=None, position_mae=None, title=None):
"""Render model summary metrics and optional position-group MAE in a compact, readable format.
- Top row: four quick cards (MSE, R^2, MAE, Mean Error)
- Bottom: small table for position-specific MAE values
Args:
metrics (dict): {'Mean Squared Error': float, 'R^2 Score': float, 'Mean Absolute Error': float, 'Mean Error': float}
position_mae (dict): {'Podium (1-3)': 1.234, 'Winners': 1.111, ...}
title (str): optional subheader text
"""
if title:
st.subheader(title)
# Render top-line metrics as 4 small cards
if metrics:
cols = st.columns(4)
labels = ["Mean Squared Error", "R^2 Score", "Mean Absolute Error", "Mean Error"]
for c, label in zip(cols, labels):
val = None
# accept either long-form labels or short keys
for key in (label, label.replace(' ', '_').lower(), label.split(' ')[0].lower()):
if metrics.get(key) is not None:
val = metrics.get(key)
break
# format value for display
if val is None or (isinstance(val, float) and np.isnan(val)):
disp = "—"
else:
if label == 'R^2 Score':
disp = f"{val:.3f}"
elif label in ('Mean Error', 'Mean Absolute Error'):
disp = f"{val:.2f}"
else:
disp = f"{val:.3f}"
c.metric(label, disp)
# Position-group MAE table (interactive)
if position_mae:
pos_df = pd.DataFrame(list(position_mae.items()), columns=["Position Group", "MAE"])
# keep MAE numeric so users can sort/filter; show 3 decimals
pos_df['MAE'] = pos_df['MAE'].astype(float).round(3)
height = get_dataframe_height(pos_df, max_height=200)
styled = pos_df.set_index('Position Group').style.format({"MAE": "{:.3f}"})
st.dataframe(styled, width='content', height=height)
# small visual spacer
st.write('')
def get_last_modified_file(dir_path):
try:
files = [path.join(dir_path, f) for f in os.listdir(dir_path) if path.isfile(os.path.join(dir_path, f))]
if not files:
return None
last_modified_file = max(files, key=path.getmtime)
return last_modified_file
except Exception as e:
st.write(f"An error occurred: {e}")
return None
latest_file = get_last_modified_file(DATA_DIR)
if latest_file is not None:
modification_time = path.getmtime(latest_file)
#readable_time = time.ctime(modification_time)
readable_time = datetime.datetime.fromtimestamp(modification_time).strftime('%Y-%m-%d %I:%M %p')
else:
readable_time = "No data files found"
def reset_filters():
# Assuming you have filters stored in session state
print(f"Session keys: {st.session_state.keys()}")
for key in st.session_state.keys():
if key.startswith('filter_'):
st.session_state[key] = None
def highlight_correlation(val):
if val >= 0.6 and val < 1.0:
color = 'green'
elif val < -0.6:
color = 'red'
else:
color = 'white'
return f'background-color: {color}'
#def reset():
# st.session_state.selection = ' All'
#st.sidebar.button('Reset', on_click=reset_filters())
column_rename_for_filter = {
'constructorName': 'Constructor',
'grandPrixName': 'Race',
'grandPrixYear': 'Year',
'positionsGained': 'Positions Gained',
'resultsDriverName': 'Driver',
'resultsFinalPositionNumber' : 'Final Position',
'resultsPodium': 'Podium',
'resultsStartingGridPositionNumber': 'Starting Position',
'resultsTop10': 'Top 10',
'resultsTop5': 'Top 5',
'short_date': 'Race Date',
'DNF' : 'DNF',
'resultsReasonRetired': 'Reason Retired',
'averagePracticePosition': 'Average Practice Pos.',
'lastFPPositionNumber': 'Last Free Practice Pos.',
'resultsQualificationPositionNumber': 'Qualifying Pos.',
'q1End': 'Out at Q1',
'q2End': 'Out at Q2',
'q3Top10': 'Q3 Top 10',
'numberOfStops': 'Number of Stops',
'averageStopTime': 'Average Pit Stop Time (s)',
'totalStopTime': 'Total Pit Stop Time (s)',
'grandPrixLaps': 'Laps (Race)',
'constructorTotalRaceStarts': 'Constructor Total Starts',
'constructorTotalRaceWins': 'Constructor Total Wins',
'constructorTotalPolePositions': 'Total Pole Positions (Constructor)',
'turns': 'Turns (Race)',
'driverBestStartingGridPosition': 'Best Starting Grid Position (Driver)',
'driverBestRaceResult': 'Best Result (Driver)',
'driverTotalChampionshipWins': 'Total Championship Wins (Driver)',
'driverTotalRaceEntries': 'Total Entries (Driver)',
'driverTotalRaceStarts': 'Total Starts (Driver)',
'driverTotalRaceWins': 'Total Wins (Driver)',
'driverTotalRaceLaps': 'Total Laps (Driver)',
'driverTotalPodiums': 'Total Podiums (Driver)',
'driverTotalPolePositions': 'Total Pole Positions (Driver)',
'activeDriver': 'Active Driver (Raced This Year)',
'yearsActive': 'Years Active',
'streetRace' : 'Street',
'trackRace': 'Track',
'primary_compound': 'Primary Compound',
'Points': 'Current Year Points (Driver)',
'constructorRank': 'Constructor Rank',
'driverRank': 'Driver Rank',
'bestChampionshipPosition': 'Best Champ Pos.',
'bestStartingGridPosition': 'Best Starting Grid Pos.',
'bestRaceResult': 'Best Race Result',
'totalChampionshipWins': 'Total Champ Wins',
'totalRaceEntries': 'Total Race Entries',
'totalRaceStarts': 'Total Race Starts',
'totalRaceWins': 'Total Race Wins',
'total1And2Finishes': 'Total 1st and 2nd',
'totalRaceLaps': 'Total Race Laps (Constructor)',
'totalPodiums': 'Total Podiums (Constructor)',
'totalPodiumRaces': 'Total Podium Races (Constructor)',
'totalPoints' : 'Total Points (Lifetime)',
'totalChampionshipPoints': 'Total Champ Points',
# 'totalPolePositions' : 'Total Pole Positions',
'totalFastestLaps': 'Total Fastest Laps',
# 'bestQualifyingTime_sec': 'Best Qualifying Time (s)',
# 'delta_from_race_avg': 'Delta from Race Avg. (s)',
'driverAge': 'Driver Age',
'currentRookie': 'Current Rookie',