baseball-engine / data_ref /scripts /write_report.py
github-actions[bot]
Automated Deploy: f4f01388c7b26e818cffbd64414eac11381a7891
35e80ff
Raw History Blame
19.4 kB
"""Builds CALIBRATION_REPORT_pitching.md from the analysis outputs.
Usage (python -I): write_report.py CALIB_DIR LANDMARKS_CSV OUT_MD
"""
import json
import sys
import numpy as np
import pandas as pd
import yaml
LV = ['high_school', 'college', 'independent', 'milb', 'all']
M = ['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']
def verdict(cur, prop):
if not cur:
return 'no current band'
a, b = cur
c, d = prop
inter = max(0, min(b, d) - max(a, c))
wr = (b - a) / (d - c)
cen = ((a + b) - (c + d)) / 2
if inter / (d - c) < 0.25:
return 'disjoint / shifted'
if wr < 0.6:
return 'too narrow'
if wr > 1.6:
return 'too wide'
if abs(cen) > 0.25 * (d - c):
return 'shifted (%+.1f)' % cen
return 'agrees'
def f(x, n=1):
return '-' if x is None else f'{x:.{n}f}'
def main(cdir, lm_csv, out):
R = yaml.safe_load(open(f'{cdir}/pitching_ranges.yaml'))
T = json.load(open(f'{cdir}/_tables.json'))
lm = pd.read_csv(lm_csv, usecols=['session_pitch', 'fp_10_time', 'fp_100_time', 'BR_time']).drop_duplicates('session_pitch')
lm = lm[~lm.session_pitch.isin(T['excluded'])]
fp10 = (1000 * (lm.BR_time - lm.fp_10_time)).median()
fp10_100 = (1000 * (lm.fp_100_time - lm.fp_10_time)).median()
L = []
w = L.append
w('# Pitching typical-range calibration from OpenBiomechanics (OBP), computed as our 2D open-side phone camera sees it\n')
w('Generated by `data_ref/scripts/` (compute_pitching_metrics.py, analyze_pitching.py, write_report.py). Machine-readable results: `pitching_ranges.yaml`; per-pitch values: `pitch_metrics_all_configs.csv`.\n')
w('## 1. Method\n')
w(f'* Data: OBP `pitching_landmarks.csv` (joint-centre positions, 360 Hz, lab frame: +x second base to home, +y first base, +z up) joined to `poi_metrics.csv` and `metadata.csv`. 403 of 411 pitches have landmarks; {T["n_pitches_excluded_event_qc"]} further pitches ({", ".join(T["excluded"])}) were dropped because OBP event times were implausible (fp->BR outside 30-400 ms or leg-lift->FP < 200 ms), leaving **{T["n_pitches_used"]} fastballs from {R["_meta"]["athletes_per_level"]["all"]} athletes**.')
w('* Virtual camera: orthographic, optical axis horizontal and along the lab y axis (perpendicular to the pitcher-to-plate x axis), image u = toward plate (lab x), v = up (z). Left-handers are mirrored (y -> -y). Perspective, lens distortion and pose-estimation noise are NOT modelled.')
w('* Events: foot plant = OBP `fp_100_time` (100 % body weight on lead foot), release = `BR_time`, peak leg lift = own max lead-knee height before FP (agrees with OBP `pkh_time` to < 1 ms on average, r = 1.00). All metrics are computed frame by frame in the image plane and read at the nearest 360 Hz frame.')
w('* Heights: `session_height_m` from metadata. Statistics: median of each athlete\'s pitches first (one value per `user`), then percentiles (linear interpolation) and mean/SD across athletes. `n_trials` counts pitches.')
w('* Sensitivity: the same pipeline with the camera yawed +-10 and +-20 degrees about the vertical axis and with a 3 degree pitch (tilt) about the camera right axis; shifts are computed on the across-athlete distribution (all levels pooled; college-only is in `_tables.json`).\n')
w('## 2. Landmark mapping\n')
w('| App joint | OBP landmark |\n|---|---|\n| lead ankle / knee / hip | `lead_ankle_jc`, `lead_knee_jc`, `lead_hip` |\n| back (rear) ankle | `rear_ankle_jc` |\n| throwing shoulder / wrist | `shoulder_jc`, `wrist_jc` (elbow `elbow_jc`) |\n| glove shoulder | `glove_shoulder_jc` |\n| mid-hip | mean of `lead_hip`, `rear_hip` |\n| mid-shoulder | mean of `shoulder_jc`, `glove_shoulder_jc` |\n| head / nose | **no head or nose landmark in OBP**; proxy = `thorax_prox` (proximal thorax / neck base) |\n')
w('Definitions as computed: stride = |u(lead ankle) - u(rear ankle)| / height at FP; knee flexion = 180 - angle(hip-knee-ankle) in the image; trunk forward tilt = angle of mid-hip -> mid-shoulder from image vertical, + toward plate; trunk lateral tilt = image-plane tilt of the throwing->glove shoulder line from horizontal (+ glove side higher, so a normal throwing-side-high release is negative); arm slot = angle of shoulder -> wrist vector from image horizontal toward the plate (90 = straight up); head stability = path length of the proxy in (u,v) from peak leg lift to release / height (we also report net displacement and vertical range); hip-shoulder separation estimate = shoulder-line tilt minus hip-line tilt (same convention) at FP.\n')
w('## 3. Validation against OBP summary metrics (399 pitches, yaw 0, tilt 0)\n')
V = T['validation']
w('| Our 2D metric | OBP 3D metric | r | mean diff (ours - OBP) | SD diff | n |\n|---|---|---|---|---|---|')
names = [('stride_vs_obp_stride_length', 'stride_pct_height (as fraction of height)', '`stride_length` (fraction of height)'),
('trunk_fwd_vs_torso_anterior_tilt_br', 'trunk_forward_tilt_release_deg', '`torso_anterior_tilt_br`'),
('arm_slot_vs_obp_arm_slot', 'arm_slot_deg', '`arm_slot` (global forearm projection angle)'),
('lead_knee_block_vs_obp_extension_fp_to_br', 'lead_knee_block_deg', '`lead_knee_extension_from_fp_to_br`'),
('trunk_lateral_2d_vs_obp_torso_lateral_tilt_br', 'trunk_lateral_tilt_release_deg', '`torso_lateral_tilt_br`'),
('hip_shoulder_sep_2d_vs_obp_3d_fp', 'hip_shoulder_sep_fp (2D)', '`rotation_hip_shoulder_separation_fp`'),
('leg_lift_to_fp_ms_own_peak_vs_obp_pkh', 'leg_lift_to_fp_ms (own peak)', 'FP - `pkh_time` (ms)')]
for k, a, b in names:
v = V[k]
d = v['mean_diff'] * (1 if k != 'stride_vs_obp_stride_length' else 100)
sd = v['sd_diff'] * (1 if k != 'stride_vs_obp_stride_length' else 100)
unit = ' pp' if k == 'stride_vs_obp_stride_length' else ''
w(f'| {a} | {b} | {v["r"]:.2f} | {d:+.1f}{unit} | {sd:.1f} | {v["n"]} |')
w('')
w('Reading the validation:\n')
w(f'* **Stride (the 2D-vs-3D convention gap).** Our ankle-to-ankle stride is ~10 percentage points of height shorter than OBP `stride_length` (r = {V["stride_vs_obp_stride_length"]["r"]:.2f}). OBP `stride_angle` is only ~5 deg, so 3D vs 2D geometry explains < 0.5 pp; the gap is a landmark/definition difference (OBP stride is not same-joint ankle centre to ankle centre; OBP does not document it in the files we have, so the exact anchor is unverified), not a camera effect. Using ankle-to-ankle (what our pose model sees) the typical college stride is ~{R["stride_pct_height"]["college"]["p50"]:.0f} % of height, consistent with the ~75 % markerless figure already noted in the app. **Do not compare our stride to the 83 % published figure.**')
w(f'* **Trunk forward tilt.** Strong agreement (r = {V["trunk_fwd_vs_torso_anterior_tilt_br"]["r"]:.2f}) with a systematic {V["trunk_fwd_vs_torso_anterior_tilt_br"]["mean_diff"]:+.1f} deg offset: the mid-hip -> mid-shoulder line is not the same axis as OBP\'s thorax segment (pelvis landmarks vs thorax, plus axial rotation at release moves the shoulder midpoint in the image). Our value is therefore the right thing to compare to our own band, but published/OBP thorax-flexion bands are ~4 deg higher.')
w(f'* **Arm slot.** r = {V["arm_slot_vs_obp_arm_slot"]["r"]:.2f}, mean diff {V["arm_slot_vs_obp_arm_slot"]["mean_diff"]:+.1f} deg, SD of differences {V["arm_slot_vs_obp_arm_slot"]["sd_diff"]:.1f} deg. OBP uses the forearm projection, we use shoulder -> wrist, so the close mean is partly coincidence. The metric is only valid for a perfectly perpendicular camera: yaw +-10 deg moves the median by -6/+8 deg and +-20 by up to +20 deg.')
w(f'* **Lead knee block** correlates r = {V["lead_knee_block_vs_obp_extension_fp_to_br"]["r"]:.2f} with OBP knee extension FP->BR (our value {V["lead_knee_block_vs_obp_extension_fp_to_br"]["mean_diff"]:+.1f} deg lower on average; the 2D knee angle is foreshortened when the thigh is not in the image plane, and OBP measures the 3D knee angle).')
w(f'* **Trunk lateral tilt and hip-shoulder separation do not validate.** Lateral tilt in the image is r = {V["trunk_lateral_2d_vs_obp_torso_lateral_tilt_br"]["r"]:.2f} against OBP (opposite sign convention, offset {V["trunk_lateral_2d_vs_obp_torso_lateral_tilt_br"]["mean_diff"]:+.0f} deg): at release the shoulder line points mostly along the camera axis so the image angle is dominated by foreshortening and swings 8-25 deg per 10-20 deg of yaw. The 2D hip-shoulder separation has r = {V["hip_shoulder_sep_2d_vs_obp_3d_fp"]["r"]:.2f} with OBP\'s transverse-plane separation, i.e. it carries no information about true separation. Both are reported only as flagged estimates.\n')
w('## 4. Distributions by playing level (median per athlete, then across athletes)\n')
ath = R['_meta']['athletes_per_level']
w(f'Athletes: high_school **{ath["high_school"]}**, college {ath["college"]}, independent {ath["independent"]}, milb {ath["milb"]}, all {ath["all"]}. **High school has only 7 athletes (32 pitches), so percentiles beyond about p25-p75 are essentially individual athletes and are not a reliable estimate of the HS population.** Milb (6) and independent (12) are also small. Only college (75) supports stable p10-p90 bands.\n')
for m in M:
w(f'### {m}\n')
w('| level | n_ath | n_trials | p5 | p10 | p25 | p50 | p75 | p90 | p95 | mean | SD |\n|---|---|---|---|---|---|---|---|---|---|---|---|')
for lv in LV:
e = R[m].get(lv)
if not e:
continue
w(f'| {lv} | {e["n_athletes"]} | {e["n_trials"]} | ' + ' | '.join(f(e[k]) for k in ['p5', 'p10', 'p25', 'p50', 'p75', 'p90', 'p95', 'mean', 'sd']) + ' |')
w('')
S = T['stats']
w('Supplementary head-travel variants (all levels, per-athlete medians): path length p10/p50/p90 = ' + ' / '.join(f(S['head_stability_pct_height']['all'][k]) for k in ['p10', 'p50', 'p90']) + ' % height; net displacement = ' + ' / '.join(f(S['head_net_displacement_pct_height']['all'][k]) for k in ['p10', 'p50', 'p90']) + ' %; vertical range only = ' + ' / '.join(f(S['head_vertical_range_pct_height']['all'][k]) for k in ['p10', 'p50', 'p90']) + ' %.\n')
w('## 5. Mapping to app levels\n')
w('* `college` <- OBP college (n = 75). Note OBP "college" athletes are volunteers in a lab (many D1 / elite) so the population skews toward better pitchers than the general college level.\n* `hs_varsity` <- OBP high_school (n = 7) **only with a low-confidence flag**; because n < 20 the proposed band falls back to the pooled all-levels p10-p90. The OBP high-school group is likely a select, high-level subset, and is not representative of typical varsity pitchers.\n* `hs_jv` <- no data; use the same pooled fallback band as hs_varsity, marked low confidence/unverified. Younger/less-skilled players are expected to have shorter strides and more variable mechanics, so these bands are if anything too narrow for JV.\n* `independent`, `milb` are shown for reference only (n = 12, 6).\n')
w('## 6. Sensitivity to camera setup (all-levels per-athlete distribution; shift vs ideal camera)\n')
w('Median shift / shift of the p10 edge / shift of the p90 edge, in metric units (stride, head in % height; angles in deg).\n')
w('| metric | yaw +10 | yaw -10 | yaw +20 | yaw -20 | tilt 3 |\n|---|---|---|---|---|---|')
for m in M:
s = T['sensitivity'][m]['all']
cells = []
for k in ['yaw10_tilt0', 'yaw-10_tilt0', 'yaw20_tilt0', 'yaw-20_tilt0', 'yaw0_tilt3']:
x = s[k]
cells.append(f'{x["median_shift"]:+.1f} / {x["p10_shift"]:+.1f} / {x["p90_shift"]:+.1f}')
w(f'| {m} | ' + ' | '.join(cells) + ' |')
w('')
w('Take-aways: timings are camera independent (but depend on frame rate and event detection, which are not modelled here). Knee flexion and stride are tolerant (|shift| <= ~2-3 deg / ~1.5 pp at +-10 yaw, ~5 pp stride at 20 deg). Trunk forward tilt moves 3-4 deg at +-10 and up to ~10 deg at -20. Arm slot (up to +8 deg at +10, +20 at +20) and trunk lateral tilt (-12 deg) are strongly yaw dependent, and the 2D hip-shoulder estimate is also affected by 3 deg tilt (-3 deg). A 3 deg camera pitch is negligible for everything except arm slot (-2 deg) and hip-shoulder estimate. Yaw-sensitive bands were widened (see below) by the larger of the p10/p90 edge shifts at +-10 deg when that shift exceeds 10 % of the band width.\n')
w('## 7. Current app ranges vs data-driven proposal (p10-p90 of per-athlete medians; widened for yaw +-10 when material)\n')
w('Verdict rule: disjoint = overlap < 25 % of proposed band; too narrow/wide = width ratio < 0.6 / > 1.6; shifted = centres differ by > 25 % of proposed width.\n')
w('| metric | level | current | proposed | verdict | n_ath | confidence |\n|---|---|---|---|---|---|---|')
keymap = {'college': 'college', 'high_school': 'hs_varsity'}
for m in M:
for lv in ['college', 'high_school']:
e = R[m][lv]
cur = e['current_band']
w(f'| {m} | {keymap[lv]} | {"-" if not cur else f"{cur[0]:.0f}-{cur[1]:.0f}"} | {e["proposed_band"][0]:.0f}-{e["proposed_band"][1]:.0f} ({e["proposed_band_source"]}) | {verdict(cur, e["proposed_band"])} | {e["n_athletes"]} | {e["confidence_of_proposal"]} |')
w('')
w('Notes per metric:\n')
c = R
w(f'* **stride_pct_height**: current 79-87 is shifted ~6-8 pp too high for our ankle-to-ankle definition (college p10-p90 = {c["stride_pct_height"]["college"]["p10"]:.0f}-{c["stride_pct_height"]["college"]["p90"]:.0f}, median {c["stride_pct_height"]["college"]["p50"]:.0f}); it is the 3D-published convention. Propose ~{c["stride_pct_height"]["college"]["proposed_band"][0]:.0f}-{c["stride_pct_height"]["college"]["proposed_band"][1]:.0f}. This also lets "normal" pitchers stop being flagged as short-stride.')
w('* **lead_knee_flexion_fp**: current college 43-61 is ~6 deg higher than the data (p10-p90 ~34-58); the hs_varsity 38-56 agrees with the pooled data. **lead_knee_flexion_release**: current 25-55 agrees with the data (25-57) but real spread is wide (SD ~13 deg); release is a moving-knee metric, so release-frame detection error widens it further in practice.')
w('* **lead_knee_block**: no current band; data median is ~+5 deg with a wide spread (p10-p90 about -9 to +20) and a considerable share of athletes whose knee flexes further (negative). The "firms up" interpretation (positive = good) is not a universal norm; a fault threshold on this metric is not supported by the data.')
w('* **trunk_forward_tilt**: current college 30-44 is ~5 deg higher than our 2D data (college p10-p90 ~19-42); consistent with the ~4 deg thorax-vs-hip-shoulder-line offset found in validation. HS sample (median 43) is too small to say HS differs.')
w('* **trunk_lateral_tilt**: the current bands (positive 9-37) have the opposite sign and a different quantity from the image-plane shoulder-line tilt (negative, -66 to -30). They are not comparable. Keep as reference only, or drop.')
w('* **arm_slot**: current 50-68 vs data (college p10-p90 ~32-54 under our shoulder->wrist image-angle definition) is shifted high by ~15 deg; and the metric moves up to +20 deg with camera yaw. It cannot be a pass/fail metric from a side view; keep it `est`/reference only and widen sharply.')
w('* **leg_lift_to_fp_ms / fp_to_release_ms / head_stability**: no current band. Proposed from the data (see yaml). The OBP FP event is 100 % body weight; the app\'s foot plant is probably nearer first contact (OBP `fp_10_time`, '
f'median {fp10_100:.0f} ms earlier), which would make fp_to_release about {fp10:.0f} ms (median) instead of ~{S["fp_to_release_ms"]["all"]["p50"]:.0f} ms. Align the event definition before using the timing bands. Head stability as specified (path from leg lift to release, normalised by height) is ~80 % of height because it includes the whole-body travel toward the plate, far above the app\'s 0-60 plausibility cap; the vertical-only range (~22 %) or head movement relative to the pelvis would be a more useful definition. The head proxy here is the neck base, which moves less than the head.')
w('* **hip_shoulder_sep_fp**: current 47-67 is the paper\'s transverse-plane separation; our 2D estimate is ~5-26 deg and uncorrelated with true separation. Not comparable; reference only.\n')
w('## 8. Caveats\n')
w('* OBP athletes are volunteers tested in one lab session with reflective markers (joint centres from a biomechanical model, 360 Hz, 20 Hz filtered). They are mostly college/pro, so "typical" here means typical for a skilled, healthy, cooperative pitcher, not for all hs_jv/varsity players. **Typical is not ideal**; the bands describe what skilled pitchers do, not what is mechanically best.')
w('* One session per athlete (3-8 fastballs), so within-athlete variation is small and between-athlete variation is all we can estimate; fastballs only; the lab mound and indoor setting differ from game conditions.')
w('* The simulation has no pose-estimation error, no perspective, no motion blur and no frame-rate limits. Real phone data will be noisier, so real distributions should be wider than these bands; widen bands further for real use or re-calibrate on app output.')
w('* Camera yaw/tilt sensitivity covers rigid camera placement only. Handedness is handled by mirroring.')
w('* Event definitions (FP at 100 % body weight, own peak-knee lift) differ from what the app detects from pose; event-timing bands are the most definition-dependent.')
w('* 4 pitches (sessions 2918 and 2923, users 1637 and 1641) were excluded for implausible OBP event times; 8 pitches have no landmark data.')
w('* HS group: 7 athletes. Independent: 12. Milb: 6.\n')
w('## 9. Recommendations\n')
w('1. Adopt the college p10-p90 bands (from `pitching_ranges.yaml`) for `college` for stride, knee flexion fp/release, trunk forward tilt, and the timings, after aligning event definitions. These have n = 75 athletes.')
w('2. For `hs_varsity` and `hs_jv`, use the pooled-all-levels bands but label them unverified/low; do not present HS-specific comparisons from the OBP HS group (n = 7). Collect real HS data from the app and recalibrate.')
w('3. Change the stride band to the ankle-to-ankle convention (about 68-80 % for college) and note the 83 % published value is a different measure.')
w('4. Treat arm slot, trunk lateral tilt and 2D hip-shoulder separation as `est`/reference-only; do not flag faults on them from a side view. Prefer a front/back view for arm slot and lateral lean.')
w('5. Add a camera-angle quality check: yaw beyond +-10 deg shifts trunk forward tilt by ~4 deg and stride by ~1.5 pp, and beyond +-20 deg by up to ~10 deg / 5 pp.')
w('6. Redefine head stability (vertical or relative-to-pelvis) before assigning a band.')
open(out, 'w').write('\n'.join(L) + '\n')
if __name__ == '__main__':
main(*sys.argv[1:4])