Spaces:
Running on T4
Running on T4
Download tools/validate_pitching_reference.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.88 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/validate_pitching_reference.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tools/validate_pitching_reference.py
-
curl -L -o validate_pitching_reference.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/validate_pitching_reference.py
5.88 kB
| """Compare delivered 3D joint centres with a paired Theia C3D, without fitting to predictions. | |
| This is an inter-method comparison, not marker-based ground truth. Requires ezc3d. | |
| Run: python tools/validate_pitching_reference.py --reference-dir PATH --alignment PATH | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from baseball_batting.pitching_geometry import curves | |
| from baseball_batting.sam_motion import MHR | |
| SEGMENTS = {f"{side}_{joint}": f"{short}_{segment}_4X4" | |
| for side, short in [("left", "l"), ("right", "r")] | |
| for joint, segment in [("hip", "thigh"), ("knee", "shank"), ("ankle", "foot"), | |
| ("shoulder", "uarm"), ("elbow", "larm"), ("wrist", "hand")]} | |
| def comparison(predicted, reference): | |
| valid = np.isfinite(predicted) & np.isfinite(reference) | |
| delta = predicted[valid] - reference[valid] | |
| if not len(delta): | |
| return {"n": 0} | |
| return {"n": int(len(delta)), "bias": float(np.mean(delta)), | |
| "mae": float(np.mean(abs(delta))), "median_absolute_difference": float(np.median(abs(delta))), | |
| "p95_absolute_difference": float(np.percentile(abs(delta), 95)), | |
| "rmse": float(np.sqrt(np.mean(delta ** 2)))} | |
| def compare(directory, alignment_path): | |
| import ezc3d | |
| manifest = json.loads((directory / "manifest.json").read_text()) | |
| provenance = json.loads((directory / "provenance.json").read_text()) | |
| frames = np.asarray(provenance["original_frame_indices"], int) | |
| records = [json.loads(line) for line in (directory / "motion.jsonl").read_text().splitlines()] | |
| assert len(records) == len(frames), "Reference mapping must cover every delivered frame" | |
| predicted = np.full((len(frames), 70, 3), np.nan) | |
| export_rotation = np.asarray(manifest["coordinates"]["camera_to_export_rotation"]) | |
| for i, row in enumerate(records): | |
| assert row["source_frame_index"] == i | |
| for name in SEGMENTS: | |
| j = row["joints"][name] | |
| if j["position"] is not None and j["status"] == "estimated": | |
| predicted[i, MHR[name]] = np.asarray(j["position"]) @ export_rotation | |
| alignment = json.loads(alignment_path.read_text()) | |
| rotation = np.asarray(alignment["rotation"]) | |
| c = ezc3d.c3d(str(directory / "theia.c3d")) | |
| labels = c["parameters"]["ROTATION"]["LABELS"]["value"] | |
| raw = c["data"]["rotations"] | |
| opts = manifest["pipeline"].get("calculation_inputs", manifest["pipeline"]["inputs"]) | |
| hand = opts["handedness"] | |
| estimate = curves(predicted, hand, opts.get("up_vector")) | |
| output = {"scope": "Single trial, single camera; SAM3D vs paired Theia markerless reference; not absolute accuracy", | |
| "source_provenance": provenance, "alignment_sha256": hashlib.sha256(alignment_path.read_bytes()).hexdigest(), | |
| "analysis_id": manifest["analysis_id"], "model": manifest.get("model"), | |
| "alignment_fitted_to_model_predictions": False, "offset_sensitivity": {}, | |
| "limitations": ["Theia is another pose estimator, not marker-based ground truth.", | |
| "Published camera alignment is provisional and was fitted using all eight cameras.", | |
| "Body centre definitions can differ between models.", | |
| "No independent physical synchronization validation; offsets zero and one are compared.", | |
| "One athlete, camera and delivery cannot validate general pitching accuracy."]} | |
| for offset in (0, 1): | |
| ref = np.full_like(predicted, np.nan) | |
| for name, label in SEGMENTS.items(): | |
| ref[:, MHR[name]] = raw[:3, 3, labels.index(label), frames + offset].T * .001 | |
| values = curves(ref, hand, [0, 0, 1]) | |
| metrics = {} | |
| for key in ("knee", "elbow", "torso", "separation", "span"): | |
| a, b = estimate[key], values[key] | |
| if key == "separation": | |
| delta = (a - b + 180) % 360 - 180 | |
| metrics[key] = comparison(delta, np.zeros_like(delta)) | |
| else: | |
| metrics[key] = comparison(a, b) | |
| ref_camera = ref @ rotation.T | |
| joint_indices = [MHR[name] for name in SEGMENTS] | |
| pred_root = (predicted[:, MHR["left_hip"]] + predicted[:, MHR["right_hip"]]) / 2 | |
| ref_root = (ref_camera[:, MHR["left_hip"]] + ref_camera[:, MHR["right_hip"]]) / 2 | |
| errors = np.linalg.norm((predicted - pred_root[:, None])[:, joint_indices] - | |
| (ref_camera - ref_root[:, None])[:, joint_indices], axis=-1) * 100 | |
| per_joint = {name: comparison(errors[:, i], np.zeros(len(frames))) for i, name in enumerate(SEGMENTS)} | |
| output["offset_sensitivity"][str(offset)] = {"angle_differences_deg_distance_cm": metrics, | |
| "root_relative_joint_difference_cm": per_joint, | |
| "events": {event: {key: {"model": float(estimate[key][index]), "reference": float(values[key][index])} | |
| for key in ("knee", "elbow", "torso", "separation") | |
| if np.isfinite(estimate[key][index]) and np.isfinite(values[key][index])} | |
| for event, index in {"foot_strike": opts["windows"][0]["foot_strike_frame"], | |
| "release": opts["release_frame"]}.items()}} | |
| (directory / "reference-comparison.json").write_text(json.dumps(output, indent=2, allow_nan=False) + "\n") | |
| return output | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--reference-dir", type=Path, required=True) | |
| parser.add_argument("--alignment", type=Path, required=True) | |
| args = parser.parse_args() | |
| result = compare(args.reference_dir, args.alignment) | |
| print(json.dumps(result["offset_sensitivity"], indent=2)) | |