Spaces:
Running on T4
Running on T4
Download data_ref/scripts/compute_contract_v1_1_benchmarks.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.54 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/data_ref/scripts/compute_contract_v1_1_benchmarks.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/data_ref/scripts/compute_contract_v1_1_benchmarks.py
-
curl -L -o compute_contract_v1_1_benchmarks.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/data_ref/scripts/compute_contract_v1_1_benchmarks.py
5.54 kB
| """Generate matching 3D reference intervals for the six additional coach metrics. | |
| Run from the repository root with landmarks.csv, metadata.csv and an output directory. | |
| Uses OBP dataset-v1 (360 Hz), first force-plate touch (fp_10_time), the existing | |
| v1 stride-start rule, and the first 100 ms after contact. Athlete medians, then | |
| population percentiles, avoid giving prolific athletes disproportionate weight. | |
| The intervals describe this laboratory population; they are not ideal targets. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from baseball_batting.coach_geometry import ( | |
| EXTENDED_METRICS, follow_through_frame, inclination, knee_angle, rotation_amount, | |
| ) | |
| def compute(landmarks, metadata): | |
| joints = ('left_hip', 'right_hip', 'lsjc', 'rsjc', 'lkjc', 'rkjc', 'lajc', 'rajc') | |
| columns = ['session_swing', 'time', 'fp_10_time', 'contact_time'] | |
| columns += [f'{j}_{axis}' for j in joints for axis in 'xyz'] | |
| data = pd.read_csv(landmarks, usecols=columns) | |
| meta = pd.read_csv(metadata).set_index('session_swing') | |
| levels = {'high_school': 'high_school', 'college': 'college', 'independent': 'pro', 'milb': 'pro'} | |
| rows = [] | |
| for swing, g in data.groupby('session_swing', sort=False): | |
| if swing not in meta.index: | |
| continue | |
| g = g.sort_values('time'); m = meta.loc[swing]; t = g.time.to_numpy() | |
| fd, ct = g.fp_10_time.iloc[0], g.contact_time.iloc[0] | |
| if not np.isfinite([fd, ct]).all() or fd >= ct: | |
| continue | |
| landing, contact = (int(np.argmin(abs(t - v))) for v in (fd, ct)) | |
| if landing >= contact: | |
| continue | |
| p = {j: g[[f'{j}_{axis}' for axis in 'xyz']].rolling(5, center=True, min_periods=1).mean().to_numpy() | |
| for j in joints} | |
| lead = 'l' if m.hitter_side == 'R' else 'r' | |
| speed = np.linalg.norm(np.gradient(p[lead + 'ajc'][:, :2], t, axis=0), axis=1) | |
| need = max(1, round(.1 / np.median(np.diff(t)))) | |
| start = None; run = 0 | |
| for i in range(landing, -1, -1): | |
| run = run + 1 if speed[i] < .15 else 0 | |
| if run >= need: | |
| start = i + need - 1 | |
| break | |
| h = p['right_hip'] - p['left_hip']; s = p['rsjc'] - p['lsjc'] | |
| hip_heading = np.degrees(np.arctan2(h[:, 1], h[:, 0])) | |
| shoulder_heading = np.degrees(np.arctan2(s[:, 1], s[:, 0])) | |
| separation = (shoulder_heading - hip_heading + 180) % 360 - 180 | |
| lean = inclination((p['left_hip'] + p['right_hip']) / 2, (p['lsjc'] + p['rsjc']) / 2, [0, 0, 1]) | |
| knee = knee_angle(p['left_hip' if lead == 'l' else 'right_hip'], p[lead + 'kjc'], p[lead + 'ajc']) | |
| finish = follow_through_frame(t, contact, len(t) - 1) | |
| rows.append({ | |
| 'session_swing': swing, 'user': m.user, 'level': levels.get(m.highest_playing_level), | |
| 'batting_hand': 'right' if m.hitter_side == 'R' else 'left', | |
| 'torso_inclination_at_stride_start': lean[start] if start is not None else np.nan, | |
| 'hip_shoulder_separation_at_stride_start': separation[start] if start is not None else np.nan, | |
| 'pelvis_rotation_to_contact': rotation_amount(hip_heading, landing, contact), | |
| 'lead_knee_extension_to_contact': knee[contact] - knee[landing], | |
| 'torso_inclination_at_contact': lean[contact], | |
| 'shoulder_rotation_after_contact': rotation_amount(shoulder_heading, contact, finish), | |
| }) | |
| return pd.DataFrame(rows) | |
| def aggregates(rows): | |
| result = {} | |
| for metric in EXTENDED_METRICS: | |
| result[metric] = {} | |
| for hand in ('right', 'left'): | |
| for level in ('high_school', 'college', 'pro'): | |
| group = rows[(rows.batting_hand == hand) & (rows.level == level)] | |
| values = group.groupby('user')[metric].median().dropna() | |
| cell = {'n_athletes': len(values), 'n_swings': int(group[metric].notna().sum())} | |
| if len(values) >= 5: | |
| cell.update({f'p{p}': round(float(np.percentile(values, p)), 3) for p in (10, 25, 50, 75, 90)}) | |
| result[metric][f'{hand}/{level}'] = cell | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('landmarks', type=Path); parser.add_argument('metadata', type=Path) | |
| parser.add_argument('output', type=Path) | |
| args = parser.parse_args(); args.output.mkdir(parents=True, exist_ok=True) | |
| rows = compute(args.landmarks, args.metadata) | |
| result = {'source': 'OpenBiomechanics dataset-v1; hitting_landmarks.zip', | |
| 'source_url': 'https://github.com/drivelineresearch/openbiomechanics/releases/tag/dataset-v1', | |
| 'landmarks_sha256': hashlib.sha256(args.landmarks.read_bytes()).hexdigest(), | |
| 'metadata_sha256': hashlib.sha256(args.metadata.read_bytes()).hexdigest(), | |
| 'n_swings': len(rows), 'n_athletes': int(rows.user.nunique()), | |
| 'definition_version': '1.1', 'follow_through_seconds': .1, | |
| 'limitations': 'Laboratory reference intervals, not ideal technique or validated phone-video accuracy.', | |
| 'metrics': aggregates(rows)} | |
| (args.output / 'contract_v1_1_benchmarks.json').write_text(json.dumps(result, indent=2) + '\n') | |
| rows.to_csv(args.output / 'contract_v1_1_swings.csv', index=False) | |
| print(json.dumps({k: result[k] for k in ('n_swings', 'n_athletes', 'landmarks_sha256')})) | |
| if __name__ == '__main__': | |
| main() | |