"""Explicit 35-DOF OpenSim kinematic proxy, weighted IK and sparse sequence refinement.""" from pathlib import Path import numpy as np from scipy.optimize import least_squares from scipy.spatial.transform import Rotation from .temporal3d import MHR_CORE from .motion import contiguous_segments, sparse_temporal_pattern from .storage import StageCache, digest, atomic_json, read_json, sha256_file def unit(vector): vector = np.asarray(vector, float) if np.linalg.norm(vector) < 1e-8: raise ValueError("Degenerate neutral segment frame") return vector/np.linalg.norm(vector) def pin_frame(axis, reference): z = unit(axis) x = np.asarray(reference)-z*np.dot(reference, z) if np.linalg.norm(x) < 1e-8: x = np.eye(3)[np.argmin(np.abs(z))]; x -= z*np.dot(x, z) x = unit(x) return np.column_stack([x, np.cross(z, x), z]) def model_spec(neutral, settings): """Landmark-derived origins/offsets are proxies, never assumed native rig centres.""" neutral = np.asarray(neutral, float) if neutral.shape != (70, 3) or not np.isfinite(neutral).all(): raise ValueError("Neutral MHR70 must contain 70 finite metre positions") p = {name: neutral[index] for name, index in MHR_CORE.items()} hip = (p["left_hip"]+p["right_hip"])/2 shoulders = (p["left_shoulder"]+p["right_shoulder"])/2 y = unit(shoulders-hip) x = unit(p["left_hip"]-p["right_hip"]) x = unit(x-y*np.dot(x, y)); z = unit(np.cross(x, y)) basis = np.column_stack([x, y, z]) bodies = {"pelvis": {"origin": hip.tolist(), "rotation": basis.tolist()}, "thorax": {"origin": shoulders.tolist(), "rotation": basis.tolist()}} joints, coordinates, markers = [], [], {} def joint(name, kind, parent, child, centre, frame): if child not in bodies: bodies[child] = {"origin": np.asarray(centre).tolist(), "rotation": basis.tolist()} parent_origin = np.zeros(3) if parent == "ground" else np.array(bodies[parent]["origin"]) parent_rotation = np.eye(3) if parent == "ground" else np.array(bodies[parent]["rotation"]) child_origin, child_rotation = np.array(bodies[child]["origin"]), np.array(bodies[child]["rotation"]) n = {"FreeJoint": 6, "BallJoint": 3, "PinJoint": 1, "UniversalJoint": 2}[kind] ids = list(range(len(coordinates), len(coordinates)+n)) for i in range(n): bounds = [-100, 100] if kind == "FreeJoint" and i >= 3 else settings["soft_coordinate_range_rad"] if kind == "UniversalJoint": bounds = settings["universal_range_rad"] coordinates.append({"name": name+"_"+str(i), "unit": "m" if kind == "FreeJoint" and i >= 3 else "rad", "range": bounds}) joints.append({"name": name, "kind": kind, "parent": parent, "child": child, "coordinates": ids, "parent_location": (parent_rotation.T@(centre-parent_origin)).tolist(), "child_location": (child_rotation.T@(centre-child_origin)).tolist(), "parent_orientation": (parent_rotation.T@frame).tolist(), "child_orientation": (child_rotation.T@frame).tolist()}) # Root at its neutral origin: the six coordinates encode changes from neutral. joint("root", "FreeJoint", "ground", "pelvis", hip, basis) joint("pelvis_thorax", "BallJoint", "pelvis", "thorax", (hip+shoulders)/2, basis) for side in ("left", "right"): hip_p, knee, ankle = [p[side+"_"+n] for n in ("hip", "knee", "ankle")] shoulder, elbow, wrist = [p[side+"_"+n] for n in ("shoulder", "elbow", "wrist")] joint(side+"_hip", "BallJoint", "pelvis", side+"_thigh", hip_p, basis) joint(side+"_knee", "PinJoint", side+"_thigh", side+"_shank", knee, pin_frame(x, y)) joint(side+"_ankle", "UniversalJoint", side+"_shank", side+"_foot", ankle, basis) joint(side+"_shoulder", "BallJoint", "thorax", side+"_upper_arm", shoulder, basis) # Flexion plane is defined explicitly in the neutral frame; no scapular DoF. hinge = np.cross(unit(elbow-shoulder), y) joint(side+"_elbow", "PinJoint", side+"_upper_arm", side+"_forearm", elbow, pin_frame(hinge, y)) joint(side+"_forearm_rotor", "PinJoint", side+"_forearm", side+"_rotor", elbow, pin_frame(wrist-elbow, y)) joint(side+"_wrist", "UniversalJoint", side+"_rotor", side+"_hand", wrist, basis) assignments = {"hip": "pelvis", "knee": side+"_thigh", "ankle": side+"_shank", "big_toe": side+"_foot", "small_toe": side+"_foot", "heel": side+"_foot", "shoulder": "thorax", "elbow": side+"_upper_arm", "wrist": side+"_rotor"} for part, body in assignments.items(): name = side+"_"+part markers[name] = {"body": body, "offset": (basis.T@(p[name]-bodies[body]["origin"])).tolist(), "mhr70_index": MHR_CORE[name]} # Dorsal hand regression proxies give wrist/rotor some orientation support. for name, index in ((side+"_index_mcp", 49 if side == "left" else 28), (side+"_little_mcp", 61 if side == "left" else 40)): markers[name] = {"body": side+"_hand", "offset": (basis.T@(neutral[index]-wrist)).tolist(), "mhr70_index": index} if len(coordinates) != 35: raise AssertionError("Model must have exactly 35 coordinates") return {"schema_version": "1.0", "model_id": settings["model_id"], "version": settings["version"], "bodies": bodies, "joints": joints, "coordinates": coordinates, "markers": markers, "source_kind": "model_regression_proxy", "independent_observation": False, "neutral_basis_definition": "x toward anatomical left; y cranial; z x cross y", "coordinate_definition": "primitive coordinates; named measurements derive from segment frames", "dynamics": "disabled; placeholder masses and inertia"} def forward_kinematics(spec, q): """Mirror the documented Free/Ball XYZ, Pin Z and Universal XY primitives.""" transforms = {"ground": (np.eye(3), np.zeros(3))} for j in spec["joints"]: r_parent, t_parent = transforms[j["parent"]] values = np.asarray(q)[j["coordinates"]] if j["kind"] in {"BallJoint", "FreeJoint"}: rotation = Rotation.from_euler("XYZ", values[:3]).as_matrix() elif j["kind"] == "PinJoint": rotation = Rotation.from_euler("Z", values[0]).as_matrix() else: rotation = Rotation.from_euler("XY", values).as_matrix() r = r_parent@j["parent_orientation"]@rotation@np.asarray(j["child_orientation"]).T shift = values[3:] if j["kind"] == "FreeJoint" else np.zeros(3) t = t_parent+r_parent@np.asarray(j["parent_location"])+r_parent@j["parent_orientation"]@shift-r@j["child_location"] transforms[j["child"]] = (r, t) markers = np.array([transforms[m["body"]][1]+transforms[m["body"]][0]@m["offset"] for m in spec["markers"].values()]) return markers, transforms def build_opensim(spec, path=None): import opensim as osim model = osim.Model(); model.setName(spec["model_id"]) bodies = {} def vec(v): return osim.Vec3(*map(float, v)) for name in spec["bodies"]: body = osim.Body(name, 1., osim.Vec3(0), osim.Inertia(1., 1., 1.)) model.addBody(body); bodies[name] = body for j in spec["joints"]: parent = model.getGround() if j["parent"] == "ground" else bodies[j["parent"]] joint = getattr(osim, j["kind"])(j["name"], parent, vec(j["parent_location"]), vec(Rotation.from_matrix(j["parent_orientation"]).as_euler("XYZ")), bodies[j["child"]], vec(j["child_location"]), vec(Rotation.from_matrix(j["child_orientation"]).as_euler("XYZ"))) for i, index in enumerate(j["coordinates"]): coordinate = joint.upd_coordinates(i) coordinate.setName(spec["coordinates"][index]["name"]) coordinate.setRangeMin(spec["coordinates"][index]["range"][0]) coordinate.setRangeMax(spec["coordinates"][index]["range"][1]) coordinate.setDefaultValue(0.) model.addJoint(joint) for name, marker in spec["markers"].items(): model.addMarker(osim.Marker(name, bodies[marker["body"]], vec(marker["offset"]))) model.finalizeConnections(); model.initSystem() if path: model.printToXML(str(path)) return model def trc(path, names, targets, times): n = len(times); dt = np.median(np.diff(times)) if n > 1 else 1. header = ["PathFileType\t4\t(X/Y/Z)\tmarkers.trc", "DataRate\tCameraRate\tNumFrames\tNumMarkers\tUnits\tOrigDataRate\tOrigDataStartFrame\tOrigNumFrames", f"{1/dt}\t{1/dt}\t{n}\t{len(names)}\tm\t{1/dt}\t1\t{n}", "Frame#\tTime\t"+"\t".join(name+"\t\t" for name in names), "\t\t"+"\t".join(f"X{i+1}\tY{i+1}\tZ{i+1}" for i in range(len(names))), ""] for i, (row, time) in enumerate(zip(targets, times)): header.append(f"{i+1}\t{time:.10f}\t"+"\t".join(f"{v:.10f}" for v in row.reshape(-1))) Path(path).write_text("\n".join(header)+"\n") def weighted_ik(model, spec, targets, weights, times, workdir): import opensim as osim names = list(spec["markers"]) neutral, _ = forward_kinematics(spec, np.zeros(35)) safe = np.where(np.isfinite(targets), targets, neutral[None]) marker_file = Path(workdir)/"ik_targets.trc"; trc(marker_file, names, safe, times) marker_weights = osim.SetMarkerWeights() supported=np.flatnonzero((weights>0).sum(axis=1)>=6) if not len(supported):return np.full((len(times),35),np.nan) first=int(supported[0]) for j,name in enumerate(names): marker_weights.cloneAndAppend(osim.MarkerWeight(name, float(weights[first,j]))) reference = osim.MarkersReference(str(marker_file), marker_weights) solver = osim.InverseKinematicsSolver(model, reference, osim.SimTKArrayCoordinateReference()) solver.setAccuracy(1e-6) state = model.initSystem(); coordinates = model.getCoordinateSet() out = np.full((len(times), 35), np.nan) initialized=False for i, time in enumerate(times): state.setTime(float(time)) if (weights[i] > 0).sum() < 6: continue try: # OpenSim creates its marker goal during assemble(); updating weights # before the first assemble dereferences an uninitialized native goal. if initialized: for j,name in enumerate(names):solver.updateMarkerWeight(name,float(weights[i,j])) if i == 0 or not np.isfinite(out[i-1]).all(): solver.assemble(state) else: solver.track(state) initialized=True out[i] = [coordinates.get(c["name"]).getValue(state) for c in spec["coordinates"]] except RuntimeError: continue return out def refine_trajectory(spec, initial, targets, weights, times, settings): out = initial.copy(); diagnostic = [] for a, b in contiguous_segments(np.isfinite(initial).all(axis=1), times): if b-a < 3: continue start = initial[a:b] dt = np.diff(times[a:b]) safe = np.nan_to_num(targets[a:b]); w = np.sqrt(weights[a:b])[..., None] lower,upper=np.array([c["range"] for c in spec["coordinates"]]).T def data(q): return (np.array([forward_kinematics(spec, row)[0] for row in q])-safe)*w def objective(flat): q = flat.reshape(-1, 35) velocity = np.diff(q, axis=0)/dt[:, None] acceleration = np.diff(velocity, axis=0)/((dt[1:]+dt[:-1])/2)[:, None] limits=np.maximum(lower-q,0)+np.maximum(q-upper,0) return np.r_[data(q).reshape(-1), np.sqrt(settings["temporal_weight"])*acceleration.reshape(-1),.01*limits.reshape(-1)] from scipy.sparse import vstack,eye pattern=vstack([sparse_temporal_pattern(b-a,35,targets.shape[1]),eye((b-a)*35)],format="csr") candidate = least_squares(objective, start.reshape(-1), jac_sparsity=pattern, max_nfev=settings["refinement_max_evaluations"], loss="soft_l1", f_scale=.02).x.reshape(-1, 35) before, after = np.sqrt(np.mean(data(start)**2)), np.sqrt(np.mean(data(candidate)**2)) retained = after <= before+settings["refinement_observation_tolerance_m"] if retained: out[a:b] = candidate diagnostic.append({"frames": [a,b-1], "weighted_coordinate_rmse_before_m": float(before), "weighted_coordinate_rmse_after_m": float(after), "accepted": bool(retained)}) return out, diagnostic def run_anatomy(request, capture, config): root = Path(request["root"]) try: import yaml status = read_json(root/"temporal3d_status.json") if status.get("status") not in {"partial", "complete"}: raise ValueError("Temporal trajectory unavailable") source = root/status["trajectory_path"] settings = yaml.safe_load(Path(config.anatomical_config_path).read_text()) cache = StageCache(root, "anatomy", digest({"upstream": status["cache_key"], "settings": settings})) if cache.valid("trajectory"): atomic_json(root/"anatomy_status.json", read_json(cache.root/"status.json")); return data = np.load(source, allow_pickle=False) # Convert camera neutral axes back once. Model targets remain in camera axes: # a FreeJoint rotates/translates the neutral model to those proxy targets. neutral = data["neutral_mhr70_m"]*np.array([1., -1., -1.]) spec = model_spec(neutral, settings) atomic_json(cache.root/"model_spec.json", spec) model = build_opensim(spec, cache.root/"BattingKinematics-v1.osim") indices = [m["mhr70_index"] for m in spec["markers"].values()] targets = data["keypoints_camera_m"][:, indices] # 3D targets are fitted model proxies. Weights reflect their 2D support where # available; hand-only proxy markers receive a weak explicitly recorded prior. weights = data["observation_weights"][:, indices].copy() for j, name in enumerate(spec["markers"]): if name.endswith("_mcp"): weights[:, j] = np.maximum(weights[:, j], .1) weights *= data["accepted_frames"][:, None] weights[~np.isfinite(targets).all(axis=2)] = 0 times = data["fitting_times"] q = weighted_ik(model, spec, targets, weights, times, cache.root) q, refinement = refine_trajectory(spec, q, targets, weights, times, settings) positions = np.full_like(targets, np.nan) rotations = np.full((len(q), len(spec["bodies"]), 3, 3), np.nan) accepted = np.zeros(len(q), bool); residual = np.full(targets.shape[:2], np.nan) for i in np.flatnonzero(np.isfinite(q).all(axis=1)): markers, transforms = forward_kinematics(spec, q[i]) error = np.linalg.norm(markers-targets[i], axis=-1) residual[i] = error eligible = weights[i] > 0 if not eligible.any() or np.sqrt(np.mean(error[eligible]**2)) > settings["marker_fit_max_rmse_m"]: continue accepted[i] = True; positions[i] = markers rotations[i] = np.array([transforms[name][0] for name in spec["bodies"]]) if not accepted.any(): raise ValueError("No IK frames passed marker agreement") path = cache.root/"trajectory.npz" np.savez_compressed(path, coordinates=q, marker_positions_m=positions, segment_rotations=rotations, residual_m=residual, accepted_frames=accepted, fitting_times=times, marker_names=np.array(list(spec["markers"])), segment_names=np.array(list(spec["bodies"]))) result = {"status": "complete" if accepted.all() else "partial", "frames_fitted": int(accepted.sum()), "cache_key": cache.key, "trajectory_path": str(path.relative_to(root)), "model_id": spec["model_id"], "model_sha256": sha256_file(cache.root/"BattingKinematics-v1.osim"), "spec_sha256": digest(spec), "dof": 35, "target_source": "MHR70_model_regression_proxy_not_independent_reference", "coordinate_space": "camera_x_right_y_down_z_forward_metres", "refinement": refinement, "geometry_source": status["geometry_source"], "validation": "reference-validation-pending", "maximum_regularization_sensitivity_m":status.get("maximum_regularization_sensitivity_m"), "dynamics": "disabled", "rotation_coordinates": "primitive_intrinsic_XYZ_XY_Z"} atomic_json(cache.root/"status.json", result) cache.commit("trajectory", [path, cache.root/"status.json", cache.root/"model_spec.json", cache.root/"BattingKinematics-v1.osim"]) except Exception as error: result = {"status": "unavailable", "reason": str(error)[:300], "error_type": type(error).__name__} atomic_json(root/"anatomy_status.json", result)