formula1 / app.py
kbberendsen's picture
update cache and improve calc function
55a5cb3
raw
history blame
2.58 kB
from shiny import App, ui, render, reactive
from shinywidgets import output_widget, render_widget
import fastf1 as ff1
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import cm
import numpy as np
import os
from pathlib import Path
# Get the current directory
current_directory = Path.cwd()
# Specify the folder name you want to open (change 'folder_name' to your desired folder)
folder_name = 'cache'
# Create a Path object for the folder
folder_path = current_directory / folder_name
# Check if the cache folder exists
if folder_path.exists() and folder_path.is_dir():
print(f"The folder '{folder_name}' exists.")
else:
print(f"The folder '{folder_name}' does not exist.")
ff1.Cache.enable_cache(folder_path)
app_ui = ui.page_fluid(
ui.div(
ui.input_select(
"track", label="Track",
choices=["Austria", "Hungary", "Spanish Grand Prix"],
selected = "Austria"
),
class_="d-flex gap-3"
),
ui.output_plot("gear")
)
def server(input, output, session):
@reactive.Calc
def get_data():
f1_session = ff1.get_session(2023, input.track(), 'R')
f1_session.load()
lap = f1_session.laps.pick_fastest()
tel = lap.get_telemetry()
#converting data to numpy data tables
x = np.array(tel['X'].values)
y = np.array(tel['Y'].values)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
gear = tel['nGear'].to_numpy().astype(float)
return points, segments, gear
@output
@render.plot
def gear():
points = get_data().points
segments = get_data().segments
gear = get_data().gear
cmap = cm.get_cmap('Paired')
lc_comp = LineCollection(segments, norm=plt.Normalize(1, cmap.N+1), cmap=cmap)
lc_comp.set_array(gear)
lc_comp.set_linewidth(4)
plt.gca().add_collection(lc_comp)
plt.axis('equal')
plt.tick_params(labelleft=False, left=False, labelbottom=False, bottom=False)
##title = plt.suptitle(
## f"Fastest Lap Gear Shift Visualization\n"
## f"{lap['Driver']} - {f1_session.event['EventName']} {f1_session.event.year}"
## )
cbar = plt.colorbar(mappable=lc_comp, label="Gear", boundaries=np.arange(1, 10))
cbar.set_ticks(np.arange(1.5, 9.5))
cbar.set_ticklabels(np.arange(1, 9))
return plt
app = App(app_ui, server)