def last_race_results() -> tuple: 'Returns the place where the last race was hosted and the data.' current_date = pd.Timestamp(datetime.now()) session = {} found = False for i in range(1, 50): try: tmp = fastf1.get_session(current_date.year, i, 'Race') t = to_local_time(tmp.event['Location'], tmp.event['EventDate'].to_pydatetime()) if t != None: current_date = datetime.now(t.tzinfo) if t > current_date: session = fastf1.get_session(current_date.year, max(1, i - 1), 'Race') found = True break except: break if not found: Console.error("last_race_results()", "session is empty") return ("Error", "") session.load(telemetry=False, weather=False, messages=False) table = [] i = 1 for _, row in session.results.iterrows(): table.append([f"{i}", row['FullName'], row['TeamName'], row['Status'], str(row['Points'])]) i += 1 return (session.event['Location'], tabulate(table, headers=["Pos", "Driver", "TeamName", "Status", "Points"], tablefmt='orgtbl', numalign="right", stralign="center"))
def test_2019(): for evn in range(1, 22): # 21 races for ses in ('FP1', 'FP2', 'FP3', 'Q', 'R'): if evn == 17 and ses == 'FP3': continue # session did not take place session = ff1.get_session(2019, evn, ses) session.load_laps(with_telemetry=False)
def test_2019(): for evn in range(1, 21): for ses in ('FP1', 'FP2', 'FP3', 'Q', 'R'): if evn == 17 and ses == 'FP3': continue # session did not take place session = ff1.get_session(2019, evn, ses) session._load_summary()
def reference_laps_data(): # provides a reference instance of session and laps to tests which # require it import fastf1 fastf1.Cache.enable_cache("test_cache/") session = fastf1.get_session(2020, 'Italy', 'R') laps = session.load_laps() return session, laps
def test_speed_trace(): ff1.Cache.enable_cache("test_cache/") session = ff1.get_session(2020, 'Belgian', 'R') session.load_laps(with_telemetry=True) fastest = session.laps.pick_fastest().telemetry fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(fastest['Time'], fastest['Speed']) return fig
def test_speed_trace(): session = ff1.get_session(2020, 5, 'Q') session.load_laps() fastest = session.laps.pick_fastest().telemetry fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(fastest['Time'], fastest['Speed']) plotting.laptime_axis(ax, 'xaxis') return fig
def last_qualifying_results() -> tuple: 'Returns the place where the last qualifying was hosted and the data.' current_date = datetime.now() session = {} found = False for i in range(1, 50): try: tmp = fastf1.get_session(current_date.year, i, 'Q') t = to_local_time(tmp.event['Location'], get_time(tmp.event, "Qualifying").to_pydatetime()) if t != None: current_date = datetime.now(t.tzinfo) if t > current_date: session = fastf1.get_session(current_date.year, max(1, i - 1), 'Q') found = True break except: break if not found: Console.error("last_qualifying_results()", "session is empty") return ("Error", "") session.load(telemetry=False, weather=False, messages=False) table = [] i = 1 for _, row in session.results.iterrows(): table.append([f"{i}", row['FullName'], format_qualifying_time(f"{row['Q1']}"), format_qualifying_time(f"{row['Q2']}"), format_qualifying_time(f"{row['Q3']}")]) i += 1 return (session.event['Location'], tabulate(table, headers=["Pos", "Driver", "Q1", "Q2", "Q3"], tablefmt='orgtbl', numalign="right", stralign="center"))
def test_doc_example_fast_lec(): monza_quali = ff1.get_session(2019, 'Monza', 'Q') laps = monza_quali.load_laps() fast_leclerc = laps.pick_driver('LEC').pick_fastest() t = fast_leclerc.telemetry['Time'] vCar = fast_leclerc.telemetry['Speed'] fig, ax = plt.subplots() ax.plot(t, vCar, label='Fast') ax.set_xlabel('Time') ax.set_ylabel('Speed [Km/h]') ax.set_title('Leclerc is') ax.legend() return fig
def test_readme_example(): race = ff1.get_session(2019, 'Bahrain', 'R') laps = race.load_laps() lec = laps.pick_driver('LEC') ham = laps.pick_driver('HAM') fig, ax = plt.subplots() plotting.laptime_axis(ax) ax.plot(lec['LapNumber'], lec['LapTime'], color='red') ax.plot(ham['LapNumber'], ham['LapTime'], color='cyan') ax.set_title("LEC vs HAM") ax.set_xlabel("Lap Number") ax.set_ylabel("Lap Time") return fig
def test_readme_example(): ff1.Cache.enable_cache("test_cache/") race = ff1.get_session(2020, 'Belgian', 'R') laps = race.load_laps() lec = laps.pick_driver('LEC') ham = laps.pick_driver('HAM') fig, ax = plt.subplots() ax.plot(lec['LapNumber'], lec['LapTime'], color='red') ax.plot(ham['LapNumber'], ham['LapTime'], color='cyan') ax.set_title("LEC vs HAM") ax.set_xlabel("Lap Number") ax.set_ylabel("Lap Time") return fig
def test_doc_example_fast_lec(): ff1.Cache.enable_cache("test_cache/") session = ff1.get_session(2020, 'Belgian', 'R') laps = session.load_laps(with_telemetry=True) fast_leclerc = laps.pick_driver('LEC').pick_fastest() t = fast_leclerc.telemetry['Time'] vCar = fast_leclerc.telemetry['Speed'] fig, ax = plt.subplots() ax.plot(t, vCar, label='Fast') ax.set_xlabel('Time') ax.set_ylabel('Speed [Km/h]') ax.set_title('Leclerc is') ax.legend() return fig
def test_doc_example_delta_time(): quali = ff1.get_session(2019, 'Spain', 'Q') laps = quali.load_laps() lec = laps.pick_driver('LEC').pick_fastest() ham = laps.pick_driver('HAM').pick_fastest() fig, ax = plt.subplots() ax.plot(lec.telemetry['Space'], lec.telemetry['Speed'], color=plotting.TEAM_COLORS[lec['Team']]) ax.plot(ham.telemetry['Space'], ham.telemetry['Speed'], color=plotting.TEAM_COLORS[ham['Team']]) twin = ax.twinx() twin.plot(ham.telemetry['Space'], utils.delta_time(ham, lec), '--', color=plotting.TEAM_COLORS[lec['Team']]) return fig
def test_cache_used_and_clear(tmpdir): fastf1.Cache.enable_cache(tmpdir) session = fastf1.get_session(2020, 5, 'FP2') # rainy and short session, good for fast test/quick loading session.load_laps() cache_dir_path = os.path.join(tmpdir, session.api_path[8:]) # pickled result should now exist assert os.listdir(cache_dir_path) == ['car_data.ff1pkl', 'position_data.ff1pkl', 'timing_app_data.ff1pkl', 'timing_data.ff1pkl', 'track_status_data.ff1pkl'] # requests cache should exist and should be used (size larger than 10Mb) assert os.path.getsize(os.path.join(tmpdir, 'fastf1_http_cache.sqlite')) > 10e6 fastf1.Cache.clear_cache(tmpdir) # should delete pickle files assert os.listdir(cache_dir_path) == [] fastf1.Cache.clear_cache(tmpdir, deep=True) # should clear requests http cache assert os.path.getsize(os.path.join(tmpdir, 'fastf1_http_cache.sqlite')) < 50000 # 100kB
def test_doc_example_delta_time(): ff1.Cache.enable_cache("test_cache/") quali = ff1.get_session(2020, 'Belgian', 'R') laps = quali.load_laps(with_telemetry=True) lec = laps.pick_driver('LEC').pick_fastest() ham = laps.pick_driver('HAM').pick_fastest() fig, ax = plt.subplots() ax.plot(lec.telemetry['Distance'], lec.telemetry['Speed'], color=plotting.TEAM_COLORS[lec['Team']]) ax.plot(ham.telemetry['Distance'], ham.telemetry['Speed'], color=plotting.TEAM_COLORS[ham['Team']]) twin = ax.twinx() delta_time, ham_car_data, lec_car_data = utils.delta_time(ham, lec) ham_car_data = ham_car_data.add_distance() twin.plot(ham_car_data['Distance'], delta_time, '--', color=plotting.TEAM_COLORS[lec['Team']]) return fig
def test_doc_example_pronto_seb(): monza_quali = ff1.get_session(2019, 'Monza', 'Q') vettel = monza_quali.get_driver('VET') assert f"Pronto {vettel.name}?" == "Pronto Sebastian?"
# fast_leclerc = laps.pick_driver('LEC').pick_fastest() # lec_car_data = fast_leclerc.get_car_data() # t = lec_car_data['Time'] # vCar = lec_car_data['Speed'] # # The rest is just plotting # fig, ax = plt.subplots() # ax.plot(t, vCar, label='Fast') # ax.set_xlabel('Time') # ax.set_ylabel('Speed [Km/h]') # ax.set_title('Leclerc is') # ax.legend() # plt.show() # Latest testing testing_22 = ff1.get_session(2021, 'Abu Dhabi', 'R') round_23_laps = testing_22.load_laps(with_telemetry=True) round_23_laps.groupby('Compound')['LapTime'].mean() # Filter out TrackStatus=4 for safety car laps green_laps = round_23_laps.loc[round_23_laps['TrackStatus'] != '4'] green_laps.groupby('Compound')['LapTime'].agg(['mean', 'count']) # Plot Dist of Laptimes by Compound green_laps['LapTime'] = green_laps['LapTime'] / pd.to_timedelta(1, unit='s') sns.boxplot(x='Compound', y='LapTime', data=green_laps) sns.violinplot(x='Compound', y='LapTime', data=green_laps) # Try to plot two drivers raw fast laps ontop of each other
from matplotlib import pyplot as plt import fastf1 as ff1 from fastf1 import plotting plotting.setup_mpl() monza_quali = ff1.get_session(2019, 'Monza', 'Q') laps = monza_quali.load_laps(with_telemetry=True) fast_leclerc = laps.pick_driver('LEC').pick_fastest() lec_car_data = fast_leclerc.get_car_data() t = lec_car_data['Time'] vCar = lec_car_data['Brake'] # The rest is just plotting fig, ax = plt.subplots() ax.plot(t, vCar, label='Fast') ax.set_xlabel('Time') ax.set_ylabel('Speed [Km/h]') ax.set_title('Leclerc is') ax.legend() plt.show()
def test_2020(): for evn in range(1, 20): # 19 races for ses in ('FP1', 'FP2', 'FP3', 'Q', 'R'): session = ff1.get_session(2020, evn, ses) session.load_laps(with_telemetry=False)
""" ############################################################################## # Import FastF1 and load the data import fastf1 import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import cm import numpy as np fastf1.Cache.enable_cache('/home/masatsugu/git/code/python/fast_F1/cache') # replace with your cache directory session = fastf1.get_session(2022, 'Saudi Arabian Grand Prix', 'Q') session.load() lap = session.laps.pick_fastest() tel = lap.get_telemetry() # sphinx_gallery_defer_figures ############################################################################## # Prepare the data for plotting by converting it to the appropriate numpy # data types 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)
def test_doc_example_pronto_seb(): ff1.Cache.enable_cache("test_cache/") session = ff1.get_session(2020, 'Belgian', 'R') vettel = session.get_driver('VET') assert f"Pronto {vettel.name}?" == "Pronto Sebastian?"
def test_2020(): for evn in range(1, 7): for ses in ('FP1', 'FP2', 'FP3', 'Q', 'R'): session = ff1.get_session(2020, evn, ses) session._load_summary()
# import seaborn as sns import pandas as pd year = int(input(prompt="Year: ")) round_num = int(input(prompt="Round: ")) session_name = input("Session: ") start = r'C:\Users\Kyle\Documents\Projects\Data Projects\f1' direct = start + '\\fastf1_cache' ff1.Cache.enable_cache(direct) event = ff1.get_event(year, round_num) session = ff1.get_session(year, round_num, session_name) session_data = session.load(laps=True, telemetry=True, weather=False) laps = session.load_laps() laps.to_csv(start + "\\timing_data\\" + str(year) + "_" + str(round_num) + "_" + session_name + "_laps.csv", index=False) telem_final = pd.DataFrame() # Get fastest lap for each driver and get telemetry from lap for driver in laps['Driver'].unique(): try: telem = laps.pick_driver(
import fastf1 fastf1.Cache.enable_cache('/home/masatsugu/git/code/python/fast_F1/cache') session = fastf1.get_session(2019, 'Monza', 'Q') session.load(telemetry=False, laps=False, weather=False) vettel = session.get_driver('VET') print(f"Pronto {vettel['FirstName']}?")
def test_cache_used_and_clear(tmpdir, requests_mock, caplog): import fastf1 import requests caplog.set_level(logging.INFO) # log level for log capturing # create a custom requests session here so that requests_mock is # properly used test_session = requests.session() fastf1.api.requests_session = test_session # enable fastf1's own pickle cache fastf1.Cache.enable_cache(tmpdir) # create mock repsonses for general api requests with open('fastf1/testing/reference_data/2020_05_FP2/' 'ergast_race.raw', 'rb') as fobj: content = fobj.read() requests_mock.get('http://ergast.com/api/f1/2020/5.json', content=content, status_code=200) with open('fastf1/testing/reference_data/2020_05_FP2/' 'ergast_race_result.raw', 'rb') as fobj: content = fobj.read() requests_mock.get('http://ergast.com/api/f1/2020/5/results.json', content=content, status_code=200) with open('fastf1/testing/reference_data/2020_05_FP2/' 'map_data.raw', 'rb') as fobj: content = fobj.read() requests_mock.post('https://www.mapcoordinates.net/admin/component/edit/' 'Vpc_MapCoordinates_Advanced_GoogleMapCoords_Component/' 'Component/json-get-elevation', content=content, status_code=200) # rainy and short session, good for fast test/quick loading session = fastf1.get_session(2020, 5, 'FP2') # create mock responses for f1 api requests req_pages = ['timing_data', 'timing_app_data', 'track_status', 'session_status', 'car_data', 'position', 'weather_data'] for p in req_pages: with open(f'fastf1/testing/reference_data/2020_05_FP2/{p}.raw', 'rb') as fobj: lines = fobj.readlines() # ensure correct newline character (as expected by api parser) # strip all newline characters and terminate each line with \r\n # needs to work despite os and git newline character substitution content = b'' for line in lines: content += line.strip(b'\n').strip(b'\r') + b'\r\n' path = fastf1.api.base_url + session.api_path + fastf1.api.pages[p] requests_mock.get(path, content=content, status_code=200) # load the data session.load_laps(with_telemetry=True) # check cache directory, pickled results should now exist cache_dir_path = os.path.join(tmpdir, session.api_path[8:]) dir_list = os.listdir(cache_dir_path) expected_dir_list = ['car_data.ff1pkl', 'position_data.ff1pkl', 'session_status_data.ff1pkl', 'timing_app_data.ff1pkl', 'timing_data.ff1pkl', 'track_status_data.ff1pkl', 'weather_data.ff1pkl'] # test both ways round assert all(elem in expected_dir_list for elem in dir_list) assert all(elem in dir_list for elem in expected_dir_list) # recreate session and reload data # this should use the cache this time caplog.clear() session = fastf1.get_session(2020, 5, 'FP2') session.load_laps(with_telemetry=True) print(caplog.text) assert "Using cached data for" in caplog.text fastf1.Cache.clear_cache(tmpdir) # should delete pickle files assert os.listdir(cache_dir_path) == []
import fastf1 as ff1 import pandas as pd ff1.Cache.enable_cache("ff1") #add mapping for f1 races to numbers #should we limit it to hamilton + bottas? iracing_track_df = pd.read_csv("ff1_data/gp_to_iracing_mapping.csv", index_col=0) #obtains the data for f1 tracks for t in iracing_track_df.iloc: session = ff1.get_session(t.year, t.gp, "R") lap_data = session.load_laps() csv_path = "ff1_data/f1_data/" + t.gp + "_gp_" + str(t.year) + ".csv" lap_data.to_csv(csv_path)