""" Soccer Feature Engineering Pipeline - Competition Version =========================================================== Engineers 33 match-level, team-level features from SkillCorner dynamic_events.csv. Based on the Kaggle Soccer Feature Engineering Hackathon requirements. This script uses the EXACT column naming convention from the reference notebook by Dev0907 to ensure full compatibility with competition evaluation. Input: SkillCorner opendata repository (or any folder with *_dynamic_events.csv) Output: features.csv - one row per team per match """ import glob import os import pandas as pd def discover_dynamic_events_files(data_root="/app/opendata/data/matches"): """Dynamically discover all *_dynamic_events.csv files via glob.""" pattern = os.path.join(data_root, "**", "*_dynamic_events.csv") files = glob.glob(pattern, recursive=True) files.sort() return files def compute_team_features(df, team): """ Compute 33 aggregated match-level features for a single team in a single match. Uses EXACT column names from the reference notebook by Dev0907. """ match_id = df["match_id"].iloc[0] team_df = df[df["team_id"] == team] poss = team_df[team_df["event_type"] == "player_possession"] obe = team_df[team_df["event_type"] == "on_ball_engagement"] obr = team_df[team_df["event_type"] == "off_ball_run"] passes = poss[poss["pass_outcome"].notna()] # DIMENSION 1: ATTACKING STRUCTURE att1 = int((passes["third_end"] == "attacking_third").sum()) carries = poss[poss["carry"] == True] att2 = int((carries["third_end"] == "attacking_third").sum()) att3 = int(passes["n_opponents_bypassed"].clip(lower=0).sum()) att4 = int(passes["last_line_break"].sum()) if "last_line_break" in passes.columns else 0 att5 = int((passes["third_start"] == "attacking_third").sum()) # DIMENSION 2: BUILD-UP PROFILE att6 = int((poss["team_in_possession_phase_type"] == "build_up").sum()) att7 = int((poss["team_in_possession_phase_type"] == "direct").sum()) att8 = int((poss["team_in_possession_phase_type"] == "set_play").sum()) att9 = int((poss["team_in_possession_phase_type"] == "quick_break").sum()) att10 = int((poss["team_in_possession_phase_type"] == "transition").sum()) # DIMENSION 3: POSSESSION QUALITY att11 = int(poss["one_touch"].sum()) att12 = int(poss["quick_pass"].sum()) att13 = int(poss["lead_to_shot"].sum()) att14 = int(poss["lead_to_goal"].sum()) att15 = float(round(poss["delta_to_last_defensive_line_gain"].clip(lower=0).sum(), 2)) att16 = float(round(poss["last_defensive_line_height_gain"].clip(lower=0).sum(), 2)) att17 = int(poss["forward_momentum"].sum()) att18 = int(poss["n_passing_options"].sum()) att19 = int(poss["n_passing_options_dangerous_difficult"].sum()) att20 = int((obr["event_subtype"] == "run_ahead_of_the_ball").sum()) # DIMENSION 4: PRESSING & DEFENSIVE SHAPE def1 = int(len(obe)) def2 = int((obe["event_subtype"] == "counter_press").sum()) def3 = int((obe["event_subtype"] == "recovery_press").sum()) chains = obe[obe["pressing_chain_length"].notna()] chain_starts = chains[chains["index_in_pressing_chain"] == 1.0] def4 = int(chain_starts["pressing_chain_length"].sum()) def5 = int(len(chain_starts)) def6 = int(chains["pressing_chain_length"].max()) if len(chains) > 0 else 0 def7 = int(obe["stop_possession_danger"].sum()) # DIMENSION 5: OFF-BALL MOVEMENT INTELLIGENCE run1 = int(obr["break_defensive_line"].sum()) run2 = int(obr["push_defensive_line"].sum()) run3 = int((obr["event_subtype"] == "behind").sum()) run4 = int((obr["event_subtype"] == "overlap").sum()) run5 = int((obr["third_start"] == "attacking_third").sum()) gng = int(poss["initiate_give_and_go"].sum()) if "initiate_give_and_go" in poss.columns else 0 return { "match_id": match_id, "team_id": team, # Attacking Structure "att1_passes_into_final_third": att1, "att2_carries_into_attacking_third": att2, "att3_opponents_bypassed_by_passes": att3, "att4_last_line_break_passes": att4, "att5_passes_in_attacking_third": att5, # Build-Up Profile "att6_buildup_phase_events": att6, "att7_direct_phase_events": att7, "att8_setplay_events": att8, "att9_quickbreak_events": att9, "att10_transition_events": att10, # Possession Quality "att11_one_touch_passes": att11, "att12_quick_passes": att12, "att13_possessions_leading_to_shot": att13, "att14_possessions_leading_to_goal": att14, "att15_def_line_depth_total_pushed_m": att15, "att16_def_line_height_total_pushed_m": att16, "att17_forward_momentum_possessions": att17, "att18_passing_options_total": att18, "att19_dangerous_difficult_pass_options": att19, "att20_runs_ahead_of_ball": att20, # Defensive Pressing "def1_total_defensive_engagements": def1, "def2_counter_press_actions": def2, "def3_recovery_press_actions": def3, "def4_pressing_chain_total_length": def4, "def5_pressing_chains_initiated": def5, "def6_max_pressing_chain_length": def6, "def7_danger_stopped": def7, # Off-Ball Movement "run1_line_breaking_runs": run1, "run2_line_pushing_runs": run2, "run3_runs_behind_defense": run3, "run4_overlap_runs": run4, "run5_attacking_third_runs": run5, "att_give_and_go_initiated": gng, } def run_pipeline(data_root="/app/opendata/data/matches", output_path="/app/features.csv"): files = discover_dynamic_events_files(data_root) print(f"Discovered {len(files)} dynamic_events.csv files") records = [] for f in files: try: df = pd.read_csv(f, low_memory=False) match_id = df["match_id"].iloc[0] teams = sorted(df["team_id"].unique().tolist()) for team in teams: features = compute_team_features(df, team) records.append(features) print(f" match {match_id}: {len(teams)} teams") except Exception as e: print(f" ERROR {os.path.basename(f)}: {e}") if not records: raise ValueError("No valid match files processed.") features_df = pd.DataFrame(records) # Ensure exact column order as in reference notebook col_order = [ "match_id", "team_id", "att1_passes_into_final_third", "att2_carries_into_attacking_third", "att3_opponents_bypassed_by_passes", "att4_last_line_break_passes", "att5_passes_in_attacking_third", "att6_buildup_phase_events", "att7_direct_phase_events", "att8_setplay_events", "att9_quickbreak_events", "att10_transition_events", "att11_one_touch_passes", "att12_quick_passes", "att13_possessions_leading_to_shot", "att14_possessions_leading_to_goal", "att15_def_line_depth_total_pushed_m", "att16_def_line_height_total_pushed_m", "att17_forward_momentum_possessions", "att18_passing_options_total", "att19_dangerous_difficult_pass_options", "att20_runs_ahead_of_ball", "def1_total_defensive_engagements", "def2_counter_press_actions", "def3_recovery_press_actions", "def4_pressing_chain_total_length", "def5_pressing_chains_initiated", "def6_max_pressing_chain_length", "def7_danger_stopped", "run1_line_breaking_runs", "run2_line_pushing_runs", "run3_runs_behind_defense", "run4_overlap_runs", "run5_attacking_third_runs", "att_give_and_go_initiated", ] features_df = features_df[col_order] features_df.to_csv(output_path, index=False) print(f"\nWrote {len(features_df)} rows x {len(features_df.columns)} columns to {output_path}") print(f"Shape: {features_df.shape}") return features_df if __name__ == "__main__": run_pipeline()