baseball-engine / data_ref /scripts /build_ranges_v3.py
github-actions[bot]
Automated Deploy: f4f01388c7b26e818cffbd64414eac11381a7891
35e80ff
Raw History Blame Contribute Delete
9.68 kB
"""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')}")