Spaces:
Running on T4
Running on T4
File size: 9,280 Bytes
35e80ff | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | """Validation, per-level statistics, yaw sensitivity, comparison to app ranges.
Usage (python -I): analyze_pitching.py PITCH_METRICS_CSV RANGES_YAML OUT_DIR
Writes OUT_DIR/pitching_ranges.yaml and OUT_DIR/_tables.json (consumed by write_report.py).
"""
import json
import sys
import numpy as np
import pandas as pd
import yaml
METRICS = ['stride_pct_height', 'lead_knee_flexion_fp_deg', 'lead_knee_flexion_release_deg', 'lead_knee_block_deg',
'trunk_forward_tilt_release_deg', 'trunk_lateral_tilt_release_deg', 'arm_slot_deg', 'leg_lift_to_fp_ms',
'fp_to_release_ms', 'head_stability_pct_height', 'hip_shoulder_sep_fp']
EXTRA = ['head_net_displacement_pct_height', 'head_vertical_range_pct_height']
LEVELS = ['high_school', 'college', 'independent', 'milb', 'all']
PCTS = [5, 10, 25, 50, 75, 90, 95]
def qc(d):
ok = (d.fp_to_release_ms.between(30, 400)) & (d.leg_lift_to_fp_ms >= 200)
return ok
def athlete_stats(df, m):
med = df.groupby(['user', 'playing_level'])[m].median().reset_index()
return med
def stats(df, m, level):
sub = df if level == 'all' else df[df.playing_level == level]
med = sub.groupby('user')[m].median().dropna()
if len(med) == 0:
return None
v = med.values
out = dict(n_athletes=int(len(v)), n_trials=int(sub[m].notna().sum()))
for p in PCTS:
out[f'p{p}'] = float(np.percentile(v, p))
out['mean'] = float(v.mean())
out['sd'] = float(v.std(ddof=1)) if len(v) > 1 else None
return out
def corr(a, b):
ok = a.notna() & b.notna()
return float(np.corrcoef(a[ok], b[ok])[0, 1]), float((a[ok] - b[ok]).mean()), float((a[ok] - b[ok]).std()), int(ok.sum())
def main(csv, ranges_yaml, outdir):
d = pd.read_csv(csv)
base_all = d[(d.yaw_deg == 0) & (d.tilt_deg == 0)]
bad = base_all[~qc(base_all)].session_pitch.unique()
d = d[~d.session_pitch.isin(bad)]
base = d[(d.yaw_deg == 0) & (d.tilt_deg == 0)].copy()
res = dict(n_pitches_total=int(len(base_all)), n_pitches_excluded_event_qc=int(len(bad)),
excluded=list(map(str, bad)), n_pitches_used=int(len(base)))
# ---- validation
val = {}
a = base.stride_pct_height / 100
val['stride_vs_obp_stride_length'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(a, base.stride_length)))
val['trunk_fwd_vs_torso_anterior_tilt_br'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(base.trunk_forward_tilt_release_deg, base.torso_anterior_tilt_br)))
val['arm_slot_vs_obp_arm_slot'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(base.arm_slot_deg, base.arm_slot)))
val['lead_knee_block_vs_obp_extension_fp_to_br'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(base.lead_knee_block_deg, base.lead_knee_extension_from_fp_to_br)))
val['hip_shoulder_sep_2d_vs_obp_3d_fp'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(base.hip_shoulder_sep_fp, base.rotation_hip_shoulder_separation_fp)))
val['trunk_lateral_2d_vs_obp_torso_lateral_tilt_br'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(base.trunk_lateral_tilt_release_deg, base.torso_lateral_tilt_br)))
# per-athlete-median level agreement for stride and trunk
val['leg_lift_to_fp_ms_own_peak_vs_obp_pkh'] = dict(zip(['r', 'mean_diff', 'sd_diff', 'n'], corr(base.leg_lift_to_fp_ms, base.leg_lift_to_fp_ms_obp_pkh)))
res['validation'] = val
# ---- stats
allm = METRICS + EXTRA
S = {m: {lv: stats(base, m, lv) for lv in LEVELS} for m in allm}
# ---- sensitivity (per-athlete-median distribution, all levels pooled + college only)
sens = {}
cfgs = [(10, 0), (-10, 0), (20, 0), (-20, 0), (0, 3)]
for m in allm:
sens[m] = {}
for scope in ['all', 'college']:
def dist(yaw, tilt):
x = d[(d.yaw_deg == yaw) & (d.tilt_deg == tilt)]
if scope == 'college':
x = x[x.playing_level == 'college']
return x.groupby('user')[m].median()
b = dist(0, 0)
ref = (b.median(), np.percentile(b, 10), np.percentile(b, 90))
sens[m][scope] = {}
for yaw, tilt in cfgs:
z = dist(yaw, tilt)
# per-athlete paired shift as well
paired = (z - b).dropna()
sens[m][scope][f'yaw{yaw}_tilt{tilt}'] = dict(
median_shift=float(z.median() - ref[0]),
p10_shift=float(np.percentile(z, 10) - ref[1]),
p90_shift=float(np.percentile(z, 90) - ref[2]),
band_width_change=float((np.percentile(z, 90) - np.percentile(z, 10)) - (ref[2] - ref[1])),
paired_athlete_shift_mean=float(paired.mean()),
paired_athlete_shift_sd=float(paired.std()),
paired_abs_p95=float(np.percentile(paired.abs(), 95)))
res['sensitivity'] = sens
# ---- compare with app ranges
app = yaml.safe_load(open(ranges_yaml))['pitching']
cur = {}
for m in METRICS:
lv = (app.get(m) or {}).get('levels')
cur[m] = {k: (list(v) if v else None) for k, v in lv.items()} if lv else None
res['current'] = cur
# ---- build yaml
out = {}
for m in METRICS:
yaw10 = max(abs(sens[m]['all']['yaw10_tilt0']['median_shift']), abs(sens[m]['all']['yaw-10_tilt0']['median_shift']))
yaw10_p = max(max(abs(sens[m]['all'][k]['p10_shift']), abs(sens[m]['all'][k]['p90_shift'])) for k in ['yaw10_tilt0', 'yaw-10_tilt0'])
band_sd = S[m]['all']['sd']
entry = {}
for lv in LEVELS:
s = S[m][lv]
if s is None:
continue
n = s['n_athletes']
pooled = S[m]['all']
src = s
fallback = False
if n < 20:
src = pooled
fallback = True
lo, hi = src['p10'], src['p90']
# widen by the yaw-10 shift when material (>= 10% of the band)
wid = hi - lo
widen = yaw10_p if yaw10_p >= 0.10 * wid else 0.0
prop = [round(lo - widen, 1), round(hi + widen, 1)]
# app level key
cb = None
if cur[m]:
key = {'college': 'college', 'high_school': 'hs_varsity'}.get(lv)
cb = cur[m].get(key) if key else None
if m in ('trunk_lateral_tilt_release_deg', 'hip_shoulder_sep_fp'):
conf = 'low'
why = '2D image-plane value is dominated by depth foreshortening / yaw; reference only'
elif m == 'head_stability_pct_height':
conf = 'low'
why = 'OBP has no head marker (thorax_prox used) and the metric includes whole-body forward travel; definition must be aligned with the app'
elif m == 'arm_slot_deg':
conf = 'low' if n < 20 else 'medium'
why = 'arm slot is a frontal-plane quantity; side-view projection is highly yaw dependent'
if yaw10 > 5:
conf = 'low'
elif fallback:
conf = 'low'
why = f'n_athletes={n} too small; band taken from pooled all-levels distribution'
elif lv in ('independent', 'milb'):
conf = 'low'
why = f'n_athletes={n}; pro reference only'
else:
conf = 'high' if yaw10_p < 0.15 * wid else 'medium'
why = f'n_athletes={n}; lab 3D-marker data; yaw+-10 shifts p10/p90 by up to {yaw10_p:.1f}'
if m in ('leg_lift_to_fp_ms', 'fp_to_release_ms') and conf == 'high':
conf = 'medium'
why += '; needs >=120 fps and event detection error not modelled'
entry[lv] = dict(
n_athletes=n, n_trials=s['n_trials'], **{f'p{p}': round(s[f'p{p}'], 2) for p in PCTS},
mean=round(s['mean'], 2), sd=None if s['sd'] is None else round(s['sd'], 2),
current_band=cb, proposed_band=prop, proposed_band_source='pooled_all_levels' if fallback else lv,
widened_for_yaw10_by=round(widen, 2),
confidence_of_proposal=conf, confidence_reason=why,
sensitivity_yaw10_shift=dict(median=round(yaw10, 2), p10_p90_edge=round(yaw10_p, 2)),
sensitivity_yaw20_median_shift=round(max(abs(sens[m]['all']['yaw20_tilt0']['median_shift']), abs(sens[m]['all']['yaw-20_tilt0']['median_shift'])), 2),
sensitivity_tilt3_median_shift=round(sens[m]['all']['yaw0_tilt3']['median_shift'], 2))
out[m] = entry
out['_meta'] = dict(source='OpenBiomechanics Project pitching dataset-v1 landmarks (CC BY-NC-SA), virtual orthographic open-side camera',
per_athlete_median_then_percentiles=True, n_pitches_used=res['n_pitches_used'],
n_pitches_excluded_event_qc=res['n_pitches_excluded_event_qc'],
athletes_per_level={lv: S['stride_pct_height'][lv]['n_athletes'] for lv in LEVELS})
yaml.safe_dump(out, open(f'{outdir}/pitching_ranges.yaml', 'w'), sort_keys=False, default_flow_style=None)
res['stats'] = S
json.dump(res, open(f'{outdir}/_tables.json', 'w'), indent=1, default=float)
if __name__ == '__main__':
main(*sys.argv[1:4])
|