github-actions[bot] commited on
Commit
1c5e162
·
1 Parent(s): 17166a9

Automated Deploy: bdfa1cf3012476c93813fcefeba6aad4a1639d18

Browse files
AI-coach-agent/src/ai_coach/knowledge/swing_metrics.yaml CHANGED
@@ -11,7 +11,7 @@
11
  # Drill ids come from drills.yaml (hitting). `drill_review`: spec = the choice shown in docs/SWING_REPORT_API.md;
12
  # needs_coach_review = a sensible pick from the starter library that a coach must confirm.
13
  # Text rules: plain words, no numbers, no good/bad judgements (guardrails.BANNED).
14
- version: "1.1" # coaching_rules_version
15
  measurement_definitions_version: "1.1"
16
 
17
  groups:
@@ -426,8 +426,8 @@ reasons:
426
  limitation: The body points we need were not clear enough in the video.
427
  report: Some body points were not clear enough in the video to measure.
428
  ground_plane_unknown:
429
- limitation: We could not find the ground in the video.
430
- report: The ground could not be found in the video, so some results are missing.
431
  scale_is_model_estimated:
432
  limitation: Distance is estimated from the video, so treat this as approximate.
433
  report: Distances are estimated from the video and are approximate.
@@ -441,8 +441,8 @@ reasons:
441
  limitation: Part of your body was hidden in the video.
442
  report: Part of the body was hidden in the video, so some results are missing or approximate.
443
  temporal_inconsistency:
444
- limitation: The movement did not line up from frame to frame, so treat this as approximate.
445
- report: The movement did not line up from frame to frame, so some results are approximate.
446
 
447
  capture_time_unknown:
448
  limitation: We do not know the true speed of this clip.
@@ -479,7 +479,13 @@ text:
479
  group_unavailable_by_reason:
480
  contact_not_verified: We could not confirm the moment the bat met the ball, so this part was not measured.
481
  contact_not_applicable: This swing had no ball contact, so this part was not measured.
482
- group_not_rated: We have only approximate results here, so this part is not scored.
 
 
 
 
 
 
483
  group_on_target: Everything we measured in this part of your swing is in the typical range.
484
  headline_focus: "{subject} is the area to work on."
485
  headline_all_on_target: Everything we could rate in this swing is in the typical range.
 
11
  # Drill ids come from drills.yaml (hitting). `drill_review`: spec = the choice shown in docs/SWING_REPORT_API.md;
12
  # needs_coach_review = a sensible pick from the starter library that a coach must confirm.
13
  # Text rules: plain words, no numbers, no good/bad judgements (guardrails.BANNED).
14
+ version: "1.2" # coaching_rules_version
15
  measurement_definitions_version: "1.1"
16
 
17
  groups:
 
426
  limitation: The body points we need were not clear enough in the video.
427
  report: Some body points were not clear enough in the video to measure.
428
  ground_plane_unknown:
429
+ limitation: We could not reliably tell which way is upright.
430
+ report: We could not confirm which way is upright, so some results are missing.
431
  scale_is_model_estimated:
432
  limitation: Distance is estimated from the video, so treat this as approximate.
433
  report: Distances are estimated from the video and are approximate.
 
441
  limitation: Part of your body was hidden in the video.
442
  report: Part of the body was hidden in the video, so some results are missing or approximate.
443
  temporal_inconsistency:
444
+ limitation: The camera or tracked body points shifted. This result may be missing or rough.
445
+ report: The camera or tracked body points shifted. Some results are missing or rough.
446
 
447
  capture_time_unknown:
448
  limitation: We do not know the true speed of this clip.
 
479
  group_unavailable_by_reason:
480
  contact_not_verified: We could not confirm the moment the bat met the ball, so this part was not measured.
481
  contact_not_applicable: This swing had no ball contact, so this part was not measured.
