Spaces:
Sleeping
Sleeping
| import polars as pl | |
| import numpy as np | |
| import requests | |
| def calculate_arm_angles(df: pl.DataFrame,pitcher_id:int) -> pl.DataFrame: | |
| df_arm_angle = pl.read_csv('stuff_model/pitcher_arm_angles_2024.csv') | |
| #pitcher_id = 489446 | |
| df_filter = df.filter(pl.col("pitcher_id") == pitcher_id).drop_nulls(subset=["release_pos_x", "release_pos_z"]) | |
| # data = requests.get(f'https://statsapi.mlb.com/api/v1/people?personIds={pitcher_id}').json() | |
| if pitcher_id not in df_arm_angle["pitcher"]: | |
| data = requests.get(f'https://statsapi.mlb.com/api/v1/people?personIds={pitcher_id}').json() | |
| height_in = data['people'][0]['height'] | |
| height = int(height_in.split("'")[0]) * 12 + int(height_in.split("'")[1].split('"')[0]) | |
| df_filter = (df_filter.with_columns( | |
| (pl.col("release_pos_x") * 12).alias("release_pos_x"), | |
| (pl.col("release_pos_z") * 12).alias("release_pos_z"), | |
| (pl.lit(height * 0.70)).alias("shoulder_pos"), | |
| ) | |
| .with_columns( | |
| (pl.col("release_pos_z") - pl.col("shoulder_pos")).alias("Opp"), | |
| pl.col("release_pos_x").abs().alias("Adj"), | |
| ) | |
| .with_columns( | |
| pl.struct(["Opp", "Adj"]).map_elements(lambda x: np.arctan2(x["Opp"], x["Adj"])).alias("arm_angle_rad") | |
| )) | |
| df_filter = (df_filter.with_columns( | |
| pl.col("arm_angle_rad").degrees().alias("arm_angle") | |
| #.drop(["Opp", "arm_angle_rad"]) | |
| )) | |
| else: | |
| shoulder_x = df_arm_angle.filter(pl.col("pitcher") == pitcher_id)["relative_shoulder_x"][0] | |
| shoulder_z = df_arm_angle.filter(pl.col("pitcher") == pitcher_id)["shoulder_z"][0] | |
| rel_x = df_arm_angle.filter(pl.col("pitcher") == pitcher_id)["relative_release_ball_x"][0] | |
| rel_z = df_arm_angle.filter(pl.col("pitcher") == pitcher_id)["release_ball_z"][0] | |
| ball_angle = df_arm_angle.filter(pl.col("pitcher") == pitcher_id)["ball_angle"][0] | |
| hyp = np.sqrt((rel_x - shoulder_x)**2 + (rel_z - shoulder_z)**2) | |
| print(shoulder_x, shoulder_z) | |
| df_filter = (df_filter.with_columns( | |
| ) | |
| .with_columns( | |
| (pl.col("release_pos_z") - shoulder_z).alias("Opp"), | |
| (pl.lit(hyp)).alias("Hyp"), | |
| ) | |
| .with_columns( | |
| pl.struct(["Opp","Hyp"]).map_elements(lambda x: np.arcsin(x["Opp"] / x["Hyp"])).alias("arm_angle_rad") | |
| ) | |
| .with_columns( | |
| pl.col("arm_angle_rad").degrees().alias("arm_angle") | |
| ) | |
| #.drop(["Opp", "arm_angle_rad"]) | |
| ) | |
| df_filter = df_filter.with_columns( | |
| ((pl.col("arm_angle") * 0.5) + (ball_angle * 0.5)).alias("arm_angle") | |
| ) | |
| return df_filter |