Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Key error when finding driver colours #538

Open
whatTheDodd opened this issue Mar 2, 2024 · 4 comments
Open

[BUG] Key error when finding driver colours #538

whatTheDodd opened this issue Mar 2, 2024 · 4 comments
Labels
stale No activity in a long time

Comments

@whatTheDodd
Copy link

whatTheDodd commented Mar 2, 2024

Describe the issue:

I am running a simple variation of one of the example projects, but when I run certain sessions (in this case 2023 Dutch Grand Prix but seemingly anything pre-2020), a KeyError is raised trying to get the driver_colour.

Reproduce the code example:

import fastf1 as ff1
import matplotlib.pyplot as plt
from fastf1 import plotting

# Enable caching and setup matplotlib
ff1.Cache.enable_cache('/dir/to/my/cache')
plotting.setup_mpl(misc_mpl_mods=False)
year = 2023
session = ff1.get_session(year, 'Dutch', 'R')
session.load(telemetry=False, weather=False)
fig, ax = plt.subplots(figsize=(8.0, 4.9))

for drivers in session.drivers:
    drive_laps = session.laps.pick_driver(drivers)
    abb = drive_laps['Driver'].iloc[0]
    colour = plotting.driver_color(abb)

    ax.plot(drive_laps['LapNumber'], drive_laps['Position'], label=abb, color=colour)

ax.set_ylim([20.5, 0.5])
ax.set_yticks([1, 5, 10, 15, 20])
ax.set_xlabel('Lap')
ax.set_ylabel('Position')

ax.legend(bbox_to_anchor=(1.0, 1.02))
plt.title(f"Position changes through {session.name}", fontsize=15)

plot_path = f"websiteimgs/{year}/{session.event.year}_{session.event.EventName}.png"
plt.savefig(plot_path, dpi=300)

Error message:

Traceback (most recent call last):
  File "/dir/to/my/project/Formula1/positions.py", line 18, in <module>
    colour = plotting.driver_color(abb)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/dir/to/my/project/Formula1/venv/lib/python3.11/site-packages/fastf1/plotting.py", line 267, in driver_color
    raise KeyError
KeyError

Process finished with exit code 1
@Casper-Guo
Copy link
Contributor

driver_color should not be relied upon if you are plotting any session from a previous season.

From the docs:

This function will try to find a matching driver for any identifier string that is passed to it. This involves case insensitive matching and partial string matching.

That is to say, it might give you a color that doesn't reflect the driver's past team. Or if the driver is no longer in F1, it will generate undefined behavior.

For working with previous seasons, I recommend defining a color map explicitly or using some sort of fall back values. For my own project I have this bandaid solution:

import fastf1.plotting as p

def pick_driver_color(driver: str) -> str:
    """Find the driver's color.

    If the driver is currently active, use his FastF1 color.
    Else, default to gray.
    """
    if p.DRIVER_TRANSLATE.get(driver, "NA") in p.DRIVER_COLORS:
        return p.DRIVER_COLORS[p.DRIVER_TRANSLATE[driver]]

    return "#808080"

@whatTheDodd
Copy link
Author

whatTheDodd commented Mar 3, 2024

I implemented the function and it works well on some races. However, it is giving me this error frequently now:

Traceback (most recent call last):
File "./Formula1/positions.py", line 24, in
abb = drive_laps['Driver'].iloc[0]
~~~~~~~~~~~~~~~~~~~~~~^^^
File "./Formula1/venv/lib/python3.11/site-packages/pandas/core/indexing.py", line 1073, in getitem
return self._getitem_axis(maybe_callable, axis=axis)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "./Formula1/venv/lib/python3.11/site-packages/pandas/core/indexing.py", line 1625, in _getitem_axis
self._validate_integer(key, axis)
File "./Formula1/venv/lib/python3.11/site-packages/pandas/core/indexing.py", line 1557, in _validate_integer
raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds

Apparently there is an issue with the iloc[0] call but I am not sure why that is becoming an issue now.

@Casper-Guo
Copy link
Contributor

Print out the dimension of drive_laps for sanity check. You might be getting empty slices

@theOehrly
Copy link
Owner

The original error is likely related to the fact that you are (most likely) using a FastF1 version before 3.1.0. At least, this is the only way for me to reproduce the problem. The 2023 GP had Lawson driving as replacement for Ricciardo and Lawson was only added with v3.1.0.
Still there remains the problem that driver_color only really supports the current season which is likely why older seasons fail more consistently. This problem will be resolved in the near future.

Apart from that, as suggested already, for the second error, verify that drive_laps is not empty. It's not guaranteed that there are laps for every driver in every session. If the driver did not participate in the session, then an empty Laps object is returned.

@theOehrly theOehrly added the stale No activity in a long time label Apr 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stale No activity in a long time
Projects
None yet
Development

No branches or pull requests

3 participants