-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_container.py
374 lines (298 loc) · 13.2 KB
/
main_container.py
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
# Main container setup
import math
import numpy as np
from scipy import stats
import streamlit as st
import plotly.express as px
import pandas as pd
from plotly.colors import n_colors
from plotly import graph_objects as go
def get_driver_names_from_id(drivers, drivers_df):
driver_names = []
for driver in drivers:
driver_names_df = drivers_df.loc[(drivers_df["driver_id"] == driver), ["forename", "surname"]]
for i, row in driver_names_df.iterrows():
name = row["forename"] + " " + row["surname"]
driver_names.append(name)
return driver_names
def get_driver_ids(drivers, drivers_df):
driver_ids = []
for driver in drivers:
driver_name = driver.split(" ")
driver_id = drivers_df.loc[(drivers_df["forename"] == driver_name[0]) & (drivers_df["surname"] == driver_name[1]), "driver_id"]
items = driver_id.items() # Series size should always be 1 because 'ID' is unique
for item in items:
driver_ids.append(item[1])
return driver_ids
def metric_setup(year, d_ids, standings_df, races_df, drivers_df, laps_df, c_df):
data = {}
count = len(d_ids)
for d_name in d_ids:
data[d_name] = {"points": 0, "wins": 0 }
driver_name = d_name.split(" ")
driver_id = drivers_df.loc[(drivers_df["forename"] == driver_name[0]) & (drivers_df["surname"] == driver_name[1]), "driver_id"]
for d in driver_id.items():
d_id = d[1]
fastest_laps_per_race = {}
races = races_df.loc[races_df["year"] == year, ["race_id", "circuit_id"]]
for index, r in races.iterrows():
# Obtains each race the selected driver was in for the selected year
dvrs = standings_df.loc[(standings_df["race_id"] == r["race_id"]) & (standings_df["driver_id"] == d_id), ["points", "wins"]]
data[d_name]["points"] = dvrs["points"].max()
data[d_name]["wins"] = dvrs["wins"].max()
# Obtains all lap times for that race
lap_times = laps_df.loc[(laps_df["race_id"] == r["race_id"]) & (laps_df["driver_id"] == d_id), ["time", "milliseconds"]]
fastest = 999999 # Milliseconds stores the time in milliseconds
time = 0
for index, row in lap_times.iterrows():
if row["milliseconds"] < fastest:
fastest = row["milliseconds"]
time = row["time"]
if time != 0:
fastest_laps_per_race[r["circuit_id"]] = {"time": row["time"], "ms": row["milliseconds"], "race":r["race_id"]}
data[d_name]["fastest_laps"] = fastest_laps_per_race
best_time = [999999, ""]
time = 0
wins = [0, ""]
points = [0, ""]
for driver in data:
if data[driver]["wins"] > wins[0]:
wins[0] = data[driver]["wins"]
wins[1] = driver
if data[driver]["points"] > points[0]:
points[0] = data[driver]["points"]
points[1] = driver
for obj in data[driver]["fastest_laps"].values():
mscds = obj["ms"]
if mscds < best_time[0]:
best_time[0] = mscds
time = obj["time"]
best_time[1] = driver
# b = list(fastest_laps_per_race.keys())[list(fastest_laps_per_race.values()).index(obj)]
# c_name = c_df.loc[c_df['circuit_id'] == b, "name"]
if wins[1] == "":
wins.pop(1)
if points[1] == "":
points.pop(1)
if best_time[1] == "":
best_time.pop(1)
val_wins = wins[0]
title_wins = "Total Wins"
val_points = int(points[0])
title_points = "Total Points"
title_time = "Fastest Lap"
if time == 0: time="No time set"
val_time = time
if count > 1:
title_wins = "Most Wins"
title_points = "Most Points"
if len(wins)==2:
val_wins = f"{wins[1]} [{wins[0]}]"
else:
val_wins = "N/A"
if len(points)==2:
val_points = f"{points[1]} [{int(points[0])}]"
else:
val_points = "N/A"
if len(best_time)==2:
val_time = f"{best_time[1]} [{time}]"
col1, col2, col3 = st.columns(3)
col1.metric(title_wins, value=val_wins)
col2.metric(title_time, value=val_time)
col3.metric(title_points, value=val_points)
def final_pos_graph(year, results_df, races_df, d_ids, drivers_df, scale):
finals = {}
count = len(d_ids)
for i in range(len(d_ids)):
finals[f"x{i}"] = []
finals[f"y{i}"] = []
names = []
pos_order = []
drivers = get_driver_names_from_id(d_ids, drivers_df)
for i, d_id in enumerate(d_ids):
races = races_df.loc[races_df["year"] == year, ["race_id", "circuit_id", "name"]]
for index, r in races.iterrows():
# Obtains each race the selected driver was in for the selected year
race_pos = results_df.loc[(results_df["race_id"] == r["race_id"]) & (results_df["driver_id"] == d_id), "position"]
race_pos = race_pos.replace('\\N','DNF')
if r["name"] not in names: names.append(r["name"])
for pos in race_pos.items():
finals[f"x{i}"].append(r["race_id"])
finals[f"y{i}"].append(pos[1])
if pos[1] not in pos_order:
if pos[1] != "DNF":
pos_order.append(int(pos[1]))
fig = go.Figure()
vals = []
for num in range(count):
for v in finals[f"x{num}"]:
vals.append(v)
fig.add_trace(go.Scatter(x=finals[f"x{num}"], y=finals[f"y{num}"], name=drivers[num], mode="markers+lines", line_color=scale[num]))
pos_order.sort() # Orders positions by numbers
pos_order.append("DNF") # Adds DNF position for bottom of graph
fig.update_layout(
title=go.layout.Title(text="Finishing Positions"),
xaxis = dict(
title = "Race",
tickangle = -45,
tickmode = 'array',
tickvals = vals,
ticktext = names,
type = "category"),
yaxis = dict(
title = "Finishing Position",
type = "category",
categoryorder ='array',
autorange = "reversed",
categoryarray = pos_order)
)
st.plotly_chart(fig, use_container_width=True)
def lap_times_graph(year, d_ids, laps_df, races_df, col):
for d_id in d_ids:
times = {"x": [], "y": [], "Name": [], "Lap": [], "Time": []}
# Obtains each race the selected driver was in for the selected year
races_df = races_df.loc[races_df["year"] == year, ["race_id", "name"]]
for index, r in races_df.iterrows():
df_laps = laps_df.loc[(laps_df["race_id"] == r["race_id"]) & (laps_df["driver_id"] == d_id), ["lap", "time", "milliseconds"]]
df_laps2 = df_laps.sort_values(by="milliseconds")
for index, r1 in df_laps.iterrows():
times["x"].append(r1["milliseconds"])
times["y"].append(r["race_id"])
times["Name"].append(r["name"])
times["Lap"].append(r1["lap"])
times["Time"].append(r1["time"])
df = pd.DataFrame(data=times)
# Remove outliers
z = np.abs(stats.zscore(df['x']))
threshold = 3
outliers = df[z > threshold]
df = df.drop(outliers.index)
fig = px.strip(df, x="x", y="y",title="Lap Times<br><sub class='subtitle'>Hover over points for more details</sub>",
labels = {"x": "Lap time", "y": "Race"},
color_discrete_sequence = n_colors("rgb(255, 75, 75)", "rgb(255,255,255)", 3, colortype="rgb"), color="y",
hover_name="Name", hover_data={"x":False, "y":False, "Lap":True, "Time":True})
fig.update_xaxes(type='date', tickformat='%M:%S.%f%f')
fig.update_layout(
showlegend = False,
yaxis = dict(
side = "right",
showticklabels = False),
xaxis = dict(
tickangle = -45)
)
col.plotly_chart(fig, use_container_width=True)
def avg_lap_times_graph(year, d_ids, laps_df, races_df, col, scale, drivers_df):
final_avgs = {}
count = len(d_ids)
for i in range(len(d_ids)):
final_avgs[f"x{i}"] = []
final_avgs[f"y{i}"] = []
names = []
drivers = get_driver_names_from_id(d_ids, drivers_df)
for i, d_id in enumerate(d_ids):
# Obtains each race the selected driver was in for the selected year
races = races_df.loc[races_df["year"] == year, ["race_id", "name"]]
for index, r in races.iterrows():
df_laps = laps_df.loc[(laps_df["race_id"] == r["race_id"]) & (laps_df["driver_id"] == d_id), "milliseconds"]
avg_lap = df_laps.mean()
if math.isnan(avg_lap) == False:
avg_lap = int(avg_lap)
final_avgs[f"x{i}"].append(avg_lap)
final_avgs[f"y{i}"].append(r["race_id"])
name = r["name"].replace("Grand Prix", "GP")
if name not in names: names.append(name)
fig = False
for num in range(count):
if (len(final_avgs[f"x{num}"])>0) and (len(final_avgs[f"y{num}"])>0):
fig = go.Figure()
break
vals = []
if fig != False:
for num in range(count):
# print(final_avgs[f"x{num}"], final_avgs[f"x{num}"])
if (len(final_avgs[f"x{num}"])>0) and (len(final_avgs[f"y{num}"])>0):
for v in final_avgs[f"y{num}"]:
if v not in vals:
vals.append(v)
fig.add_trace(go.Scatter(x=final_avgs[f"x{num}"], y=final_avgs[f"y{num}"], name=drivers[num], mode="markers", marker={'size': 10}, marker_color=scale[num]))
fig.update_layout(
title=go.layout.Title(text="Average lap time (per race)"),
xaxis = dict(
title = "Average lap time",
type = 'date',
tickformat = '%M:%S.%f%f',
tickangle = -45,
dtick=10000),
yaxis = dict(
title = "Race",
tickmode = 'array',
tickvals = vals,
ticktext = names,
type = "category")
)
col.plotly_chart(fig, use_container_width=True)
else:
col.subheader("Average lap times (per race)")
col.write("Unable to retrieve suitable data")
def points_graph(year, d_ids, col, races_df, results_df, scale, drivers_df):
d_names = get_driver_names_from_id(d_ids, drivers_df)
race_names = []
final_points = {}
count = len(d_ids)
for i in range(len(d_ids)):
final_points[f"x{i}"] = []
final_points[f"y{i}"] = []
for i, d_id in enumerate(d_ids):
# Obtains each race the selected driver was in for the selected year
races = races_df.loc[races_df["year"] == year, ["race_id", "name"]]
for index, r in races.iterrows():
name = r["name"].replace("Grand Prix", "GP")
if name not in race_names: race_names.append(name)
df_points = results_df.loc[(results_df["race_id"] == r["race_id"]) & (results_df["driver_id"] == d_id), "points"]
for race in df_points.items():
final_points[f"y{i}"].append(race[1])
final_points[f"x{i}"].append(r["race_id"])
vals = []
fig = go.Figure()
for num in range(count):
for v in final_points[f"x{num}"]:
if v not in vals:
vals.append(v)
fig.add_trace(go.Bar(x=final_points[f"x{num}"], y=final_points[f"y{num}"], name=d_names[num], marker_color=scale[num]))
fig.update_layout(
title=go.layout.Title(text="Total Points"),
# yaxis = dict(
# side = "right"),
xaxis = dict(
tickangle = -45,
tickmode = 'array',
tickvals = vals,
ticktext = race_names,
type = "category")
)
col.plotly_chart(fig, use_container_width=True)
def Main_Setup(filter_data, dfs):
# Dataframes
standings_df = dfs["driver_standings"]
races_df = dfs["races"]
drivers_df = dfs["drivers"]
laps_df = dfs["laps"]
c_df = dfs["circuits"]
results_df = dfs["results"]
year = filter_data["year"]
drivers = filter_data["drivers"]
st.header(f"Performance Overview - {year}", anchor=False)
if (len(drivers) == 0):
st.text("Select driver(s) to view performance overview")
driver_ids = get_driver_ids(drivers, drivers_df)
# Custom colours for GO
scale = ["#FF4B4B", "#FFA5A5", "#FFFFFF", "#666464", "#F76757"]
if (len(drivers) != 0):
metric_setup(year, drivers, standings_df, races_df, drivers_df, laps_df, c_df)
final_pos_graph(year, results_df, races_df, driver_ids, drivers_df, scale)
col1, col2 = st.columns(2, gap="large")
points_graph(year, driver_ids, col2, races_df, results_df, scale, drivers_df)
if (len(drivers) == 1):
lap_times_graph(year, driver_ids, laps_df, races_df, col1)
else:
avg_lap_times_graph(year, driver_ids, laps_df, races_df, col1, scale, drivers_df)