Spaces:
Running on T4
Running on T4
File size: 6,542 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 | """Run real (lab) athletes through the agent's evidence engine and report how many healthy athletes each set of ranges flags.
python validate_with_obp.py <calibration dir> <ranges_v3_proposed.yaml> [seed]
Scenario A = the agent's CURRENT ranges and the app's CURRENT metric definitions (hitting stride = ankle travel).
Scenario B = the PROPOSED v3 ranges (only metrics marked use=judge; hitting stride redefined as foot-to-foot).
Phone pose-estimation noise is SIMULATED with the assumed standard deviations below (documented assumption, not measured).
Athletes are lab volunteers (mostly college/pro), so most should NOT be flagged for a problem; flag rates well above ~30% suggest
the ranges are miscalibrated for this population. This is a sanity check of the ranges, not a measure of coaching accuracy.
"""
import csv
import random
import sys
from collections import Counter, defaultdict
from pathlib import Path
import yaml
from ai_coach import analysis
calib, v3_path = Path(sys.argv[1]), Path(sys.argv[2])
seed = int(sys.argv[3]) if len(sys.argv) > 3 else 11
v3 = yaml.safe_load(v3_path.read_text())
LEVEL_MAP = {"high_school": "hs_varsity", "college": "college", "independent": "college", "milb": "college"}
NOISE_SD = { # assumed phone pose-estimation noise per metric (same units as the metric)
"pct": 1.5, "deg": 3.0, "pitch_ms": 4.0, "hit_ms": 6.0,
}
UNIT = {"stride_pct_height": "%", "foot_plant_to_contact_ms": "ms", "head_movement_pct_height": "%", "com_drift_pct_height": "%",
"lead_knee_angle_contact_deg": "deg", "lead_knee_flexion_fp_deg": "deg", "lead_knee_flexion_release_deg": "deg",
"lead_knee_block_deg": "deg", "trunk_forward_tilt_release_deg": "deg", "arm_slot_deg": "deg",
"leg_lift_to_fp_ms": "ms", "fp_to_release_ms": "ms", "head_stability_pct_height": "%"}
CONF = {"stride_pct_height": "high", "head_movement_pct_height": "high", "com_drift_pct_height": "medium",
"foot_plant_to_contact_ms": "medium", "lead_knee_angle_contact_deg": "medium", "lead_knee_flexion_fp_deg": "medium",
"lead_knee_flexion_release_deg": "medium", "lead_knee_block_deg": "medium", "trunk_forward_tilt_release_deg": "medium",
"arm_slot_deg": "medium", "leg_lift_to_fp_ms": "high", "fp_to_release_ms": "high", "head_stability_pct_height": "high"}
def noise_sd(discipline, key):
unit = UNIT[key]
return NOISE_SD["pct"] if unit == "%" else NOISE_SD["deg"] if unit == "deg" else NOISE_SD["pitch_ms" if discipline == "pitching" else "hit_ms"]
def sessions(discipline, rng):
"""{(athlete, level): [per-trial raw metric dicts]} from the calibration CSVs."""
by = defaultdict(list)
if discipline == "pitching":
for r in csv.DictReader((calib / "pitch_metrics_all_configs.csv").open()):
if float(r["yaw_deg"]) == 0 and float(r["tilt_deg"]) == 0:
by[(r["user"], r["playing_level"])].append(r)
else:
for r in csv.DictReader((calib / "work_hitting" / "swing_metrics_hitting.csv").open()):
if r["config"] == "base":
by[(r["user"], r["level"])].append(r)
return by
def build_reps(discipline, trials, scenario, rng):
"""Turn raw trials into session reps with simulated noise; scenario decides which metric set/definitions are used."""
if discipline == "pitching":
keys = {"stride_pct_height": "stride_pct_height", "lead_knee_flexion_fp_deg": "lead_knee_flexion_fp_deg",
"lead_knee_flexion_release_deg": "lead_knee_flexion_release_deg", "lead_knee_block_deg": "lead_knee_block_deg",
"trunk_forward_tilt_release_deg": "trunk_forward_tilt_release_deg", "arm_slot_deg": "arm_slot_deg",
"leg_lift_to_fp_ms": "leg_lift_to_fp_ms", "fp_to_release_ms": "fp_to_release_ms"}
keys["head_stability_pct_height"] = "head_vertical_range_pct_height" if scenario == "B" else "head_stability_pct_height"
else:
keys = {"stride_pct_height": "stride_sep_fp_pct_height" if scenario == "B" else "stride_pct_height",
"foot_plant_to_contact_ms": "foot_plant_to_contact_ms", "head_movement_pct_height": "head_movement_pct_height",
"com_drift_pct_height": "com_drift_pct_height", "lead_knee_angle_contact_deg": "lead_knee_angle_contact_deg"}
reps = []
for t in trials:
metrics = []
for key, col in keys.items():
if t.get(col) in (None, ""):
continue
value = float(t[col]) + rng.gauss(0, noise_sd(discipline, key))
metrics.append({"key": key, "value": round(value, 2), "unit": UNIT[key], "confidence": CONF[key]})
reps.append({"metrics": metrics})
return reps
def run(discipline, scenario, seed):
rng = random.Random(seed)
rows = defaultdict(lambda: {"athletes": 0, "flagged": 0, "problems": Counter(), "n_problems": 0})
judged = {k for k, e in v3[discipline].items() if e["use"] == "judge"} if scenario == "B" else None
for (athlete, level), trials in sessions(discipline, rng).items():
if len(trials) < 3:
continue
app_level = LEVEL_MAP.get(level, "college")
reps = build_reps(discipline, trials, scenario, rng)
overrides = None
if scenario == "B":
overrides = {k: tuple(v3[discipline][k]["levels"][app_level]) for k in judged if v3[discipline][k]["levels"]}
for rep in reps: # reference-only metrics are not judged in the proposal: drop them
rep["metrics"] = [m for m in rep["metrics"] if m["key"] in judged or m["key"] == "arm_slot_deg"]
result = analysis.analyze(discipline, app_level, reps, overrides)
eligible = [p.key for p in result.problems if p.eligible]
row = rows[app_level]
row["athletes"] += 1
row["flagged"] += bool(eligible)
row["n_problems"] += len(eligible)
row["problems"].update(eligible)
return rows
for discipline in ("pitching", "hitting"):
for scenario, label in (("A", "CURRENT ranges and definitions"), ("B", "PROPOSED v3 ranges")):
rows = run(discipline, scenario, seed)
print(f"\n== {discipline} / {label}")
for level, r in sorted(rows.items()):
share = r["flagged"] / r["athletes"] if r["athletes"] else 0
top = ", ".join(f"{k}:{v}" for k, v in r["problems"].most_common(5)) or "-"
print(f" {level:11} athletes={r['athletes']:3} flagged_with_a_problem={share:5.0%} avg_problems={r['n_problems'] / max(r['athletes'], 1):.2f} top: {top}")
|