482
+ ground_plane_unknown: We could not confirm which way is upright. These moves need that check, so this part is not scored.
483
+ temporal_inconsistency: Camera movement or shifts in body tracking prevent a score for this part of the swing.
484
+ required_landmarks_unusable: The body points needed for this part were not clear enough to score.
485
+ required_event_unavailable: A swing moment needed for this part could not be confirmed, so it is not scored.
486
+ capture_time_unknown: We do not know the true clip speed, so this part is not scored.
487
+ follow_through_not_recorded: The clip ends too soon after contact to score this part.
488
+ group_not_rated: These results lack a usable reference for a score.
489
  group_on_target: Everything we measured in this part of your swing is in the typical range.
490
  headline_focus: "{subject} is the area to work on."
491
  headline_all_on_target: Everything we could rate in this swing is in the typical range.
AI-coach-agent/src/ai_coach/swing_report/service.py CHANGED
@@ -263,6 +263,18 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
263
  text_meta = {"text_source": "rules", "model": None, "cache_hit": False,
264
  "fallback_reason": "no_rated_measurements"}
265
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  report["meta"] = {
267
  "generated_at": (now or datetime.now(UTC)).astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
268
  "request_id": request_id, **text_meta, "prompt_version": PROMPT_VERSION,
 
263
  text_meta = {"text_source": "rules", "model": None, "cache_hit": False,
264
  "fallback_reason": "no_rated_measurements"}
265
 
266
+ # Keep coverage factual even when a model rewrites the finding. A group label does
267
+ # not mean every measurement within that phase contributed to its score.
268
+ partial_metrics = False
269
+ for g in groups:
270
+ members = [by_id[key] for key in g["metric_ids"]]
271
+ if g["score"] is not None and any(m["score"] is None for m in members):
272
+ g["summary"] += " This score covers only part of this phase."
273
+ partial_metrics = True
274
+ if partial_metrics:
275
+ report["data_quality"].append({"code": "partial_measurement_coverage", "severity": "warning",
276
+ "text": "Some group scores use only part of the planned measurements. Missing results do not count as zero."})
277
+
278
  report["meta"] = {
279
  "generated_at": (now or datetime.now(UTC)).astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
280
  "request_id": request_id, **text_meta, "prompt_version": PROMPT_VERSION,
AI-coach-agent/tests/test_swing_report_report.py CHANGED
@@ -94,7 +94,7 @@ def test_spec_example():
94
  assert meta["text_source"] == "rules" and meta["model"] is None and meta["fallback_reason"] == "llm_not_configured"
95
  assert meta["request_id"] == "req_1" and meta["prompt_version"].startswith("swing-report-v1-")
96
  assert (meta["input_schema_version"], meta["measurement_definitions_version"], meta["benchmark_registry_version"],
97
- meta["coaching_rules_version"]) == ("1.0", "1.0", "2026-10-31.1", "1.1")
98
  assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", meta["generated_at"])
99
 
100
 
@@ -106,6 +106,31 @@ def test_completeness_and_order():
106
  assert [m["metric_id"] for m in r["measurements"]] == METRICS
107
 
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  def test_invalid_payload_raises_with_paths():
110
  p = payload()
111
  p["measurements"][1]["reasons"] = []
 
94
  assert meta["text_source"] == "rules" and meta["model"] is None and meta["fallback_reason"] == "llm_not_configured"
95
  assert meta["request_id"] == "req_1" and meta["prompt_version"].startswith("swing-report-v1-")
96
  assert (meta["input_schema_version"], meta["measurement_definitions_version"], meta["benchmark_registry_version"],
97
+ meta["coaching_rules_version"]) == ("1.0", "1.0", "2026-10-31.1", "1.2")
98
  assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", meta["generated_at"])
99
 
100
 
 
106
  assert [m["metric_id"] for m in r["measurements"]] == METRICS
107
 
108
 
109
+ @pytest.mark.parametrize(("reason", "explanation"), [
110
+ ("ground_plane_unknown", "upright"),
111
+ ("temporal_inconsistency", "Camera movement"),
112
+ ("required_landmarks_unusable", "body points"),
113
+ ])
114
+ def test_missing_group_scores_explain_the_shared_cause(reason, explanation):
115
+ p = payload()
116
+ for m in p["measurements"]:
117
+ m.update(value=None, status="unavailable", confidence=None, reasons=[reason])
118
+ r = build(p)
119
+ assert explanation in by_group(r)["stride"]["summary"]
120
+ assert r["overall_score"] is None
121
+
122
+
123
+ def test_partially_measured_group_does_not_claim_complete_coverage():
124
+ p = payload()
125
+ p["measurements"][0].update(value=None, status="unavailable", confidence=None,
126
+ reasons=["ground_plane_unknown"])
127
+ r = build(p)
128
+ g = by_group(r)["stride"]
129
+ assert g["score"] == 100 # missing separation is excluded, not counted as zero
130
+ assert "only part of this phase" in g["summary"]
131
+ assert "partial_measurement_coverage" in {n["code"] for n in r["data_quality"]}
132
+
133
+
134
  def test_invalid_payload_raises_with_paths():
135
  p = payload()
136
  p["measurements"][1]["reasons"] = []
baseball_batting/motion_coach.py CHANGED
@@ -57,7 +57,7 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
57
  curves, reference, oriented = frame_curves(corrected['points_relative'], video_times,
58
  corrected['boundary'], options.sam_options(), baseline)
59
 
60
- def quality(indices, names):
61
  ids = [i for i in indices if i is not None]
62
  joints = [MHR[name] for name in names]
63
  selected = np.ix_(ids, joints)
@@ -65,11 +65,11 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
65
  reasons = []
66
  if ids and not corrected['valid'][selected].all():
67
  reasons.append('required_landmarks_unusable')
68
- if options.up_vector is None:
69
  reasons.append('ground_plane_unknown')
70
- if options.camera_stability != 'fixed_verified':
71
  reasons.append('temporal_inconsistency')
72
- if reference == 'degenerate_analysis_axis':
73
  reasons.append('required_landmarks_unusable')
74
  warnings = []
75
  if ids and (corrected['boundary'][selected].any() or interpolated):
@@ -100,7 +100,7 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
100
  missing.append('required_landmarks_unusable')
101
  return result(model, value, missing, selected_event.reasons, interpolated, warnings)
102
 
103
- def add_interval(metric, evaluate, indices, names):
104
  if metric.value is None or any(i is None for i in indices):
105
  return metric
106
  from itertools import product
@@ -110,7 +110,7 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
110
  if len(ids) > 1 and ids[0] >= ids[-1]:
111
  continue
112
  checked = list(range(ids[0], ids[-1] + 1)) if len(ids) > 1 else ids
113
- if quality(checked, names)[1]:
114
  return metric # A partial neighborhood cannot bound event sensitivity.
115
  value = evaluate(*ids)
116
  if not np.isfinite(value):
@@ -170,14 +170,18 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
170
  if oriented is not None:
171
  lean = inclination((oriented[:, 9] + oriented[:, 10]) / 2,
172
  (oriented[:, 5] + oriented[:, 6]) / 2, [0, 0, 1])
173
- if lead is not None:
174
- knee = knee_angle(oriented[:, MHR[lead + '_hip']], oriented[:, MHR[lead + '_knee']],
175
- oriented[:, MHR[lead + '_ankle']])
 
 
 
176
  event_map = {'stride_start': events.stride_start, 'front_foot_down': events.front_foot_down,
177
  'contact': events.contact, 'follow_through': events.follow_through}
178
- def extra(metric_id, group, reference_name, names, ids, event_ids, evaluate, *, lead_required=False):
 
179
  checked = list(range(ids[0], ids[-1] + 1)) if len(ids) == 2 and all(i is not None for i in ids) else ids
180
- interp, absent, warns = quality(checked, names)
181
  event_reasons = []
182
  for key in event_ids:
183
  ev = event_map[key]
@@ -198,7 +202,7 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
198
  rounded = float(wrap180(rounded))
199
  row = result(lambda **fields: ExtendedMeasurement(**common, **fields), rounded,
200
  absent, event_reasons, interp, warns)
201
- return add_interval(row, evaluate, ids, names)
202
  extended = [
203
  extra('torso_inclination_at_stride_start', 'balance_load', 'torso_angle_from_vertical',
204
  torso_names, [stride_start], ['stride_start'], lambda i: lean[i]),
@@ -209,7 +213,8 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
209
  lambda a, b: rotation_amount(curves['hip_heading_deg'], a, b)),
210
  extra('lead_knee_extension_to_contact', 'power_move', 'change_in_3d_lead_knee_angle',
211
  [lead + '_' + part for part in ('hip', 'knee', 'ankle')] if lead else hip_names,
212
- [landing, contact], ['front_foot_down', 'contact'], lambda a, b: knee[b] - knee[a], lead_required=True),
 
213
  extra('torso_inclination_at_contact', 'contact_follow_through', 'torso_angle_from_vertical',
214
  torso_names, [contact], ['contact'], lambda i: lean[i]),
215
  extra('shoulder_rotation_after_contact', 'contact_follow_through', 'absolute_net_horizontal_rotation',
 
57
  curves, reference, oriented = frame_curves(corrected['points_relative'], video_times,
58
  corrected['boundary'], options.sam_options(), baseline)
59
 
60
+ def quality(indices, names, requires_orientation=True):
61
  ids = [i for i in indices if i is not None]
62
  joints = [MHR[name] for name in names]
63
  selected = np.ix_(ids, joints)
 
65
  reasons = []
66
  if ids and not corrected['valid'][selected].all():
67
  reasons.append('required_landmarks_unusable')
68
+ if requires_orientation and options.up_vector is None:
69
  reasons.append('ground_plane_unknown')
70
+ if requires_orientation and options.camera_stability != 'fixed_verified':
71
  reasons.append('temporal_inconsistency')
72
+ if requires_orientation and reference == 'degenerate_analysis_axis':
73
  reasons.append('required_landmarks_unusable')
74
  warnings = []
75
  if ids and (corrected['boundary'][selected].any() or interpolated):
 
100
  missing.append('required_landmarks_unusable')
101
  return result(model, value, missing, selected_event.reasons, interpolated, warnings)
102
 
103
+ def add_interval(metric, evaluate, indices, names, requires_orientation=True):
104
  if metric.value is None or any(i is None for i in indices):
105
  return metric
106
  from itertools import product
 
110
  if len(ids) > 1 and ids[0] >= ids[-1]:
111
  continue
112
  checked = list(range(ids[0], ids[-1] + 1)) if len(ids) > 1 else ids
113
+ if quality(checked, names, requires_orientation)[1]:
114
  return metric # A partial neighborhood cannot bound event sensitivity.
115
  value = evaluate(*ids)
116
  if not np.isfinite(value):
 
170
  if oriented is not None:
171
  lean = inclination((oriented[:, 9] + oriented[:, 10]) / 2,
172
  (oriented[:, 5] + oriented[:, 6]) / 2, [0, 0, 1])
173
+ if lead is not None:
174
+ # An intrinsic joint angle is unchanged by camera rotation, translation or uniform scale.
175
+ # Unlike horizontal headings, it does not require an estimated vertical reference.
176
+ native = corrected['points_relative']
177
+ knee = knee_angle(native[:, MHR[lead + '_hip']], native[:, MHR[lead + '_knee']],
178
+ native[:, MHR[lead + '_ankle']])
179
  event_map = {'stride_start': events.stride_start, 'front_foot_down': events.front_foot_down,
180
  'contact': events.contact, 'follow_through': events.follow_through}
181
+ def extra(metric_id, group, reference_name, names, ids, event_ids, evaluate, *, lead_required=False,
182
+ requires_orientation=True):
183
  checked = list(range(ids[0], ids[-1] + 1)) if len(ids) == 2 and all(i is not None for i in ids) else ids
184
+ interp, absent, warns = quality(checked, names, requires_orientation)
185
  event_reasons = []
186
  for key in event_ids:
187
  ev = event_map[key]
 
202
  rounded = float(wrap180(rounded))
203
  row = result(lambda **fields: ExtendedMeasurement(**common, **fields), rounded,
204
  absent, event_reasons, interp, warns)
205
+ return add_interval(row, evaluate, ids, names, requires_orientation)
206
  extended = [
207
  extra('torso_inclination_at_stride_start', 'balance_load', 'torso_angle_from_vertical',
208
  torso_names, [stride_start], ['stride_start'], lambda i: lean[i]),
 
213
  lambda a, b: rotation_amount(curves['hip_heading_deg'], a, b)),
214
  extra('lead_knee_extension_to_contact', 'power_move', 'change_in_3d_lead_knee_angle',
215
  [lead + '_' + part for part in ('hip', 'knee', 'ankle')] if lead else hip_names,
216
+ [landing, contact], ['front_foot_down', 'contact'], lambda a, b: knee[b] - knee[a],
217
+ lead_required=True, requires_orientation=False),
218
  extra('torso_inclination_at_contact', 'contact_follow_through', 'torso_angle_from_vertical',
219
  torso_names, [contact], ['contact'], lambda i: lean[i]),
220
  extra('shoulder_rotation_after_contact', 'contact_follow_through', 'absolute_net_horizontal_rotation',
docs/motion-coach-v1.1.md CHANGED
@@ -28,10 +28,14 @@ The backend saves revised marks and the report together using these frame indice
28
 
29
  The existing landmark, vertical-reference, interpolation, scale and camera checks still apply. Slow background drift is now checked against an anchor image as well as consecutive images. Three corroborating anchor displacements above the larger of 1% of image size or three times the adjacent-motion threshold contradict a fixed-camera declaration. Unsigned per-frame movement is never summed, so tracking noise cannot accumulate into a false drift estimate. This is an image-motion diagnostic, not camera calibration. A caller's original declaration is retained in the request; conflicting evidence changes the effective analysis status.
30
 
 
 
31
  ## Scores and advice
32
 
33
  The references describe recorded athletes, not ideal technique or guaranteed performance. Each metric uses the existing percentile-distance score. Group scores average rated metrics, including limited metrics; overall score averages rated groups. Limited inputs make their scores tentative. Missing groups are explicitly listed, and partial coverage adds a warning explaining the overall score's denominator.
34
 
 
 
35
  Where neighboring samples are usable, `value_interval` spans evaluations with event marks shifted by one source frame in either direction. The coach computes `score_interval` across that range, including scoring breakpoints. These are event-sensitivity bounds, **not** confidence intervals or bounds on total model error. Missing neighboring evidence or a signed-angle wrap prevents publishing a misleading linear interval. A range that changes rating category or spans at least 20 score points cannot determine the corrective focus or a technique tip.
36
 
37
  Unknown drill context and dry swings receive descriptions of the reference comparisons, without technique corrections. Their text is deterministic, so a language model cannot turn a walk-through drill into an instruction to shorten the stride. Conflicting profile and payload batting sides also suppress technique advice and add `batting_hand_conflict`; scores still identify which analysis side was used. The engine does not infer batting side from video.
 
28
 
29
  The existing landmark, vertical-reference, interpolation, scale and camera checks still apply. Slow background drift is now checked against an anchor image as well as consecutive images. Three corroborating anchor displacements above the larger of 1% of image size or three times the adjacent-motion threshold contradict a fixed-camera declaration. Unsigned per-frame movement is never summed, so tracking noise cannot accumulate into a false drift estimate. This is an image-motion diagnostic, not camera calibration. A caller's original declaration is retained in the request; conflicting evidence changes the effective analysis status.
30
 
31
+ Lead-knee extension is an intrinsic 3D joint-angle change. It does not require a fixed camera or a vertical reference, because rotating or translating the coordinate frame does not change the angle between the thigh and lower leg. It still requires usable hip, knee and ankle positions and valid event marks, and remains a model estimate. Missing calibration therefore blocks the horizontal/world-oriented measurements without discarding this independent measurement.
32
+
33
  ## Scores and advice
34
 
35
  The references describe recorded athletes, not ideal technique or guaranteed performance. Each metric uses the existing percentile-distance score. Group scores average rated metrics, including limited metrics; overall score averages rated groups. Limited inputs make their scores tentative. Missing groups are explicitly listed, and partial coverage adds a warning explaining the overall score's denominator.
36
 
37
+ Unrated group summaries explain shared causes such as an uncertain upright direction, camera/tracking instability, missing body points or missing event marks. A scored group with unavailable members states that it covers only part of the phase; missing values never count as zero.
38
+
39
  Where neighboring samples are usable, `value_interval` spans evaluations with event marks shifted by one source frame in either direction. The coach computes `score_interval` across that range, including scoring breakpoints. These are event-sensitivity bounds, **not** confidence intervals or bounds on total model error. Missing neighboring evidence or a signed-angle wrap prevents publishing a misleading linear interval. A range that changes rating category or spans at least 20 score points cannot determine the corrective focus or a technique tip.
40
 
41
  Unknown drill context and dry swings receive descriptions of the reference comparisons, without technique corrections. Their text is deterministic, so a language model cannot turn a walk-through drill into an instruction to shorten the stride. Conflicting profile and payload batting sides also suppress technique advice and add `batting_hand_conflict`; scores still identify which analysis side was used. The engine does not infer batting side from video.
tests/test_coach_contract_v1_1.py CHANGED
@@ -11,10 +11,11 @@ from baseball_batting.coach_geometry import inclination, knee_angle, rotation_am
11
  from baseball_batting.motion_coach import build_coach_payload
12
  from baseball_batting.motion_contract import MotionInput
13
  from baseball_batting.motion_refine import static_camera_conflict
 
14
  from test_sam_batting import pose
15
 
16
 
17
- def fixture_payload(*, hand='right', clock=True, camera='fixed_verified', transform=None):
18
  n = 31; p = pose(n); times = np.arange(n) / 30
19
  for i in range(n):
20
  a = np.radians(3 * i)
@@ -25,8 +26,8 @@ def fixture_payload(*, hand='right', clock=True, camera='fixed_verified', transf
25
  p = p @ transform.T; up = transform @ up
26
  corrected = {'points_relative': p, 'valid': np.isfinite(p).all(-1),
27
  'boundary': np.zeros((n, 70), bool), 'interpolated': np.zeros((n, 70), bool)}
28
- opts = MotionInput(single_swing=True, camera_stability=camera, up_vector=up.tolist(),
29
- up_source='Synthetic known vertical', handedness=hand,
30
  athlete={'athlete_id': 'fixture', 'batting_hand': hand}, context={'practice_type': 'tee'},
31
  contact_frame=20, windows=[{'start_frame': 0, 'end_frame': 30, 'stride_start_frame': 3, 'landing_frame': 10}])
32
  return build_coach_payload(opts, {'analysis_id': 'fixture', 'analysis_revision': 1}, corrected, times,
@@ -70,7 +71,54 @@ def test_unknown_clock_blocks_only_timed_follow_through_and_moving_camera_blocks
70
  assert len(unavailable) == 1 and unavailable[0]['metric_id'] == 'shoulder_rotation_after_contact'
71
  assert 'capture_time_unknown' in unavailable[0]['reasons']
72
  moving = fixture_payload(camera='moving')
73
- assert all(m['value'] is None for m in moving['measurements'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
 
76
  def test_old_three_metric_payload_still_builds_without_inventing_new_values():
 
11
  from baseball_batting.motion_coach import build_coach_payload
12
  from baseball_batting.motion_contract import MotionInput
13
  from baseball_batting.motion_refine import static_camera_conflict
14
+ from baseball_batting.sam_motion import MHR
15
  from test_sam_batting import pose
16
 
17
 
18
+ def fixture_payload(*, hand='right', clock=True, camera='fixed_verified', transform=None, vertical_known=True):
19
  n = 31; p = pose(n); times = np.arange(n) / 30
20
  for i in range(n):
21
  a = np.radians(3 * i)
 
26
  p = p @ transform.T; up = transform @ up
27
  corrected = {'points_relative': p, 'valid': np.isfinite(p).all(-1),
28
  'boundary': np.zeros((n, 70), bool), 'interpolated': np.zeros((n, 70), bool)}
29
+ opts = MotionInput(single_swing=True, camera_stability=camera, up_vector=up.tolist() if vertical_known else None,
30
+ up_source='Synthetic known vertical' if vertical_known else None, handedness=hand,
31
  athlete={'athlete_id': 'fixture', 'batting_hand': hand}, context={'practice_type': 'tee'},
32
  contact_frame=20, windows=[{'start_frame': 0, 'end_frame': 30, 'stride_start_frame': 3, 'landing_frame': 10}])
33
  return build_coach_payload(opts, {'analysis_id': 'fixture', 'analysis_revision': 1}, corrected, times,
 
71
  assert len(unavailable) == 1 and unavailable[0]['metric_id'] == 'shoulder_rotation_after_contact'
72
  assert 'capture_time_unknown' in unavailable[0]['reasons']
73
  moving = fixture_payload(camera='moving')
74
+ assert all(m['value'] is None for m in moving['measurements'] if m['metric_id'] != 'lead_knee_extension_to_contact')
75
+ assert next(m for m in moving['measurements'] if m['metric_id'] == 'lead_knee_extension_to_contact')['value'] == 0
76
+
77
+
78
+ def test_intrinsic_knee_angle_survives_unknown_vertical_and_camera_rotation():
79
+ rotation = np.array([[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]])
80
+ p = fixture_payload(vertical_known=False, camera='moving', transform=rotation)
81
+ assert not validate_payload(p)[1]
82
+ usable = [m for m in p['measurements'] if m['value'] is not None]
83
+ assert len(usable) == 1 and usable[0]['metric_id'] == 'lead_knee_extension_to_contact'
84
+ assert usable[0]['value'] == 0 and usable[0]['status'] == 'limited'
85
+ report = build_report(p, AthleteContext(level='college'), settings=Settings(_env_file=None, google_api_key=None))
86
+ assert [g['group'] for g in report['groups'] if g['score'] is not None] == ['power_move']
87
+ groups = {g['group']: g for g in report['groups']}
88
+ assert 'upright' in groups['balance_load']['summary']
89
+ assert 'only part of this phase' in groups['power_move']['summary']
90
+ assert 'partial_measurement_coverage' in {n['code'] for n in report['data_quality']}
91
+
92
+
93
+ @pytest.mark.parametrize('missing_joint', [None, 'left_hip', 'left_knee', 'left_ankle'])
94
+ def test_intrinsic_knee_change_under_time_varying_camera_requires_all_three_landmarks(missing_joint):
95
+ n = 31; times = np.arange(n) / 30; p = pose(n)
96
+ # A known 60-to-90 degree knee change between landing (10) and contact (20).
97
+ angles = np.radians(30 + 3 * np.arange(n))
98
+ p[:, MHR['left_knee']] = 0
99
+ p[:, MHR['left_hip']] = [0, 1, 0]
100
+ p[:, MHR['left_ankle']] = np.column_stack((np.sin(angles), np.cos(angles), np.zeros(n)))
101
+ for i in range(n):
102
+ a = .1 * i
103
+ rotation = np.array([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]])
104
+ p[i] = (1 + i / 100) * (p[i] @ rotation.T) + [i / 10, -i / 20, i / 30]
105
+ if missing_joint is not None:
106
+ p[15, MHR[missing_joint]] = np.nan
107
+ corrected = {'points_relative': p, 'valid': np.isfinite(p).all(-1),
108
+ 'boundary': np.zeros((n, 70), bool), 'interpolated': np.zeros((n, 70), bool)}
109
+ options = MotionInput(single_swing=True, camera_stability='moving', handedness='right',
110
+ athlete={'athlete_id': 'fixture', 'batting_hand': 'right'}, contact_frame=20,
111
+ windows=[{'start_frame': 0, 'end_frame': 30, 'stride_start_frame': 3, 'landing_frame': 10}])
112
+ payload = build_coach_payload(options, {'analysis_id': 'fixture', 'analysis_revision': 1},
113
+ corrected, times, times, []).model_dump(mode='json')
114
+ assert not validate_payload(payload)[1]
115
+ knee = next(m for m in payload['measurements'] if m['metric_id'] == 'lead_knee_extension_to_contact')
116
+ if missing_joint is None:
117
+ assert knee['value'] == pytest.approx(30)
118
+ assert knee['value_interval']['lower'] == pytest.approx(24)
119
+ assert knee['value_interval']['upper'] == pytest.approx(36)
120
+ else:
121
+ assert knee['value'] is None and knee['reasons'] == ['required_landmarks_unusable']
122
 
123
 
124
  def test_old_three_metric_payload_still_builds_without_inventing_new_values():
tests/test_motion_coach.py CHANGED
@@ -139,7 +139,8 @@ def test_unavailable_dependencies_do_not_invent_or_remove_other_metrics(mode):
139
  assert all(m['value'] is not None for k, m in rows.items() if k != 'shoulder_rotation_after_contact')
140
  assert rows['shoulder_rotation_after_contact']['reasons'] == ['required_event_unavailable', 'capture_time_unknown']
141
  if mode in ('unknown_up', 'moving_camera'):
142
- assert all(m['value'] is None for m in rows.values())
 
143
  if mode == 'missing_shoulder':
144
  assert rows['hip_shoulder_separation_at_foot_down']['value'] is None
145
  assert rows['stride_relative_length']['value'] is not None
@@ -314,7 +315,8 @@ def test_estimated_up_is_used_only_when_accepted_for_measurements(tmp_path, vide
314
  data = json.loads((job/'coach-payload.json').read_text())
315
  assert validate_payload(data)[1] == {}
316
  assert all((m['value'] is not None) == reliable for m in data['measurements']
317
- if m['metric_id'] != 'shoulder_rotation_after_contact')
 
318
  assert manifest.pipeline['inputs']['up_vector'] is None
319
  assert manifest.pipeline['calculation_inputs']['up_vector'] == ([0, -1, 0] if reliable else None)
320
 
 
139
  assert all(m['value'] is not None for k, m in rows.items() if k != 'shoulder_rotation_after_contact')
140
  assert rows['shoulder_rotation_after_contact']['reasons'] == ['required_event_unavailable', 'capture_time_unknown']
141
  if mode in ('unknown_up', 'moving_camera'):
142
+ assert all(m['value'] is None for k, m in rows.items() if k != 'lead_knee_extension_to_contact')
143
+ assert rows['lead_knee_extension_to_contact']['value'] is not None
144
  if mode == 'missing_shoulder':
145
  assert rows['hip_shoulder_separation_at_foot_down']['value'] is None
146
  assert rows['stride_relative_length']['value'] is not None
 
315
  data = json.loads((job/'coach-payload.json').read_text())
316
  assert validate_payload(data)[1] == {}
317
  assert all((m['value'] is not None) == reliable for m in data['measurements']
318
+ if m['metric_id'] not in ('shoulder_rotation_after_contact', 'lead_knee_extension_to_contact'))
319
+ assert next(m for m in data['measurements'] if m['metric_id'] == 'lead_knee_extension_to_contact')['value'] is not None
320
  assert manifest.pipeline['inputs']['up_vector'] is None
321
  assert manifest.pipeline['calculation_inputs']['up_vector'] == ([0, -1, 0] if reliable else None)
322