File size: 2,667 Bytes
27fe184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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)
    # 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]
        ball_angle = df_arm_angle.filter(pl.col("pitcher") == pitcher_id)["ball_angle"][0]

        print(shoulder_x, shoulder_z)

        df_filter = (df_filter.with_columns(

            )
            .with_columns(
                (pl.col("release_pos_z") - shoulder_z).alias("Opp"),
                (pl.col("release_pos_x") - shoulder_x).alias("Adj"),
            )
            .with_columns(
                pl.struct(["Opp", "Adj"]).map_elements(lambda x: np.arctan2(x["Opp"], x["Adj"])).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.25) + (ball_angle * 0.75)).alias("arm_angle")
            )
    


    
    return df_filter