github-actions[bot]
Automated Deploy: a19ede424a80b7b8d7f6978585141d1bb45de69c
326d3cc
Raw History Blame Contribute Delete
7.66 kB
"""Continuous projected curves, then summaries with independent evidence gates."""
import numpy as np
from .contracts import Metric, RTMW_CORE
def flexion_degrees(a, b, c):
a, b, c = np.asarray(a, float), np.asarray(b, float), np.asarray(c, float)
u, v = a-b, c-b
denominator = np.linalg.norm(u, axis=-1)*np.linalg.norm(v, axis=-1)
cosine = np.sum(u*v, axis=-1)/np.where(denominator > 1e-9, denominator, np.nan)
return 180-np.degrees(np.arccos(np.clip(cosine, -1, 1)))
def derivative(values, times):
"""Differentiate only contiguous finite increasing intervals; do not bridge gaps."""
values, times = np.asarray(values, float), np.asarray(times, float)
result = np.full_like(values, np.nan)
valid = np.isfinite(times) & np.isfinite(values).reshape(len(times), -1).all(axis=1)
start = 0
for k in range(len(times)+1):
boundary = k == len(times) or not valid[k] or (k > start and times[k] <= times[k-1])
if boundary:
if k-start >= 3:
result[start:k] = np.gradient(values[start:k], times[start:k], axis=0, edge_order=2)
start = k+1 if k < len(times) and not valid[k] else k
return result
def continuous_curves(observations, capture):
frames = observations["frames"]
n = len(frames)
body = np.array([f["body_points"] for f in frames], dtype=float)
for i, f in enumerate(frames):
for j, state in enumerate(f["body_states"]):
if state not in {"model_inferred", "image_supported", "manual"}:
body[i, j] = np.nan
bat = np.full((n, 2, 2), np.nan)
for i, f in enumerate(frames):
qualified=f["bat"].get("method")=="qualified_endpoint_cnn_v1"
if f["bat"]["points"] is not None and all(s in ({"image_supported", "manual", "model_inferred"} if qualified else {"image_supported", "manual"}) for s in f["bat"]["states"]):
bat[i] = f["bat"]["points"]
time = np.array([f["physical_s"] for f in capture["frames"]], dtype=float)
curves = {"physical_time_s": time, "body_pixels": body, "bat_endpoints_pixels": bat}
for side in ("left", "right"):
for joint, names in (("elbow", ("shoulder", "elbow", "wrist")), ("knee", ("hip", "knee", "ankle"))):
a, b, c = [body[:, RTMW_CORE[f"{side}_{name}"]] for name in names]
curves[f"{side}_{joint}_projected_flexion_deg"] = flexion_degrees(a, b, c)
curves[f"{side}_hand_path_pixels"] = body[:, RTMW_CORE[f"{side}_wrist"]]
curves["projected_ankle_span_px"] = np.linalg.norm(body[:, 15]-body[:, 16], axis=1)
shaft = bat[:, 1]-bat[:, 0]
curves["projected_bat_shaft_angle_deg"] = np.degrees(np.arctan2(-shaft[:, 1], shaft[:, 0]))
if capture["physical_clock_known"] and capture["camera_stability"] == "fixed_verified" and not any(
{"duplicate_pts", "nonmonotonic_pts", "duplicate_image", "missing_pts", "timestamp_gap_or_variable_cadence"} & set(f["flags"]) for f in capture["frames"]):
for side in ("left", "right"):
curves[f"{side}_hand_projected_velocity_px_s"] = derivative(curves[f"{side}_hand_path_pixels"], time)
return curves
def summarize(curves, observations, capture, events):
output = []
timing_source = capture["timing_source"].get("kind", "unknown")
def sources(indices, landmark_indices):
return sorted({observations["frames"][int(i)]["body_states"][j]
for i in indices for j in landmark_indices
if observations["frames"][int(i)]["body_states"][j] in {"manual", "model_inferred", "image_supported"}})
for name in [k for k in curves if k.endswith("flexion_deg") or k == "projected_ankle_span_px"]:
v = curves[name]
indices = np.flatnonzero(np.isfinite(v))
if name == "projected_ankle_span_px":
used = [15,16]
else:
side, joint = name.split("_")[:2]
names = ("shoulder", "elbow", "wrist") if joint == "elbow" else ("hip", "knee", "ankle")
used = [RTMW_CORE[f"{side}_{j}"] for j in names]
provenance = sources(indices, used)
output.append(Metric(name+"_median", "1.0", float(np.median(v[indices])) if len(indices) else None,
"deg_projected" if name.endswith("deg") else "px", "supported" if len(indices) else "unsupported",
provenance, indices.tolist(), "oriented_image_projection", timing_source,
unavailable_reason=None if len(indices) else "missing_joint_observations"))
bat_angle = curves["projected_bat_shaft_angle_deg"]
indices = np.flatnonzero(np.isfinite(bat_angle))
# Median of directional angles must use circular arithmetic across ±180°.
value = None
if len(indices):
rad = np.radians(bat_angle[indices])
value = float(np.degrees(np.arctan2(np.sin(rad).mean(), np.cos(rad).mean())))
output.append(Metric("projected_bat_shaft_angle_circular_mean", "1.0", value, "deg_projected",
"supported" if value is not None else "unsupported",
sorted({s for i in indices for s in observations["frames"][i]["bat"]["states"]}), indices.tolist(),
"image_plane_x_right_y_up", timing_source,
unavailable_reason=None if value is not None else "no_supported_bat_endpoints"))
for side in ("left", "right"):
path = curves[f"{side}_hand_path_pixels"]
valid = np.isfinite(path).all(axis=1)
reason = None
if capture["camera_stability"] != "fixed_verified":
reason = "camera_stability_unverified"
elif not valid.all() or len(path) < 2:
reason = "incomplete_hand_path"
distance = float(np.linalg.norm(np.diff(path, axis=0), axis=1).sum()) if reason is None else None
output.append(Metric(f"{side}_hand_projected_path_length", "1.0", distance, "px",
"supported" if reason is None else "unsupported", sources(np.flatnonzero(valid), [RTMW_CORE[f"{side}_wrist"]]),
np.flatnonzero(valid).tolist(), "fixed_camera_image_plane", timing_source, reason))
velocity = curves.get(f"{side}_hand_projected_velocity_px_s")
indices = np.flatnonzero(np.isfinite(velocity).all(axis=1)) if velocity is not None else np.array([], int)
reason = None if len(indices) else ("physical_clock_unknown" if not capture["physical_clock_known"] else "timing_or_camera_or_observation_support_failed")
speed = float(np.linalg.norm(velocity[indices], axis=1).max()) if len(indices) else None
output.append(Metric(f"{side}_hand_peak_projected_speed", "1.0", speed, "px/s",
"supported" if speed is not None else "unsupported", sources(indices, [RTMW_CORE[f"{side}_wrist"]]), indices.tolist(),
"fixed_camera_image_plane", timing_source, reason))
for name, unit, reason in (
("ground_plane_stride_length", "m", "ground_calibration_and_event_not_qualified"),
("pelvis_thorax_heading_separation", "deg", "anatomical_3d_method_not_qualified"),
("pelvis_peak_angular_velocity", "deg/s", "anatomical_3d_method_not_qualified"),
("bat_sweet_spot_speed_at_contact", "m/s", "independent_bat_3d_geometry_not_qualified"),
("bat_attack_angle_at_contact", "deg", "independent_bat_3d_geometry_not_qualified"),
("exit_velocity", "m/s", "outcome_module_not_supported"),
):
output.append(Metric(name, "1.0", None, unit, "unsupported", [], [], "not_established", timing_source, reason))
return output