baseball-engine / AI-coach-agent /tests /test_analysis.py
github-actions[bot]
Automated Deploy: f4f01388c7b26e818cffbd64414eac11381a7891
35e80ff
Raw History Blame Contribute Delete
11.9 kB
"""The evidence engine: what do the measurements support? (This is the agent's baseline, not the coach.)"""
from ai_coach import analysis
from ai_coach import knowledge as kb
from .helpers import measurements
def run(series, discipline="hitting", level="college", overrides=None, **kw):
session = measurements(discipline=discipline, level=level, series=series, **kw)
return analysis.analyze(discipline, level, session["reps"], overrides)
def problem(result, key):
return next(p for p in result.problems if p.key == key)
def test_metric_stats_median_weakest_confidence_zone_and_status():
result = run(
{
"stride_pct_height": ("%", "high", [47.0, 48.0, 49.0]),
"com_drift_pct_height": ("%", "medium", [-25.0, -24.0, None]),
}
)
stride = next(m for m in result.metrics if m.key == "stride_pct_height")
assert (stride.value, stride.n_reps, stride.per_rep, stride.zone, stride.band) == (
48.0,
3,
[47.0, 48.0, 49.0],
"in_range",
(42.3, 55.8),
)
assert stride.range_status == "calibrated" and stride.range_confidence == "medium" and stride.judgeable
drift = next(m for m in result.metrics if m.key == "com_drift_pct_height")
assert (drift.value, drift.n_reps, drift.confidence) == (-24.5, 2, "medium")
def test_estimates_are_not_judgeable_and_the_weakest_trusted_confidence_wins():
result = run({"stride_pct_height": ("%", "high", [47.0, 47.0]), "head_movement_pct_height": ("%", "est", [2.0, 2.0])})
assert not next(m for m in result.metrics if m.key == "head_movement_pct_height").judgeable
rows = [{"metrics": [{"key": "stride_pct_height", "value": 47.0, "unit": "%", "confidence": c}]} for c in ("high", "medium")]
assert analysis.analyze("hitting", "hs_varsity", rows).metrics[0].confidence == "medium"
def test_estimate_reps_do_not_drag_down_a_trusted_metric():
"""Statistic rule: only High/Medium reps count when any exist, so an eligible problem never shows an 'est' metric."""
rows = [{"metrics": [{"key": "stride_pct_height", "value": 60.0, "unit": "%", "confidence": "high"}]} for _ in range(7)]
rows += [{"metrics": [{"key": "stride_pct_height", "value": 40.0, "unit": "%", "confidence": "est"}]} for _ in range(3)]
result = analysis.analyze("hitting", "hs_varsity", rows)
stride = result.metrics[0]
assert (stride.value, stride.confidence, stride.n_reps, len(stride.per_rep)) == (60.0, "high", 7, 7)
over = next(p for p in result.problems if p.key == "over_stride")
assert over.eligible and over.confidence == "high"
only_est = analysis.analyze("hitting", "hs_varsity", rows[7:])
assert only_est.metrics[0].confidence == "est" and only_est.metrics[0].n_reps == 3 # nothing trusted: reported as is
def test_a_single_outlier_rep_never_makes_a_problem_even_in_a_short_session():
for n in (1, 2, 3):
vals = [47.0] * (n - 1) + [70.0]
p = problem(run({"stride_pct_height": ("%", "high", vals)}), "over_stride")
assert not p.eligible, n
one = problem(run({"stride_pct_height": ("%", "high", [70.0])}), "over_stride")
assert "not a repeated pattern" in one.reason
two = problem(run({"stride_pct_height": ("%", "high", [70.0, 70.0])}), "over_stride")
assert two.eligible and two.severity == "minor" # repeated, but 'major' needs 3 evaluated reps
def test_major_needs_three_evaluated_reps_and_uses_unrounded_excess():
assert problem(run({"stride_pct_height": ("%", "high", [70.0] * 3)}), "over_stride").severity == "major"
# excess (62.4 - 55.8) / 13.5 = 0.4889 rounds to 0.5 for display but must not count as major
near = problem(run({"stride_pct_height": ("%", "high", [62.4] * 5)}), "over_stride")
assert near.median_excess == 0.5 and near.severity == "minor"
assert problem(run({"stride_pct_height": ("%", "high", [62.7] * 5)}), "over_stride").severity == "major"
def test_spread_rule_needs_more_than_one_deviating_rep():
p = problem(run({"arm_slot_deg": ("deg", "medium", [50.0, 50.0, 70.0])}, discipline="pitching"), "slot_inconsistency")
assert not p.eligible and "not a repeated pattern" in p.reason
def test_inverted_or_empty_override_ranges_are_rejected():
import pytest
for bad in ((60.0, 40.0), (40.0, 40.0), (float("nan"), 50.0), ("a", "b"), (1.0,)):
with pytest.raises(ValueError, match="override"):
kb.metric_range("hitting", "stride_pct_height", "hs_varsity", {"stride_pct_height": bad})
def test_reference_only_and_no_band_metrics_are_never_zoned():
result = run(
{
"hip_shoulder_separation_foot_plant_deg": ("deg", "est", [41.0]),
"lateral_trunk_tilt_contact_deg": ("deg", "medium", [14.0]),
}
)
by = {m.key: m for m in result.metrics}
assert by["hip_shoulder_separation_foot_plant_deg"].zone == "reference_only"
assert by["lateral_trunk_tilt_contact_deg"].zone == "unknown" and by["lateral_trunk_tilt_contact_deg"].band is None
def test_a_repeated_out_of_range_metric_becomes_an_eligible_problem():
result = run({"stride_pct_height": ("%", "high", [64.0, 65.0, 66.0, 64.5, 67.0, 65.5])})
p = problem(result, "over_stride")
assert p.eligible and p.severity == "major" and p.frequency == 1.0 and p.reps_showing == 6 == p.reps_evaluated
assert p.evidence == ["stride_pct_height"] and p.rank == 1 and p.confidence == "high" and p.median_excess > 0.5
assert p.range_confidence == "medium"
def test_direction_matters():
long_stride = problem(run({"stride_pct_height": ("%", "high", [60.0] * 6)}), "over_stride")
assert long_stride.eligible
short_pitch = problem(run({"stride_pct_height": ("%", "high", [60.0] * 6)}, discipline="pitching"), "short_stride")
assert short_pitch.eligible
long_pitch = problem(run({"stride_pct_height": ("%", "high", [95.0] * 6)}, discipline="pitching"), "short_stride")
assert not long_pitch.eligible
def test_tolerance_scales_with_band_width_and_range_confidence():
# a coach override is high confidence: tolerance is 10% of the band width (43..51 -> 0.8)
coach = {"stride_pct_height": (43.0, 51.0)}
series = lambda v: {"stride_pct_height": ("%", "high", [v] * 6)} # noqa: E731
assert not problem(run(series(51.7), overrides=coach), "over_stride").eligible
assert problem(run(series(51.9), overrides=coach), "over_stride").eligible
# college stride band 42.3..55.8 is medium confidence: tolerance 15% of 13.5 = 2.03 (counts above 57.83)
assert not problem(run(series(57.7)), "over_stride").eligible
assert problem(run(series(57.9)), "over_stride").eligible
# high-school band 39.9..52.2 rests on few athletes (low confidence): tolerance 25% of 12.3 = 3.08 (counts above 55.28)
assert not problem(run(series(55.2), level="hs_varsity"), "over_stride").eligible
assert problem(run(series(55.4), level="hs_varsity"), "over_stride").eligible
def test_one_bad_rep_is_not_a_pattern():
result = run({"stride_pct_height": ("%", "high", [47.0, 47.0, 47.0, 47.0, 47.0, 70.0])})
p = problem(result, "over_stride")
assert not p.eligible and "not a repeated pattern" in p.reason and p.reps_showing == 1
def test_a_metric_measured_on_too_few_reps_is_not_judged():
result = run({"stride_pct_height": ("%", "high", [60.0, 60.0, None, None, None, None])})
p = problem(result, "over_stride")
assert not p.eligible and "only 2 of 6 reps" in p.reason
def test_estimates_cannot_support_a_problem():
p = problem(run({"stride_pct_height": ("%", "est", [60.0] * 6)}), "over_stride")
assert not p.eligible and "estimates" in p.reason
def test_unmeasured_metric_gives_no_problem():
p = problem(run({"head_movement_pct_height": ("%", "high", [2.0] * 4)}), "over_stride")
assert not p.eligible
assert "not measured" in p.reason
def test_reference_only_ranges_are_never_judged():
result = run({"trunk_lateral_tilt_release_deg": ("deg", "medium", [60.0] * 6)}, discipline="pitching")
p = problem(result, "excess_lateral_lean")
assert not p.eligible and "reference-only" in p.reason
def test_estimate_only_problems_never_fire():
result = run({"hip_shoulder_separation_foot_plant_deg": ("deg", "est", [-80.0] * 6)})
p = problem(result, "early_shoulder_open")
assert not p.eligible and "never judged" in p.reason
def test_metrics_without_a_default_range_need_a_coach_target():
series = {"load_tempo_s": ("s", "high", [0.3] * 6)}
assert "coach target" in problem(run(series), "rushing").reason
enabled = run(series, overrides={"load_tempo_s": (0.8, 1.2)})
assert problem(enabled, "rushing").eligible
def test_multiple_rules_are_combined_per_rep():
series = {
"foot_plant_to_contact_ms": ("ms", "medium", [128.0, 300.0, 300.0, 128.0, 128.0, 128.0]),
"load_tempo_s": ("s", "high", [0.2, 0.9, 0.9, 0.9, 0.9, 0.9]),
}
# reference-only in the library (its "contact" is an arm-extension proxy); a coach target restores it
result = run(series, overrides={"load_tempo_s": (0.4, 0.7), "foot_plant_to_contact_ms": (97.8, 145.6)})
p = problem(result, "rushing")
# reps 1,2 show via the plant-to-contact rule, rep 0 shows via the load rule -> three distinct reps
assert p.eligible and p.reps_showing == 3 and set(p.evidence) == {"foot_plant_to_contact_ms", "load_tempo_s"}
def test_spread_rule_finds_inconsistent_arm_slot():
slots = [45.0, 70.0, 52.0, 66.0, 59.0, 40.0, 75.0, 58.0]
p = problem(run({"arm_slot_deg": ("deg", "medium", slots)}, discipline="pitching"), "slot_inconsistency")
assert p.eligible and p.evidence == ["arm_slot_deg"] and p.frequency > 0.3
steady = problem(
run({"arm_slot_deg": ("deg", "medium", [59.0, 60.0, 58.0, 59.5, 60.5, 58.5])}, discipline="pitching"),
"slot_inconsistency",
)
assert not steady.eligible
few = problem(run({"arm_slot_deg": ("deg", "medium", [40.0, 80.0])}, discipline="pitching"), "slot_inconsistency")
assert not few.eligible and "fewer than 3" in few.reason
def test_severity_and_ranking_prefer_larger_lower_body_problems():
series = {
"stride_pct_height": ("%", "high", [56.0] * 8), # major, lower tier
"trunk_forward_tilt_release_deg": ("deg", "medium", [8.0] * 8), # minor, middle tier
}
result = run(series, discipline="pitching")
assert [p.key for p in result.eligible] == ["short_stride", "upright_finish"]
assert problem(result, "short_stride").severity == "major" and problem(result, "upright_finish").severity == "minor"
assert problem(result, "short_stride").impact > problem(result, "upright_finish").impact
def test_medium_confidence_ranks_below_high_at_equal_size():
series = {
"stride_pct_height": ("%", "medium", [56.0] * 8), # major, lower tier, medium measurement and range confidence
"lead_knee_flexion_release_deg": ("deg", "high", [75.0] * 8), # major, lower tier, high confidence range
}
result = run(series, discipline="pitching")
assert problem(result, "short_stride").severity == problem(result, "soft_front_leg").severity == "major"
assert result.eligible[0].key == "soft_front_leg"
def test_level_changes_the_range_and_a_missing_level_is_flagged():
series = {"stride_pct_height": ("%", "high", [49.5] * 6)}
assert not problem(run(series, level="hs_varsity"), "over_stride").eligible
college = analysis.analyze("hitting", "college", measurements(series=series)["reps"])
assert college.level == "college" and not college.level_assumed
unknown = analysis.analyze("hitting", None, measurements(series=series)["reps"])
assert unknown.level == "hs_varsity" and unknown.level_assumed
assert kb.normalise_level("middle_school") == ("hs_varsity", True)
def test_empty_session_is_safe():
result = analysis.analyze("hitting", "hs_varsity", [])
assert result.metrics == [] and result.eligible == []