<jupyter_start><jupyter_text>Fast BreakWe want to engineer the feature that considers if a fast break is happening?If a fast break is happening, we expect the XG will increase. What hueristic are we using to determine a fast break?  A fast break is started when a ball is stolen then the ball ends up in the opponents final 3rd. We can look at speed of players and ball. For now, if the ball is stolen and put near the opponents goal that is a fast break.<jupyter_code># Add this so we can import our haxml code from outside the notebooks folder.
import sys
sys.path.append("../")

from haxml.prediction import (
    generate_rows_demo
)
from haxml.utils import (
    load_match,
    inflate_match,
    get_stadiums,
    get_matches_metadata,
    to_clock,
    train_test_split_matches_even_count
)
from haxml.viz import (
    plot_stadium,
    zoom_stadium,
    plot_positions
)
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import json
import pandas as pd
from tqdm import tqdm

# should move this to a haxml library i.e utils
def make_df(metadata, callback, progress=False):
    """
    Transforms match metadata into a DataFrame of records for
    each kick, including target label and features.
    Args:
        metadata: Match metadata (list of dicts).
        callback: Method to run on each match to extract kicks.
        progress: Whether or not to show progress bar (boolean).
    Returns:
        DataFrame where each row is a kick record.
    """
    rows = []
    bar = tqdm(metadata) if progress else metadata
    for meta in bar:
        key = meta["match_id"]
        infile = "../data/packed_matches/{}.json".format(key)
        try:
            s = stadiums[meta["stadium"]]
            row_gen = load_match(infile, lambda m: callback(m, s))
            for row in row_gen:
                row["match"] = key
                rows.append(row)
        except FileNotFoundError:
            pass
    return pd.DataFrame(rows)
stadiums = get_stadiums("../data/stadiums.json")
metadata = get_matches_metadata("../data/matches_metadata.csv")
meta = metadata[321]
key = meta["match_id"]
infile = "../data/packed_matches/{}.json".format(key)
stadium = stadiums[meta["stadium"]]
match = load_match(infile)
row_gen = generate_rows_demo(match, stadium)
df = pd.DataFrame(row_gen)
df["match"] = key
def isFastBreak(kick):
    '''
    Takes in a kick and where it ends up 
    '''
    travel_dist = ((kick['fromX'] - kick['toX'])**2 + (kick['fromY'] - kick['toY'])**2)**(1/2)
    if travel_dist > 200 and kick['type'] == "steal":
        return True
    return False
# can probably find a way to write less code
def get_defender_features(match):
    """
    Args:
        match: index for match within metadata
    Returns:
        Return a df containing new features for fast break
        fast break hueristic: steal and ball travels more than 300 dist
    """
    meta = get_matches_metadata("../data/matches_metadata.csv")[match]
    stadiums = get_stadiums("../data/stadiums.json")
    infile = "../data/packed_matches/{}.json".format(meta["match_id"])
    stadium = stadiums[meta["stadium"]]
    match = load_match(infile)
    row_gen = generate_rows_demo(match, stadium)
    df = pd.DataFrame(row_gen)
    kick_df = pd.DataFrame(match["kicks"]).to_dict(orient="records")
    is_fastBreak = []
    for kick in kick_df:
        is_fastBreak.append(isFastBreak(kick))
    df["FastBreak"] = is_fastBreak
    return df
new_df = get_defender_features(543)
new_df.head(20)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10079275198187995, 'fraction_numerical': 0.005379388448471121, 'mean_word_length': 3.246394230769231, 'pattern_counts': {'":': 1, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 5}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '200366', 'license': 'MIT', 'n_tokens_mistral': 1099, 'n_tokens_neox': 1073, 'n_words': 353, 'path': 'notebooks/edwin_fast-break2.ipynb', 'repo_name': 'vingkan/haxml', 'size': '3532'}