### Install databallpy dependencies with poetry Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/quick_overview.md Run one of these commands to install dependencies. Use `poetry install` for general setup, `make deps` for Linux/macOS, or `poetry install --with docs,developing` for Windows. ```console $ poetry install $ make deps # for Linux/macOs $ poetry install --with docs,developing # for Windows ``` -------------------------------- ### Output of initial possession calculation Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Example output showing the possession array for each frame, with 'away_6' at the start and 'home_2' later. ```text ['away_6' 'away_6' 'away_6' ... 'home_2' 'home_2' 'home_2'] ``` -------------------------------- ### Install DataBallPy with pip Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/installation_page.ipynb Install the DataBallPy package from PyPI. The basic command installs the core package. Additional extras are available: '[kloppy]' to use kloppy as data parser, and '[accessible-space]' to enable the dangerous accessible space functionality. ```python pip install databallpy # Or if you are using kloppy as data parser: pip install 'databallpy[kloppy]' # Or if you want to make use of the dangerous accessible space functionality pip install 'databallpy[accessible-space]' ``` -------------------------------- ### Install Poetry with Official Installer Script Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/poetry_deps_manager.md Run this command in Command Prompt or PowerShell as an administrator to download and install Poetry using the official installer script. ```bash curl -sSL https://install.python-poetry.org | python3 - ``` -------------------------------- ### Save Tracking Video Example (save_tracking_video) Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/visualizations_page.ipynb Creates a video of tracking data using save_tracking_video with a pitch control heatmap overlay from get_pitch_control. Requires FFMPEG installed on your system and added to your path. ```python from databallpy.visualize import save_tracking_video heatmap_overlay = game.tracking_data.get_pitch_control( game.pitch_dimensions, start_idx=0, end_idx=100, ) save_tracking_video( game, start_idx=0, end_idx=100, save_folder=os.path.join(os.getcwd(), "static"), title="Tracking Video Example", events=["pass"], variable_of_interest=game.tracking_data.loc[0:100, "frame"], add_velocities=True, heatmap_overlay=heatmap_overlay, overlay_cmap="coolwarm", verbose=False, ) ``` -------------------------------- ### Check Poetry version Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/poetry_deps_manager.md Run this command in a new command prompt or PowerShell window to confirm Poetry is installed and accessible. The output should display the installed Poetry version. ```bash poetry --version ``` -------------------------------- ### Install DataBallPy with optional extras Source: https://github.com/alek050/databallpy/blob/develop/README.md Install DataBallPy with optional extras: 'kloppy' for loading any kloppy-supported provider, and 'accessible-space' for Dangerous Accessible Space. ```bash pip install 'databallpy[kloppy]' # load any kloppy-supported provider ``` ```bash pip install 'databallpy[accessible-space]' # Dangerous Accessible Space ``` -------------------------------- ### Install DataBallPy with pip Source: https://github.com/alek050/databallpy/blob/develop/docs/introduction/intro_page.md Install the DataBallPy package from PyPi using pip. Run this command in your terminal or command prompt. ```bash $ pip install databallpy ``` -------------------------------- ### Output of value_counts Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Example output showing the number of frames each player has possession, with home_4 having the most. ```text player_possession home_4 174 home_5 171 home_2 148 away_7 127 home_9 102 home_7 89 home_3 52 home_1 43 home_11 33 away_5 31 home_8 13 away_2 10 home_10 10 away_8 8 away_9 8 away_10 4 away_6 2 away_11 1 Name: count, dtype: int64 ``` -------------------------------- ### Commented Example and Video Display Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/visualizations_page.ipynb A commented variant of the save_tracking_video example save folder and an IPython Video display to embed the resulting MP4. ```python # from databallpy.visualize import save_tracking_video # heatmap_overlay = game.tracking_data.get_pitch_control( # game.pitch_dimensions, # start_idx=0, # end_idx=100, # ) # save_tracking_video( # game, # start_idx=0, # end_idx=100, # save_folder=os.path.join(os.getcwd(), "..", "static"), # title="Tracking Video Example", # events=["pass"], # variable_of_interest=game.tracking_data.loc[0:100, "frame"], # add_velocities=True, # heatmap_overlay=heatmap_overlay, # overlay_cmap="coolwarm", # verbose=False, # ) from IPython.display import Video Video(os.path.join(os.getcwd(), "../static", "Tracking Video Example.mp4"), embed=True, width=800) ``` -------------------------------- ### Create a git branch for local development Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/quick_overview.md First checkout the development branch, then create a branch named with the issue number, type, and short description. The example shows issue 5 for a feature normalizing playing direction in tracking data. ```console $ git checkout -b -- $ # example for issue 5, a new features that normalizes playing direction in tracking data $ git checkout development $ git checkout -b 5-feat-normalize_playing_direction_td ``` -------------------------------- ### Load game data for synchronization Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/synchronisation_page.ipynb Loads tracking and event data from files or the open game provided by the DFL. Use this to get a game object for synchronization examples. ```python from databallpy import get_game, get_open_game game = get_game( tracking_data_loc="../data/tracking_data.dat", tracking_metadata_loc="../data/tracking_metadata.xml", tracking_data_provider="tracab" event_data_loc="../data/event_data_f24.xml", event_metadata_loc="../data/event_metadata_f7.xml", event_data_provider="opta", ) # or get the open game provided by the DFL (Sportec Solutions) game = get_open_game() ``` -------------------------------- ### Install DataBallPy with pip Source: https://github.com/alek050/databallpy/blob/develop/README.md Install the core DataBallPy package. Optional extras are available for kloppy support and Dangerous Accessible Space. ```bash pip install databallpy ``` -------------------------------- ### Commented-out save_tracking_video example Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb A commented-out version of the save_tracking_video call, likely for reference or to disable execution. ```python # from databallpy.visualize import save_tracking_video # game.tracking_data["player_possession"] = individual_possession # save_tracking_video( # game, # 0, # 500, # os.path.join(os.getcwd(), "../static"), # title="individual_possession", # events=["pass", "dribble", "shot"], # variable_of_interest=individual_possession[:500 + 1], # add_player_possession=True # ) ``` -------------------------------- ### Find Poetry Installation Path (Windows) Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/poetry_deps_manager.md Run this command to locate the Poetry executable path on Windows. The typical output is something like 'C:\Users\YourUserName\AppData\Local\Programs\Python\Python310\Scripts\poetry.exe'. ```bash poetry where ``` -------------------------------- ### Load game and access xT column in pass events Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Retrieve a game using either tracking/event data files or the open game, then print the "xt" column from pass events. Requires the data files or internet access for the open game. Note that this example covers only open play events; other event types have separate xT models. ```python from databallpy import get_game, get_open_game game = get_game( tracking_data_loc="../data/tracking_data.dat", tracking_metadata_loc="../data/tracking_metadata.xml", tracking_data_provider="tracab" event_data_loc="../data/event_data_f24.xml", event_metadata_loc="../data/event_metadata_f7.xml", event_data_provider="opta", ) # or get the open game provided by DFL/Sportec Solutions game = get_open_game() print(game.pass_events["xt"]) ``` -------------------------------- ### Import optimization and visualization modules Source: https://github.com/alek050/databallpy/blob/develop/docs/features/optimization.ipynb Imports required libraries and databallpy modules for the optimization example, including pandas, matplotlib, and the optimization and visualization functions. ```python import pandas as pd import os import matplotlib.pyplot as plt from databallpy import get_saved_game from databallpy.optimization.constraints import TTIConstraint from databallpy.optimization.objectives import ( PressureObjective, WeightedPitchControlObjective, ) from databallpy.optimization.optimization import optimize_tracking_frame from databallpy.optimization.simulated_annealing import SimulatedAnnealing from databallpy.visualize import plot_tracking_data, diff_frames ``` -------------------------------- ### Load saved game and view xT values Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Load a previously saved game using get_saved_game and display the first few xT values from pass events. Requires a saved game directory. The output shows example values from the xt column. ```python from databallpy import get_saved_game import os game = get_saved_game("synced_game", os.path.join("..", "saved_games")) print(game.pass_events["xt"].head()) ``` ```output Output: 0 0.001000 1 0.002746 2 0.002224 3 0.018354 4 0.000831 Name: xt, dtype: float64 ``` -------------------------------- ### Opta Event Data XML Example Source: https://github.com/alek050/databallpy/blob/develop/docs/introduction/intro_event_data_page.md Shows a raw Opta event data XML snippet with an event, its qualifiers, and attributes. The qualifier_id="56" value="Back" indicates a backward pass. This format requires translation of type_id and qualifier_id to be meaningful. ```xml ``` -------------------------------- ### Calculate success move probabilities and xG for free kicks Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Builds a transition matrix of successful ball moves for each starting zone and fills an array with expected goals (xG) values based on free kick parameters. Requires precomputed x_edges, y_edges, free_kicks DataFrame, hist2d_params, xg_params, X_RANGE, get_smallest_angle, and scale_and_predict_logreg. ```python succ_move_probs = np.zeros((N_X_BINS * N_Y_BINS, N_X_BINS * N_Y_BINS)) xg_vals = np.zeros(N_X_BINS * N_Y_BINS) xg_by_free_kick_params = xg_params["xG_by_free_kick"] cell_id = 0 for x_start1, x_start2 in zip(x_edges[:-1], x_edges[1:]): # df of all events that are within the x range start_df_x = free_kicks[((free_kicks["start_x"] >= x_start1) & (free_kicks["start_x"] <= x_start2))] for y_start1, y_start2 in zip(y_edges[:-1], y_edges[1:]): # df of all events that are within the x and the y range start_df = start_df_x[((start_df_x["start_y"] >= y_start1) & (start_df_x["start_y"] <= y_start2))] succ_mask = (~start_df["end_x"].isnull()) & (~start_df["end_y"].isnull()) & (start_df["event"]!="shot") & (start_df["successful"]==1) hist_ball_moves_succ_current_pos, _, _ = np.histogram2d(start_df.loc[succ_mask, "end_x"], start_df.loc[succ_mask, "end_y"], **hist2d_params) if len(start_df) > 0: current_ratio = hist_ball_moves_succ_current_pos / len(start_df) else: current_ratio = np.zeros(hist_ball_moves_succ_current_pos.shape) succ_move_probs[cell_id] = current_ratio.ravel() # Fill xG array loc = np.array([np.mean([x_start1, x_start2]), np.mean([y_start1, y_start2])]) goal_distance = np.sqrt(np.power(X_RANGE[1] - loc[0], 2) + np.power(loc[1], 2)) shot_angle = get_smallest_angle(loc - np.array([X_RANGE[1], 3.63]), loc - np.array([X_RANGE[1], -3.66]), angle_format="degree") xg_vals[cell_id] = scale_and_predict_logreg(np.array([[goal_distance, shot_angle]]), xg_by_free_kick_params)[0] cell_id += 1 ``` -------------------------------- ### Get initial possessions based on proximity and PZ radius Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Determines initial ball possession for each frame by finding the closest player and checking if they are within the possession zone radius. Returns a Series with player IDs or None. ```python def get_initial_possessions( tracking_data: pd.DataFrame, pz_radius: float, distances_df: pd.DataFrame = None, ) -> pd.Series: """ Calculate initial ball possession based on proximity and duration within the possession zone (PZ). Args: tracking_data (pd.DataFrame): Tracking data with player positions. pz_radius (float): Radius of the possession zone in meters. distances_df (pd.DataFrame, optional): DataFrame with distances between the ball and players. Defaults to None. Returns: pd.Series: Player possession status for each frame. """ if not distances_df: distances_df = get_distance_between_ball_and_players(tracking_data).fillna(np.inf) closest_player = distances_df.idxmin(axis=1, skipna=True) close_enough = distances_df.min(axis=1) < pz_radius return np.where(close_enough, closest_player, None) ``` -------------------------------- ### Prepare game data for synchronization Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/synchronisation_page.ipynb Loads a saved game, adds velocity and acceleration to ball tracking data, and modifies event data with custom tackle and pass events. This prepares the data for synchronization examples. ```python import os import numpy as np import pandas as pd from databallpy import get_saved_game from databallpy.schemas import EventData from databallpy.utils.constants import MISSING_INT game = get_saved_game(os.path.join(os.getcwd(), "..", "saved_games", "not_synced_game")) game.tracking_data.add_velocity(["ball"], filter_type="savitzky_golay", window_length=5, polyorder=2) game.tracking_data.add_acceleration(["ball"], filter_type="savitzky_golay", window_length=25, polyorder=2) event_data = game.event_data.iloc[15:25].copy() tackle_dict = { "event_id":2504471412, "type_id":7, "action_type": "tackle", "period_id": 1, "minutes": 0, "seconds": 38, "player_id": game.home_players.loc[game.home_players["shirt_num"]==8, "id"].values[0], "team_id": game.home_team_id, "outcome": MISSING_INT, "start_x": -7.9329, "start_y": 18.2203, "datetime": pd.to_datetime("1980-01-01 15:00:40.110000+00:00"), "original_event": "tackle", "original_id": 17, "player_name": "home_8", } event_data = pd.concat([event_data, EventData([tackle_dict])]) wrong_pass_dict = { "event_id":9999999999, "type_id":7, "action_type": "pass", "period_id": 1, "minutes": 0, "seconds": 32, "player_id": game.away_players.loc[game.home_players["shirt_num"]==1, "id"].values[0], "team_id": game.away_team_id, "outcome": MISSING_INT, "start_x": 35.5699, "start_y": 3.8403, "datetime": pd.to_datetime("1980-01-01 15:00:33.836000+00:00"), "original_event": "pass", "original_id": 999, "player_name": "away_1", } event_data = pd.concat([event_data, EventData([wrong_pass_dict])]) event_data.index = [15, 16, 18, 19, 20, 21, 22, 24, 25, 26, 23, 17] event_data = event_data.sort_index() game.tracking_data = game.tracking_data.loc[600:1100] game.event_data = event_data.copy() game._is_synchronised = True ``` -------------------------------- ### Display tracking video in Jupyter notebook Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/synchronisation_page.ipynb Shows commented-out code for saving a tracking video and displays it as an MP4 embedded in the notebook. Useful for visualizing the short game segment used in the synchronization examples. ```python # save_tracking_video( # game, # 600, # 1100, # os.path.join(os.getcwd(), "..", "static"), # title="tracking_sync" # ) from IPython.display import Video Video(os.path.join(os.getcwd(), "..", "static", "tracking_sync.mp4"), embed=True, width=800) ``` -------------------------------- ### Run tests, linters, and documentation with make ready Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/quick_overview.md For macOS and Linux users, `make ready` runs tests, linters, and documentation in one command. ```console > make ready ``` -------------------------------- ### Build documentation before pull request Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/quick_overview.md Update and run documentation without errors. Use `make documentation` on Linux/macOS or `poetry run jupyter-book build docs/ --all` on Windows. ```console > # for linux and macos > make documentation > # for windows > poetry run jupyter-book build docs/ --all ``` -------------------------------- ### get_start_end_idxs Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Gets the starting and ending indexes of proposed possessions based on initial possession of the ball. Returns a tuple of arrays containing the start and end indexes. ```APIDOC ## get_start_end_idxs ### Description Gets the starting and ending indexes of the proposed possessions based on the initial possession of the ball. The proposed possessions are periods where the possession of the ball changes. ### Method Function Call ### Signature ```python def get_start_end_idxs(pz_initial: np.ndarray) -> tuple[np.ndarray, np.ndarray]: ``` ### Parameters - **pz_initial** (np.ndarray) - Required - The initial possession of the ball. ### Returns - **tuple[np.ndarray, np.ndarray]** - The starting and ending indexes of the proposed possessions. ``` -------------------------------- ### Get pass start locations with different playing directions Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/preprocessing_options.ipynb Loops over the first 70 pass events and extracts the ball start location for each event using 'home_oriented' and 'possession_oriented' playing directions. The team side is stored as a binary flag. ```python import numpy as np pass_start_locs_team = np.zeros((len(synced_game.pass_events), 3)) pass_start_locs_possession = np.zeros((len(synced_game.pass_events), 3)) for i, event in enumerate(synced_game.pass_events.itertuples()): if i >= 70: break frame = synced_game.get_event_frame(event_id=event.event_id, playing_direction="home_oriented") pass_start_locs_team[i, :2] = frame[[f"ball_x", f"ball_y"]].values[0] pass_start_locs_team[i, 2] = int(event.team_side == "home") frame = synced_game.get_event_frame(event_id=event.event_id, playing_direction="possession_oriented") pass_start_locs_possession[i, :2] = frame[[f"ball_x", f"ball_y"]].values[0] pass_start_locs_possession[i, 2] = int(event.team_side == "home") ``` -------------------------------- ### get_start_end_idxs: Get proposed possession intervals Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Finds start and end indexes of proposed possessions where possession changes, excluding periods with None possession. Returns tuple of arrays. ```python def get_start_end_idxs(pz_initial: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Function to get the starting and ending indexes of the proposed possessions based on the initial possession of the ball. The proposed possessions are periods where the possession of the ball changes. Args: pz_initial (np.ndarray): The initial possession of the ball. Returns: tuple[np.ndarray, np.ndarray]: The starting and ending indexes of the proposed possessions. """ shifting_idxs = np.where(pz_initial[:-1] != pz_initial[1:])[0] shifting_idxs = np.concatenate([[-1], shifting_idxs, [len(pz_initial) - 1]]) possession_start_idxs = shifting_idxs[:-1] + 1 possession_end_idxs = shifting_idxs[1:] none_idxs = np.where(pz_initial[possession_start_idxs] == None)[0] possession_start_idxs = np.delete(possession_start_idxs, none_idxs) possession_end_idxs = np.delete(possession_end_idxs, none_idxs) return possession_start_idxs, possession_end_idxs ``` -------------------------------- ### Load a game with tracking and event data Source: https://github.com/alek050/databallpy/blob/develop/docs/introduction/intro_page.md Use `get_game()` to load a game from local files, specifying the tracking and event data providers. Alternatively, use `get_open_game()` to load an open Metrica dataset of tracking and event data. ```python from databallpy import get_game, get_open_game game = get_game( tracking_data_loc="../data/tracking_data.dat", tracking_metadata_loc="../data/tracking_metadata.xml", tracking_data_provider="tracab", event_data_loc="../data/event_data_f24.xml", event_metadata_loc="../data/event_metadata_f7.xml", event_data_provider="opta", ) # or to load an open metrica dataset of tracking and event data game = get_open_game() ``` -------------------------------- ### Run tests before pull request Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/quick_overview.md Run all tests. Use `make test` on Linux/macOS or the `poetry run py.test` command on Windows. The Windows command includes coverage reporting and a coverage configuration file. ```console > # for linux and macos > make test > # for windows > poetry run py.test tests/ --pythonwarnings=once --cov-report=term-missing --cov-report=html --cov=databallpy --cov-config=.coveragerc ``` -------------------------------- ### Calculate covered distance with get_covered_distance Source: https://github.com/alek050/databallpy/blob/develop/docs/features/covered_distance_page.ipynb Use the get_covered_distance method on game.tracking_data to compute the total covered distance for specified players between start and end indices. The example uses game.get_column_ids() for all players and sets the end index to one minute (frame_rate*60). ```python game.tracking_data.get_covered_distance( game.get_column_ids(), start_idx=0, end_idx=game.tracking_data.frame_rate*60 ) ``` -------------------------------- ### Run linters before pull request Source: https://github.com/alek050/databallpy/blob/develop/docs/contributing/quick_overview.md Run all linters. Use `make formatlint` on Linux/macOS or `poetry run ruff format tests/ databallpy` on Windows. ```console > # for linux and macos > make formatlint > # for windows > poetry run ruff format tests/ databallpy ``` -------------------------------- ### Create custom events with events_to_xml() Source: https://github.com/alek050/databallpy/blob/develop/docs/features/video_analysis_xml_export.ipynb Use events_to_xml() with manually constructed Event dicts when events come from tracking data or your own model. Times are in seconds relative to the start of the relevant half, matching SportsCode and Longomatch conventions. The example defines two pressing events with labels and prints the resulting XML string. ```python from databallpy import events_to_xml, Event, LabelDict # Imagine these pressing events were detected from tracking data pressing_events: dict[str, Event] = { "0": Event( id="0", code="Press", start_t=312.0, # seconds from half-start end_t=320.0, labels=[ LabelDict(group="Team", name="Home"), LabelDict(group="Outcome", name="Ball won"), ], ), "1": Event( id="1", code="Press", start_t=874.5, end_t=882.0, labels=[ LabelDict(group="Team", name="Away"), LabelDict(group="Outcome", name="Unsuccessful"), ], ), } xml_str = events_to_xml(pressing_events) print(xml_str) ``` -------------------------------- ### Install accessible-space package Source: https://github.com/alek050/databallpy/blob/develop/docs/features/dangerous_accessible_space.ipynb Install the `accessible-space` package, which is required by `add_dangerous_accessible_space`. Use `databallpy[accessible-space]` to install it with databallpy, or install the package directly with version >=2.0.13. ```bash pip install 'databallpy[accessible-space]' ``` ```bash pip install 'accessible-space>=2.0.13' ``` -------------------------------- ### Game.event_timestamp_is_precise Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Property that checks if the event timestamps are precise. A timestamp is considered precise if the start of the game is not exactly at the start of the initial game time (e.g., 20:00:00) but at the actual start of the game (e.g., 20:00:03.2378). ```APIDOC ## Game.event_timestamp_is_precise ### Description Property that checks if the event timestamps are precise. A timestamp is considered precise if the start of the game is not exactly at the start of the initial game time (e.g., 20:00:00) but at the actual start of the game (e.g., 20:00:03.2378). ### Method @property ### Endpoint Game.event_timestamp_is_precise ### Returns - **bool** - True if the event timestamps are precise, False otherwise. ``` -------------------------------- ### Game.tracking_timestamp_is_precise Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Property that checks if the tracking timestamps are precise. A timestamp is considered precise if the start of the game is not exactly at the start of the initial game time (e.g., 20:00:00) but at the actual start of the game (e.g., 20:00:03.2378). ```APIDOC ## Game.tracking_timestamp_is_precise ### Description Property that checks if the tracking timestamps are precise. A timestamp is considered precise if the start of the game is not exactly at the start of the initial game time (e.g., 20:00:00) but at the actual start of the game (e.g., 20:00:03.2378). ### Method @property ### Endpoint Game.tracking_timestamp_is_precise ### Returns - **bool** - True if the tracking timestamps are precise, False otherwise. ``` -------------------------------- ### Set up matplotlib inline Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Enables inline plotting in Jupyter notebooks. ```python %matplotlib inline ``` -------------------------------- ### Plot pass start locations for home and possession oriented Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/preprocessing_options.ipynb Creates two side-by-side pitch plots comparing pass start locations when oriented by home team versus by possession. The away team's locations are mirrored in the possession-oriented plot. ```python fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5)) fig, ax1 = plot_soccer_pitch(fig=fig, ax=ax1) fig, ax2 = plot_soccer_pitch(fig=fig, ax=ax2) home_mask = pass_start_locs_team[:, 2] == 1 ax1.scatter(pass_start_locs_team[home_mask, 0], pass_start_locs_team[home_mask, 1], c="blue", label="home") ax1.scatter(pass_start_locs_team[~home_mask, 0], pass_start_locs_team[~home_mask, 1], c="red", label="away") ax2.scatter(pass_start_locs_possession[home_mask, 0], pass_start_locs_possession[home_mask, 1], c="blue", label="home") ax2.scatter(pass_start_locs_possession[~home_mask, 0], pass_start_locs_possession[~home_mask, 1], c="red", label="away") ax1.set_title("Home Oriented") ax2.set_title("Possession Oriented") ax1.legend() ax2.legend() fig.tight_layout() plt.show() ``` ```text Result:
``` -------------------------------- ### Game.get_event Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Function to get the event with the given event_id. ```APIDOC ## Game.get_event ### Description Function to get the event with the given event_id. ### Method get_event ### Signature ```python def Game.get_event(self, event_id: int) -> pd.Series ``` ### Parameters - **event_id** (int) - Required - The id of the event to retrieve. ### Returns - **pd.Series** - The event data as a pandas Series. ``` -------------------------------- ### Load game with get_game and get_open_game Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Imports the function to add team possession and loads a game either from local files or the open game provided by DFL/Sportec Solutions. ```python from databallpy import get_game, get_open_game game = get_game( tracking_data_loc="../data/tracking_data.dat", tracking_metadata_loc="../data/tracking_metadata.xml", tracking_data_provider="tracab" event_data_loc="../data/event_data_f24.xml", event_metadata_loc="../data/event_metadata_f7.xml", event_data_provider="opta", ) # or get the open game provided by the DFL/Sportec Solutions game = get_open_game() ``` -------------------------------- ### Game.get_event_frame Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Function to get the frame of the event with the given event_id. ```APIDOC ## Game.get_event_frame ### Description Function to get the frame of the event with the given event_id. ### Method get_event_frame ### Signature ```python def Game.get_event_frame(self, event_id: int | str, playing_direction: str='home_oriented') -> pd.DataFrame ``` ### Parameters - **event_id** (int | str) - Required - The id of the event to retrieve the frame for. - **playing_direction** (str) - Optional - The playing direction, default is 'home_oriented'. ### Returns - **pd.DataFrame** - The frame data as a pandas DataFrame. ``` -------------------------------- ### Game.get_frames Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Function to get the frames of the game with the given frame indexes. ```APIDOC ## Game.get_frames ### Description Function to get the frames of the game with the given frame indexes. ### Method get_frames ### Signature ```python def Game.get_frames(self, frames: int | list[int], playing_direction: str='home_oriented') -> pd.DataFrame ``` ### Parameters - **frames** (int | list[int]) - Required - The frame index or list of frame indexes to retrieve. - **playing_direction** (str) - Optional - The playing direction, default is 'home_oriented'. ### Returns - **pd.DataFrame** - The frames data as a pandas DataFrame. ``` -------------------------------- ### Game.player_id_to_column_id Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Simple function to get the column id based on player id. ```APIDOC ## Game.player_id_to_column_id ### Description Simple function to get the column id based on player id. ### Method player_id_to_column_id ### Signature ```python def Game.player_id_to_column_id(self, player_id: int) -> str ``` ### Parameters - **player_id** (int) - Required - The player id to convert to column id. ### Returns - **str** - The column id corresponding to the player id. ``` -------------------------------- ### Define pitch grid constants Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Sets up the grid dimensions and pitch size used for the xT model. These constants define the number of bins and the pitch boundaries in meters. ```python N_X_BINS = 32 N_Y_BINS = 24 X_RANGE = (-53, 53) Y_RANGE = (-34, 34) PITCH_LENGTH = 106 PITCH_WIDTH = 68 CELL_LENGTH = (X_RANGE[1] - X_RANGE[0]) / N_X_BINS CELL_WIDTH = (Y_RANGE[1] - Y_RANGE[0]) / N_Y_BINS ``` -------------------------------- ### Compute initial possession for a game Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Calls get_initial_possessions with a possession zone radius of 2.5 meters and prints the resulting possession array. The output shows the away team had kickoff and away_6 took it. ```python initial_possession = get_initial_possessions(game.tracking_data, 2.5) print(initial_possession) ``` -------------------------------- ### Game.player_column_id_to_full_name Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/game_api.rst Simple function to get the full name of a player from the column id. ```APIDOC ## Game.player_column_id_to_full_name ### Description Simple function to get the full name of a player from the column id. ### Method Function ### Endpoint Game.player_column_id_to_full_name ### Parameters #### Required Parameters - **column_id** (str) - Required - The column id of the player. ### Returns - **str** - The full name of the player. ``` -------------------------------- ### Output of constant time bias calculation Source: https://github.com/alek050/databallpy/blob/develop/docs/getting_started/synchronisation_page.ipynb Shows the start datetimes and the time difference. ```text Output: Start datetime tracking data: 1980-01-01 15:00:00+00:00 Start datetime event data: 1980-01-01 15:00:01.880000+00:00 Time difference: 0 days 00:00:01.880000 ``` -------------------------------- ### Load and filter positions dataset (with error) Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Loads a local pickle file and filters out own goals and goals scored from own half. This snippet fails because the file 'data/positions_goals_dataset2.pkl' does not exist, producing a FileNotFoundError. ```python df = pd.read_pickle("data/positions_goals_dataset2.pkl") # note this is a local dataset # exclude own goals and goals scored from own half, probably an event data error df = df[df["event"]!="own_goal"] df = df[~((df["event"]=="shot") & (df["successful"]==1) & (df["start_x"] < 0))] df_set_piece = df[df["set_piece"]!="no_set_piece"] df_set_piece["set_piece"].value_counts() ``` ```text Error (truncated): [0;32m--> 882[0m handle [38;5;241m=[39m [38;5;28;43mopen[39;49m[43m([49m[43mhandle[49m[43m,[49m[43m ioargs[49m[38;5;241;43m.[39;49m[43mmode[49m[43m)[39;49m [1;32m 883[0m handles[38;5;241m.[39mappend(handle) [1;32m 885[0m [38;5;66;03m# Convert BytesIO or file objects passed with an encoding[39;00m [0;31mFileNotFoundError[0m: [Errno 2] No such file or directory: 'data/positions_goals_dataset2.pkl' ``` -------------------------------- ### save_tracking_video Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/visualize_api.rst Function to save a subset of a game clip of the tracking data. It requires FFMPEG to be installed on the device. ```APIDOC ## save_tracking_video ### Description Function to save a subset of a game clip of the tracking data. Note that making animation is built with FFMPEG; you need to have FFMPEG installed on your device before being able to use this function. ### Method Function call ### Signature ```python def save_tracking_video(game: Game, start_idx: int, end_idx: int, save_folder: str, *, title: str='test_clip', team_colors: list=['green', 'red'], events: list=[], variable_of_interest: pd.Series | list=None, add_player_possession: bool=False, add_velocities: bool=False, heatmap_overlay: np.ndarray | None=None, overlay_cmap: Colormap | str='viridis', verbose: bool=True) ``` ### Parameters - **game** (Game) - Required - Game with tracking data and other info of the game. - **start_idx** (int) - Required - Start index of what to save of the game.tracking_data df. - **end_idx** (int) - Required - End index of what to save of the game.tracking_data df. - **save_folder** (str) - Required - Location where to save the clip. - **title** (str, optional) - Title of the clip. Defaults to "test_clip". - **team_colors** (list, optional) - Colors of the home and away team. Defaults to ["green", "red"]. - **events** (list, optional) - The SPADL action types (e.g. 'clearance') and/or databallpy events (e.g. 'pass') to plot as well. Defaults to []. - **variable_of_interest** (pd.Series | list, optional) - Variable you want to have plotted in the clip, this is a pd.Series that should have the same index (start_idx:end_idx) as the tracking data that will be plotted. Defaults to None. - **add_player_possession** (bool, optional) - Whether to add a mark around which player has possession over the ball. Defaults to False. If True, the column 'player_possession' should be in the game.tracking_data. - **add_velocities** (bool, optional) - Whether or not to add the velocities to the clip, will add arrows to show the velocity. Defaults to False. - **heatmap_overlay** (np.ndarray, optional) - A heatmap to overlay on the pitch. Defaults to None. - **overlay_cmap** (Colormap | str, optional) - The colormap to use for the heatmap overlay. Defaults to "viridis". - **verbose** (bool, optional) - Whether or not to print info in the terminal on the progress. Defaults to True. ### Response No return value documented. ``` -------------------------------- ### Define get_xG and calculate_success_move_probabilities functions Source: https://github.com/alek050/databallpy/blob/develop/docs/features/xt_models.ipynb Defines two functions: get_xG calculates the expected goal value for a location using the loaded parameters, and calculate_success_move_probabilities computes the success move probabilities for a cell. The code then initializes grids and loops over all cells to fill them. ```python # get your own xg params or use the one in databallpy in models/xg_params.json def get_xG(loc: np.ndarray, xg_params: dict=xg_params) -> float: """ Calculate the expected goal (xG) value for a given location. Args: loc (np.ndarray): The location on the pitch as a numpy array [x, y]. xg_params (Dict[str]): The parameters for the xG model. Returns: float: The xG value. """ goal_distance = np.sqrt(np.power(X_RANGE[1] - loc[0], 2) + np.power(loc[1], 2)) shot_angle = get_smallest_angle(loc - np.array([X_RANGE[1], 3.63]), loc - np.array([X_RANGE[1], -3.66]), angle_format="degree") return scale_and_predict_logreg(np.array([[goal_distance, shot_angle]]), xg_params["xg_by_foot"])[0] def calculate_success_move_probabilities(df: pd.DataFrame, x_start: float, x_end: float, y_start: float, y_end: float, params: dict=hist2d_params) -> np.ndarray: """ Calculate the success move probabilities for events within a specified cell on the pitch. This function filters events based on their starting position, checks if the move was successful, and calculates the success probability for moving the ball into different areas of the pitch from the specified cell. Args: df: A pandas DataFrame containing event data. x_start: The starting x-coordinate of the cell. x_end: The ending x-coordinate of the cell. y_start: The starting y-coordinate of the cell. y_end: The ending y-coordinate of the cell. params: Parameters for the numpy histogram2d function. Returns: A flattened numpy array containing the success move probabilities for the specified cell. """ filtered_df = df[(df["start_x"] >= x_start) & (df["start_x"] <= x_end) & (df["start_y"] >= y_start) & (df["start_y"] <= y_end)] succ_mask = ( (~filtered_df["end_x"].isnull()) & (~filtered_df["end_y"].isnull()) & (filtered_df["event"] != "shot") & (filtered_df["successful"] == 1) ) hist_ball_moves_succ, _, _ = np.histogram2d( filtered_df.loc[succ_mask, "end_x"], filtered_df.loc[succ_mask, "end_y"], **params ) current_ratio = hist_ball_moves_succ / len(filtered_df) if len(filtered_df) > 0 else np.zeros_like(hist_ball_moves_succ) return current_ratio.ravel() # Initialize empty grids succ_move_probs = np.zeros((N_X_BINS * N_Y_BINS, N_X_BINS * N_Y_BINS)) xg_vals = np.zeros(N_X_BINS * N_Y_BINS) cell_id = 0 for x_start, x_end in zip(x_edges[:-1], x_edges[1:]): for y_start, y_end in zip(y_edges[:-1], y_edges[1:]): # Calculate the success move probabilities for the current cell succ_move_probs[cell_id] = calculate_success_move_probabilities(df, x_start, x_end, y_start, y_end, hist2d_params) # Calculate the expected goal value for the current cell mean_loc = np.array([np.mean([x_start, x_end]), np.mean([y_start, y_end])]) xg_vals[cell_id] = get_xG(mean_loc) cell_id += 1 ``` -------------------------------- ### convert_kloppy_event_dataset Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/dataparsers_api.rst Converts a Kloppy event dataset into an EventData object. This function is used to get all event information of a game from a Kloppy dataset. ```APIDOC ## convert_kloppy_event_dataset ### Description Converts a Kloppy event dataset into an EventData object. This function is used to get all event information of a game from a Kloppy dataset. ### Method Function call ### Endpoint `databallpy.data_parsers.kloppy_parsers.convert_kloppy_event_dataset` ### Parameters - **event_dataset** (kloppy.domain.EventDataset, optional) - Required - A Kloppy event dataset. - **periods** (pd.DataFrame) - Required - DataFrame containing information about the periods ### Returns - **EventData** - All event data in an EventData object ``` -------------------------------- ### convert_kloppy_tracking_dataset Source: https://github.com/alek050/databallpy/blob/develop/docs/api_docs/dataparsers_api.rst Converts a Kloppy tracking dataset into a TrackingData object. This function is used to get all tracking information of a game from a Kloppy dataset. ```APIDOC ## convert_kloppy_tracking_dataset ### Description Converts a Kloppy tracking dataset into a TrackingData object. This function is used to get all tracking information of a game from a Kloppy dataset. ### Method Function call ### Endpoint `databallpy.data_parsers.kloppy_parsers.convert_kloppy_tracking_dataset` ### Parameters - **tracking_dataset** (kloppy.domain.TrackingDataset, optional) - Required - A Kloppy tracking dataset. - **periods** (pd.DataFrame) - Required - DataFrame containing information about the periods ### Returns - **TrackingData** - All tracking data in a TrackingData object ``` -------------------------------- ### Access add_individual_player_possession method Source: https://github.com/alek050/databallpy/blob/develop/docs/features/team_and_player_possession.ipynb Shows how to access the add_individual_player_possession method on the tracking data object. ```python game.tracking_data.add_individual_player_possession ```