Spaces:
Running on T4
Running on T4
File size: 9,682 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 | """Merge the OBP calibration results into one proposed ranges file for the coach agent (format v3).
python build_ranges_v3.py <current ranges.yaml> <calibration dir> <out yaml>
Every decision below is explicit and reviewable. Nothing here edits the agent; the output is a proposal.
"""
import csv
import statistics
import sys
from collections import defaultdict
from pathlib import Path
import yaml
current_path, calib_dir, out_path = (Path(p) for p in sys.argv[1:4])
current = yaml.safe_load(current_path.read_text())
pitch = yaml.safe_load((calib_dir / "pitching_ranges.yaml").read_text())
hit = yaml.safe_load((calib_dir / "hitting_ranges.yaml").read_text())
LEVELS = ("hs_jv", "hs_varsity", "college")
ATTRIBUTION = "OpenBiomechanics Project, Driveline Baseball (CC BY-NC-SA 4.0): commercial licence required"
def keep_published(discipline, key):
"""Existing (published / PRD) bands, kept for reference-only metrics."""
entry = current[discipline][key]
return entry["levels"], entry["status"], entry.get("placeholder", False)
def pitching_level_map(stats, key):
"""OBP high_school -> hs_varsity and hs_jv (low confidence, pooled); college -> college."""
out = {}
for lvl, src in (("hs_jv", "high_school"), ("hs_varsity", "high_school"), ("college", "college")):
d = stats[src]
out[lvl] = {"band": d["proposed_band"], "confidence": d["confidence_of_proposal"] if lvl == "college" else "low",
"n": d["n_athletes"] if lvl != "hs_jv" else 0}
return out
def hitting_level_map(m, key):
out = {}
for lvl in LEVELS:
d = m[lvl]
out[lvl] = {"band": d["proposed_band"], "confidence": d["confidence_of_proposal"] if lvl == "college" else "low",
"n": d.get("n_athletes", 0) if lvl != "hs_jv" else 0}
return out
def entry(discipline, key, unit, levels, use, comparable, basis, note, definition=None, force_confidence=None, placeholder=False):
e = {
"unit": unit,
"use": use,
"comparable": comparable,
"placeholder": placeholder,
"status": {"hs": "calibrated" if basis == "calibrated_obp" else "unverified",
"college": "calibrated" if basis == "calibrated_obp" else "unverified"},
"basis": basis,
"levels": None,
"confidence": None,
"n_athletes": None,
"note": note,
}
if definition:
e["definition"] = definition
if levels:
e["levels"] = {lv: [round(float(x), 1) for x in levels[lv]["band"]] for lv in LEVELS}
e["confidence"] = {lv: force_confidence or levels[lv]["confidence"] for lv in LEVELS}
e["n_athletes"] = {lv: levels[lv]["n"] for lv in LEVELS}
return e
out = {"version": 3, "source": f"calibrated on public lab data: {ATTRIBUTION}. Typical != ideal; no phone noise included.",
"attribution": ATTRIBUTION, "hitting": {}, "pitching": {}}
# ------------------------------------------------------------------------------------------------ pitching
P = out["pitching"]
for key, unit, note in (
("stride_pct_height", "%", "Ankle-to-ankle distance at foot plant as % of height, measured from a side view (our convention). Real pitchers measure about 74%, not the published 83% (3D convention)."),
("lead_knee_flexion_fp_deg", "deg", "0 = straight leg. College band is high confidence."),
("lead_knee_flexion_release_deg", "deg", "The knee is extending at release, so this depends on release-frame detection."),
("lead_knee_block_deg", "deg", "Flexion at foot plant minus flexion at release; positive = the leg firmed up. Wide spread between pitchers."),
("trunk_forward_tilt_release_deg", "deg", "Mid-hip to mid-shoulder line vs vertical; about 4 deg lower than the lab thorax segment."),
("leg_lift_to_fp_ms", "ms", "Uses the lab foot plant (100% body weight). Align the app's foot-plant event with it."),
("fp_to_release_ms", "ms", "Uses the lab foot plant (100% body weight), about 19 ms after first touch. Align the app's event."),
):
P[key] = entry("pitching", key, unit, pitching_level_map(pitch[key], key), "judge", True, "calibrated_obp", note)
for key, unit, why in (
("trunk_lateral_tilt_release_deg", "deg", "Frontal-plane lean; a side-view phone camera cannot see it and the lab sign convention differs. Reference only."),
("arm_slot_deg", "deg", "Shifts 8 to 20 deg with a slightly off camera angle. Reference only; used only for pitch-to-pitch consistency."),
("hip_shoulder_sep_fp", "deg", "A 2D estimate unrelated to the true 3D rotation (r = -0.08). Reference only, never judged."),
):
levels, status, placeholder = keep_published("pitching", key)
e = entry("pitching", key, unit, None, "reference_only", False, "published", why)
e["levels"] = levels
e["status"] = status
e["confidence"] = {lv: "low" for lv in LEVELS}
P[key] = e
# head stability redefined as the vertical range of the head (computed per athlete median, then percentiles)
rows = list(csv.DictReader((calib_dir / "pitch_metrics_all_configs.csv").open()))
per_athlete = defaultdict(list)
for r in rows:
if float(r["yaw_deg"]) == 0 and float(r["tilt_deg"]) == 0 and r["head_vertical_range_pct_height"]:
per_athlete[(r["user"], r["playing_level"])].append(float(r["head_vertical_range_pct_height"]))
meds = sorted(statistics.median(v) for v in per_athlete.values())
def pct(vals, p):
k = (len(vals) - 1) * p / 100
lo, hi = int(k), min(int(k) + 1, len(vals) - 1)
return vals[lo] + (vals[hi] - vals[lo]) * (k - lo)
band = [pct(meds, 10), pct(meds, 90)]
P["head_stability_pct_height"] = entry(
"pitching", "head_stability_pct_height", "%",
{lv: {"band": band, "confidence": "low", "n": len(meds) if lv != "hs_jv" else 0} for lv in LEVELS}, "judge", True,
"calibrated_obp",
"REDEFINED: vertical range of the head from leg lift to release, as % of height (total path length is dominated by the whole "
"body moving toward the plate and is meaningless). Band is pooled across all levels.",
definition="vertical range of the head (max minus min height) from leg lift to release, % of body height")
# ------------------------------------------------------------------------------------------------ hitting
H = out["hitting"]
hm = hit["metrics"]
H["stride_pct_height"] = entry(
"hitting", "stride_pct_height", "%", hitting_level_map(hm["stride_sep_fp_pct_height"], "stride"), "judge", True, "calibrated_obp",
"REDEFINED: foot-to-foot (ankle-to-ankle) horizontal distance at foot plant as % of height. The old 'lead-ankle travel from load "
"start' definition measures about 15%, not the 43-51% the band described.",
definition="horizontal distance between the lead and back ankle at foot plant, % of body height")
H["foot_plant_to_contact_ms"] = entry(
"hitting", "foot_plant_to_contact_ms", "ms", hitting_level_map(hm["foot_plant_to_contact_ms"], "fpc"), "judge", True,
"calibrated_obp",
"Lab values (foot plant at 100% body weight, contact from the lab). The PRD's 185-235 ms does not match; re-derive on the app's own "
"detected events from pilot clips. Confidence is low until the event definitions are aligned.",
force_confidence="low")
H["com_drift_pct_height"] = entry(
"hitting", "com_drift_pct_height", "%", hitting_level_map(hm["com_drift_pct_height"], "com"), "judge", True, "calibrated_obp",
"Hip midpoint relative to the lead ankle at contact (negative = hips behind the front foot). Real hitters sit 19-30% behind it.")
for key, unit, note in (
("head_movement_pct_height", "%", "The lab data has no head point (the neck-base proxy reads 8-18%), so the PRD's 0-5% band can be neither confirmed nor rejected: head movement is NOT judged until the app's own nose tracking is calibrated on pilot clips."),
("lead_knee_angle_contact_deg", "deg", "A face-on 2D knee angle reads about 28 deg straighter than the real knee and does not track it (r = 0.01). Reference only until a better view or method exists."),
("hip_shoulder_separation_foot_plant_deg", "deg", "Not valid from a chest-facing camera (r = 0.38 with the 3D x-factor). Reference only."),
):
levels, status, placeholder = keep_published("hitting", key)
use = "reference_only" # head movement too: no valid head point in the lab data, so the band cannot be calibrated yet
e = entry("hitting", key, unit, None, use, use == "judge", "prd_unverified", note, placeholder=placeholder)
e["levels"] = levels
e["status"] = status
e["confidence"] = {lv: "low" for lv in LEVELS}
H[key] = e
for key, unit, note in (
("load_tempo_s", "s", "A data band exists (college 0.76-1.41 s) but depends on a reconstructed load-start rule. No band until validated on pilot clips."),
("load_launch_ratio", "ratio", "A data band exists (college 5.9-13.6) but depends on a reconstructed load-start rule. No band until validated."),
("lateral_trunk_tilt_contact_deg", "deg", "The shoulder line is nearly edge-on to a chest-facing camera at contact. Not a valid trunk-tilt measurement."),
):
H[key] = entry("hitting", key, unit, None, "reference_only", False, "none", note)
out_path.write_text("# Proposed ranges v3 (agent-owned format). Generated by data_ref/scripts/build_ranges_v3.py; review before use.\n"
+ yaml.safe_dump(out, sort_keys=False, width=120))
for d in ("hitting", "pitching"):
for k, e in out[d].items():
cur = current[d][k]["levels"]
print(f"{d[:3]} {k:42} use={e['use']:14} college={ (e['levels'] or {}).get('college')} conf={(e['confidence'] or {}).get('college')} | was {(cur or {}).get('college')}")
|