Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
ebede04
1
Parent(s): 11fcb85
Automated Deploy: bfc2534d4ddb0a114466a5bed5d28d2e173f8a17
Browse files- baseball_batting/api.py +1 -1
- baseball_batting/motion_contract.py +1 -0
- baseball_batting/motion_evidence.py +19 -5
- baseball_batting/motion_refinement.py +86 -45
- docs/MOTION_PLAYER_API.md +18 -10
- docs/MOTION_REQUIREMENTS_AUDIT.md +1 -1
- docs/motion-input.schema.json +7 -0
- tests/test_motion_refinement.py +69 -0
baseball_batting/api.py
CHANGED
|
@@ -78,7 +78,7 @@ def create_app(settings=None, service=None):
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
-
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.12.
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
|
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
+
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.12.2", lifespan=lifespan,
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
baseball_batting/motion_contract.py
CHANGED
|
@@ -17,6 +17,7 @@ class MotionCamera(CameraInput):
|
|
| 17 |
|
| 18 |
class RefinementSettings(Strict):
|
| 19 |
enabled: bool = True
|
|
|
|
| 20 |
window_frames: int = Field(default=48, ge=12, le=120, strict=True)
|
| 21 |
context_frames: int = Field(default=8, ge=2, le=24, strict=True)
|
| 22 |
iterations: int = Field(default=25, ge=5, le=100, strict=True)
|
|
|
|
| 17 |
|
| 18 |
class RefinementSettings(Strict):
|
| 19 |
enabled: bool = True
|
| 20 |
+
native_batch_frames: int = Field(default=8, ge=1, le=16, strict=True)
|
| 21 |
window_frames: int = Field(default=48, ge=12, le=120, strict=True)
|
| 22 |
context_frames: int = Field(default=8, ge=2, le=24, strict=True)
|
| 23 |
iterations: int = Field(default=25, ge=5, le=100, strict=True)
|
baseball_batting/motion_evidence.py
CHANGED
|
@@ -45,8 +45,9 @@ def flow_support(previous,current,old_points,new_points,old_scores,new_scores,mi
|
|
| 45 |
if q is None:return supported,testable
|
| 46 |
back,reverse,_=cv2.calcOpticalFlowPyrLK(b,a,q,None,winSize=(31,31),maxLevel=4)
|
| 47 |
if back is None:return supported,testable
|
| 48 |
-
testable[ids]=(status[:,0]>0)&(reverse[:,0]>0)
|
| 49 |
fb=np.linalg.norm(back[:,0]-p[:,0],axis=-1)
|
|
|
|
|
|
|
| 50 |
agreement=np.linalg.norm(q[:,0]-new_points[ids]*scale,axis=-1)
|
| 51 |
# Pixel tolerance scales with displayed image, not a particular test clip.
|
| 52 |
tolerance=max(2.,.006*size[1])
|
|
@@ -54,6 +55,14 @@ def flow_support(previous,current,old_points,new_points,old_scores,new_scores,mi
|
|
| 54 |
return supported,testable
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def collect(job,video,capture,models,options,progress,device='cuda'):
|
| 58 |
import cv2
|
| 59 |
from .api_worker import model_files
|
|
@@ -64,6 +73,7 @@ def collect(job,video,capture,models,options,progress,device='cuda'):
|
|
| 64 |
n=capture['frame_count'];j=len(NAMES)
|
| 65 |
pixels=np.full((n,j,2),np.nan);weights=np.zeros((n,j));scores=np.zeros((n,j))
|
| 66 |
usable=np.zeros(n,bool);heights=np.ones(n);flow=np.zeros((n,j),bool);flow_testable=np.zeros((n,j),bool)
|
|
|
|
| 67 |
previous=None;prior=None;prior_scores=None;prior_time=None;old_box=None
|
| 68 |
camera_displacement=np.full(n,np.nan)
|
| 69 |
times=np.array([r['physical_s'] if r['physical_s'] is not None else r['playback_s'] for r in capture['frames']])
|
|
@@ -83,20 +93,24 @@ def collect(job,video,capture,models,options,progress,device='cuda'):
|
|
| 83 |
if previous is not None and 0<times[i]-prior_time<=options.correction.max_gap_s:
|
| 84 |
camera_displacement[i]=background_motion(previous,gray,old_box,box)
|
| 85 |
flow[i],flow_testable[i]=flow_support(previous,gray,prior,pixels[i],prior_scores,scores[i],options.refinement.minimum_observation_score)
|
| 86 |
-
#
|
| 87 |
-
|
|
|
|
| 88 |
elif previous is not None:serial+=1
|
| 89 |
usable[i]=np.count_nonzero(weights[i]>0)>=options.refinement.minimum_observed_joints
|
| 90 |
sequence[i]=serial;previous=gray;prior=pixels[i].copy();prior_scores=scores[i].copy();prior_time=times[i];old_box=box
|
| 91 |
if i%16==0 or i==n-1:progress('image_motion_evidence',i+1,n)
|
|
|
|
|
|
|
| 92 |
evidence={'pixels':pixels,'weights':weights,'scores':scores,'box_heights':heights,
|
| 93 |
'frame_usable':usable,'flow_supported':flow,'flow_testable':flow_testable,'sequence_ids':sequence,
|
|
|
|
| 94 |
'background_displacement_image_fraction':camera_displacement}
|
| 95 |
if options.camera and options.camera.distortion is not None:evidence['distortion']=np.array(options.camera.distortion)
|
| 96 |
np.savez_compressed(job/'motion-evidence-private.npz',**evidence)
|
| 97 |
-
metadata={'version':'rtmw-image-evidence-
|
| 98 |
'observation_names':list(NAMES),'minimum_score':options.refinement.minimum_observation_score,
|
| 99 |
-
'frames_with_minimum_support':int(usable.sum()),'optical_flow':'
|
| 100 |
'anatomy':'RTMW homologous image landmarks are soft constraints; not asserted identical to native rig joint centers',
|
| 101 |
'visibility':'detector confidence and image continuity; not verified occlusion labels or depth accuracy',
|
| 102 |
'confidence':'image evidence weights only; no calibrated 3D confidence',
|
|
|
|
| 45 |
if q is None:return supported,testable
|
| 46 |
back,reverse,_=cv2.calcOpticalFlowPyrLK(b,a,q,None,winSize=(31,31),maxLevel=4)
|
| 47 |
if back is None:return supported,testable
|
|
|
|
| 48 |
fb=np.linalg.norm(back[:,0]-p[:,0],axis=-1)
|
| 49 |
+
# A failed cycle is an unreliable tracker, not evidence against a detector.
|
| 50 |
+
testable[ids]=(status[:,0]>0)&(reverse[:,0]>0)&(fb<=2.)
|
| 51 |
agreement=np.linalg.norm(q[:,0]-new_points[ids]*scale,axis=-1)
|
| 52 |
# Pixel tolerance scales with displayed image, not a particular test clip.
|
| 53 |
tolerance=max(2.,.006*size[1])
|
|
|
|
| 55 |
return supported,testable
|
| 56 |
|
| 57 |
|
| 58 |
+
def observation_weights(base,forward,forward_testable,backward,backward_testable):
|
| 59 |
+
"""Use either neighboring image as corroboration; weaken only reliable disagreement."""
|
| 60 |
+
supported=forward|backward
|
| 61 |
+
contradicted=(forward_testable&~forward)|(backward_testable&~backward)
|
| 62 |
+
result=base.copy();result[contradicted&~supported]*=.25
|
| 63 |
+
return result
|
| 64 |
+
|
| 65 |
+
|
| 66 |
def collect(job,video,capture,models,options,progress,device='cuda'):
|
| 67 |
import cv2
|
| 68 |
from .api_worker import model_files
|
|
|
|
| 73 |
n=capture['frame_count'];j=len(NAMES)
|
| 74 |
pixels=np.full((n,j,2),np.nan);weights=np.zeros((n,j));scores=np.zeros((n,j))
|
| 75 |
usable=np.zeros(n,bool);heights=np.ones(n);flow=np.zeros((n,j),bool);flow_testable=np.zeros((n,j),bool)
|
| 76 |
+
reverse_flow=np.zeros((n,j),bool);reverse_testable=np.zeros((n,j),bool)
|
| 77 |
previous=None;prior=None;prior_scores=None;prior_time=None;old_box=None
|
| 78 |
camera_displacement=np.full(n,np.nan)
|
| 79 |
times=np.array([r['physical_s'] if r['physical_s'] is not None else r['playback_s'] for r in capture['frames']])
|
|
|
|
| 93 |
if previous is not None and 0<times[i]-prior_time<=options.correction.max_gap_s:
|
| 94 |
camera_displacement[i]=background_motion(previous,gray,old_box,box)
|
| 95 |
flow[i],flow_testable[i]=flow_support(previous,gray,prior,pixels[i],prior_scores,scores[i],options.refinement.minimum_observation_score)
|
| 96 |
+
# Offline look-ahead needs only the current and previous image. It
|
| 97 |
+
# can corroborate the earlier observation when forward tracking fails.
|
| 98 |
+
reverse_flow[i-1],reverse_testable[i-1]=flow_support(gray,previous,pixels[i],prior,scores[i],prior_scores,options.refinement.minimum_observation_score)
|
| 99 |
elif previous is not None:serial+=1
|
| 100 |
usable[i]=np.count_nonzero(weights[i]>0)>=options.refinement.minimum_observed_joints
|
| 101 |
sequence[i]=serial;previous=gray;prior=pixels[i].copy();prior_scores=scores[i].copy();prior_time=times[i];old_box=box
|
| 102 |
if i%16==0 or i==n-1:progress('image_motion_evidence',i+1,n)
|
| 103 |
+
weights=observation_weights(weights,flow,flow_testable,reverse_flow,reverse_testable)
|
| 104 |
+
usable=(weights>0).sum(axis=1)>=options.refinement.minimum_observed_joints
|
| 105 |
evidence={'pixels':pixels,'weights':weights,'scores':scores,'box_heights':heights,
|
| 106 |
'frame_usable':usable,'flow_supported':flow,'flow_testable':flow_testable,'sequence_ids':sequence,
|
| 107 |
+
'reverse_flow_supported':reverse_flow,'reverse_flow_testable':reverse_testable,
|
| 108 |
'background_displacement_image_fraction':camera_displacement}
|
| 109 |
if options.camera and options.camera.distortion is not None:evidence['distortion']=np.array(options.camera.distortion)
|
| 110 |
np.savez_compressed(job/'motion-evidence-private.npz',**evidence)
|
| 111 |
+
metadata={'version':'rtmw-image-evidence-v2','model_sha256':sha256_file(paths['body_pose']),
|
| 112 |
'observation_names':list(NAMES),'minimum_score':options.refinement.minimum_observation_score,
|
| 113 |
+
'frames_with_minimum_support':int(usable.sum()),'optical_flow':'two_neighbor_LK_with_forward_backward_cycle_checks; weights_only',
|
| 114 |
'anatomy':'RTMW homologous image landmarks are soft constraints; not asserted identical to native rig joint centers',
|
| 115 |
'visibility':'detector confidence and image continuity; not verified occlusion labels or depth accuracy',
|
| 116 |
'confidence':'image evidence weights only; no calibrated 3D confidence',
|
baseball_batting/motion_refinement.py
CHANGED
|
@@ -7,7 +7,7 @@ individually. Every rejected window rolls back to its native prediction.
|
|
| 7 |
import numpy as np
|
| 8 |
from .sam_motion import MHR, BONES, segments
|
| 9 |
|
| 10 |
-
VERSION = 'native-body-refinement-
|
| 11 |
NAMES = tuple(MHR)
|
| 12 |
INDICES = tuple(MHR.values())
|
| 13 |
LOCAL = {name:i for i,name in enumerate(NAMES)}
|
|
@@ -58,13 +58,31 @@ def body_size(points):
|
|
| 58 |
# Trunk + hip/ankle distance is less affected by raised hands than a bbox.
|
| 59 |
sizes=[]
|
| 60 |
for side in ('left','right'):
|
| 61 |
-
a,b,c=[LOCAL[side+'_'+part] for part in ('shoulder','hip','ankle')]
|
| 62 |
sizes.append(np.linalg.norm(points[:,a]-points[:,b],axis=-1)+
|
| 63 |
-
np.linalg.norm(points[:,b]-points[:,c],axis=-1))
|
| 64 |
q=np.concatenate(sizes);q=q[np.isfinite(q)&(q>1e-5)]
|
| 65 |
return float(np.median(q)) if len(q) else None
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_heights,
|
| 69 |
settings,distortion=None,temporal_factor=1.,device='cuda'):
|
| 70 |
"""Adapt the existing MHR fitter's image/prior/temporal objective for either rig.
|
|
@@ -75,17 +93,26 @@ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_he
|
|
| 75 |
"""
|
| 76 |
import torch
|
| 77 |
def tensor(v):return torch.as_tensor(v,dtype=torch.float32,device=device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
initial_pose=tensor(pose);initial_camera=tensor(camera)
|
| 79 |
# Separate shared-shape normalization from pose fitting. The old initializer
|
| 80 |
# is retained for image/normalization diagnostics, not treated as 3D truth.
|
| 81 |
-
with torch.no_grad():normalized=
|
| 82 |
target=normalized
|
| 83 |
p=torch.nn.Parameter(initial_pose.clone());c=torch.nn.Parameter(initial_camera.clone())
|
| 84 |
w=tensor(weights);observed=tensor(np.nan_to_num(pixels));k=tensor(intrinsics)
|
| 85 |
heights=tensor(box_heights).clamp(min=1)
|
| 86 |
size=body_size(target.detach().cpu().numpy())
|
| 87 |
if size is None:raise ValueError('refinement_body_scale_unresolved')
|
| 88 |
-
|
|
|
|
|
|
|
| 89 |
if (dt<=0).any():raise ValueError('refinement_clock_not_increasing')
|
| 90 |
distortion=tensor(distortion) if distortion is not None else None
|
| 91 |
sigma=heights[:,None]*settings['observation_scale_box_fraction']
|
|
@@ -99,8 +126,9 @@ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_he
|
|
| 99 |
((dt[:-1]+dt[1:])/2)[:,None]).detach()
|
| 100 |
root_tolerance=(.005*size+.03*torch.maximum(root_speed[:-1],root_speed[1:])*
|
| 101 |
((dt[:-1]+dt[1:])/2)).detach()
|
| 102 |
-
def evaluate():
|
| 103 |
-
xyz
|
|
|
|
| 104 |
projected=project_torch(xyz,k,distortion)
|
| 105 |
e=(projected-observed)/sigma[...,None]
|
| 106 |
image=((torch.sqrt(1+e.square().sum(-1))-1)*w).sum()/w.sum().clamp(min=1)
|
|
@@ -130,18 +158,22 @@ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_he
|
|
| 130 |
change=(relative-initial_relative).norm(dim=-1).max()/size
|
| 131 |
return bool(torch.isfinite(xyz).all() and (xyz[...,2]>0).all() and change<=settings['maximum_body_change_fraction'])
|
| 132 |
for _ in range(settings['iterations']):
|
| 133 |
-
optimizer.zero_grad()
|
|
|
|
|
|
|
|
|
|
| 134 |
if not torch.isfinite(loss):raise ValueError('refinement_nonfinite_objective')
|
| 135 |
value=float(loss.detach())
|
| 136 |
if value<best and feasible(xyz.detach()):best=value;best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 137 |
loss.backward()
|
|
|
|
| 138 |
if any(q.grad is None or not torch.isfinite(q.grad).all() for q in (p,c)):
|
| 139 |
raise ValueError('refinement_native_gradients_unavailable')
|
| 140 |
torch.nn.utils.clip_grad_norm_([p,c],5.);optimizer.step()
|
| 141 |
with torch.no_grad():
|
| 142 |
loss,xyz,_=evaluate()
|
| 143 |
if torch.isfinite(loss) and float(loss)<best and feasible(xyz):best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 144 |
-
xyz=
|
| 145 |
return {'points_camera':xyz.detach().cpu().numpy(),'projection':xy.detach().cpu().numpy(),
|
| 146 |
'pose':best_pose.cpu().numpy(),'camera':best_camera.cpu().numpy(),
|
| 147 |
'normalized_initializer':normalized.cpu().numpy()}
|
|
@@ -228,55 +260,63 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 228 |
scenario_valid=np.zeros((len(scenarios),n),bool)
|
| 229 |
windows=[];fitted_pose=np.array(parameters['pose'],copy=True);fitted_camera=np.array(parameters['camera'],copy=True)
|
| 230 |
distortion=evidence.get('distortion');serial=np.array(sequence,copy=True)
|
| 231 |
-
#
|
|
|
|
|
|
|
| 232 |
for contiguous in segments(valid,times,max_gap):
|
| 233 |
for segment in np.split(contiguous,np.flatnonzero(np.diff(sequence[contiguous])!=0)+1):
|
| 234 |
if len(segment)<4:continue
|
| 235 |
forward=forward_factory(segment)
|
|
|
|
|
|
|
|
|
|
| 236 |
local_valid=np.zeros(n,bool);local_valid[segment]=True
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
if ok:
|
| 251 |
-
for scenario_index,
|
| 252 |
-
alternative
|
| 253 |
-
good,_=
|
| 254 |
-
|
| 255 |
-
if not good:sensitivity_complete=False
|
| 256 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 257 |
-
alt_relative=alternative['points_camera']-alternative['points_camera'][:,hip].mean(1)[:,None]
|
| 258 |
-
fit_relative=fit['points_camera']-fit['points_camera'][:,hip].mean(1)[:,None]
|
| 259 |
-
|
| 260 |
-
maximum=np.maximum(maximum,delta)
|
| 261 |
scenarios[scenario_index][np.ix_(owned,indices)]=alternative['points_camera'][take]-alternative['camera'][take,None]
|
| 262 |
scenario_valid[scenario_index,owned]=good
|
| 263 |
-
if ok:
|
| 264 |
accepted[owned]=True
|
| 265 |
fitted_pose[owned]=fit['pose'][take];fitted_camera[owned]=fit['camera'][take]
|
| 266 |
result['camera_translation'][owned]=fit['camera'][take]
|
| 267 |
result['points_body'][np.ix_(owned,indices)]=fit['points_camera'][take]-fit['camera'][take,None]
|
| 268 |
result['projection'][np.ix_(owned,indices)]=fit['projection'][take]
|
| 269 |
-
if sensitivity_complete:sensitivity[np.ix_(owned,indices)]=maximum
|
| 270 |
-
checks['sensitivity_complete']=sensitivity_complete
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
# No derivative spans a switch between raw/refined motion, or fit-window seam.
|
| 280 |
boundaries[1:]|=accepted[1:]!=accepted[:-1];boundaries[:-1]|=accepted[1:]!=accepted[:-1]
|
| 281 |
extra=np.cumsum(np.r_[0,(boundaries[1:]|boundaries[:-1])])
|
| 282 |
result['sequence_ids']=serial*(n+1)+extra
|
|
@@ -303,6 +343,7 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 303 |
'gap_interpolation':'disabled; no image evidence invented','parameter_limits':'native_rig_and_initializer_prior; no invented anatomical bounds',
|
| 304 |
'sensitivity_kind':'temporal_regularization_sensitivity; not a calibrated error interval',
|
| 305 |
'sensitivity_factors':settings['sensitivity_factors'],'accuracy_validated':False}
|
| 306 |
-
metadata['window_boundaries']='
|
|
|
|
| 307 |
metadata['image_conflicting_joint_count']=int(conflict.sum())
|
| 308 |
return result,metadata
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
from .sam_motion import MHR, BONES, segments
|
| 9 |
|
| 10 |
+
VERSION = 'native-body-refinement-v2'
|
| 11 |
NAMES = tuple(MHR)
|
| 12 |
INDICES = tuple(MHR.values())
|
| 13 |
LOCAL = {name:i for i,name in enumerate(NAMES)}
|
|
|
|
| 58 |
# Trunk + hip/ankle distance is less affected by raised hands than a bbox.
|
| 59 |
sizes=[]
|
| 60 |
for side in ('left','right'):
|
| 61 |
+
a,b,c,d=[LOCAL[side+'_'+part] for part in ('shoulder','hip','knee','ankle')]
|
| 62 |
sizes.append(np.linalg.norm(points[:,a]-points[:,b],axis=-1)+
|
| 63 |
+
np.linalg.norm(points[:,b]-points[:,c],axis=-1)+np.linalg.norm(points[:,c]-points[:,d],axis=-1))
|
| 64 |
q=np.concatenate(sizes);q=q[np.isfinite(q)&(q>1e-5)]
|
| 65 |
return float(np.median(q)) if len(q) else None
|
| 66 |
|
| 67 |
|
| 68 |
+
def accumulate_body_gradients(forward,pose,camera,point_gradient,batch):
|
| 69 |
+
"""Exact vector–Jacobian products, releasing each native mesh graph immediately.
|
| 70 |
+
|
| 71 |
+
The point gradient comes from the FULL trajectory objective, including terms
|
| 72 |
+
crossing batch boundaries. Only the rig evaluation is batched, not the fit.
|
| 73 |
+
"""
|
| 74 |
+
import torch
|
| 75 |
+
if pose.grad is None:pose.grad=torch.zeros_like(pose)
|
| 76 |
+
if camera.grad is None:camera.grad=torch.zeros_like(camera)
|
| 77 |
+
for a in range(0,len(pose),batch):
|
| 78 |
+
b=min(a+batch,len(pose));p,c=pose[a:b],camera[a:b];xyz=forward(p,c)
|
| 79 |
+
if not xyz.requires_grad:raise ValueError('refinement_native_gradients_unavailable')
|
| 80 |
+
dp,dc=torch.autograd.grad(xyz,(p,c),grad_outputs=point_gradient[a:b],allow_unused=True)
|
| 81 |
+
if any(q is None or not torch.isfinite(q).all() for q in (dp,dc)):
|
| 82 |
+
raise ValueError('refinement_native_gradients_unavailable')
|
| 83 |
+
pose.grad[a:b].add_(dp);camera.grad[a:b].add_(dc)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_heights,
|
| 87 |
settings,distortion=None,temporal_factor=1.,device='cuda'):
|
| 88 |
"""Adapt the existing MHR fitter's image/prior/temporal objective for either rig.
|
|
|
|
| 93 |
"""
|
| 94 |
import torch
|
| 95 |
def tensor(v):return torch.as_tensor(v,dtype=torch.float32,device=device)
|
| 96 |
+
def body(p,c):
|
| 97 |
+
# Keep ONE trajectory/objective; only native rig evaluations are batched.
|
| 98 |
+
batch=settings.get('native_batch_frames',8);parts=[]
|
| 99 |
+
for a in range(0,len(p),batch):
|
| 100 |
+
b=min(a+batch,len(p));pp,cc=p[a:b],c[a:b]
|
| 101 |
+
parts.append(forward(pp,cc))
|
| 102 |
+
return torch.cat(parts)
|
| 103 |
initial_pose=tensor(pose);initial_camera=tensor(camera)
|
| 104 |
# Separate shared-shape normalization from pose fitting. The old initializer
|
| 105 |
# is retained for image/normalization diagnostics, not treated as 3D truth.
|
| 106 |
+
with torch.no_grad():normalized=body(initial_pose,initial_camera).detach()
|
| 107 |
target=normalized
|
| 108 |
p=torch.nn.Parameter(initial_pose.clone());c=torch.nn.Parameter(initial_camera.clone())
|
| 109 |
w=tensor(weights);observed=tensor(np.nan_to_num(pixels));k=tensor(intrinsics)
|
| 110 |
heights=tensor(box_heights).clamp(min=1)
|
| 111 |
size=body_size(target.detach().cpu().numpy())
|
| 112 |
if size is None:raise ValueError('refinement_body_scale_unresolved')
|
| 113 |
+
# Large source PTS origins lose frame intervals if cast directly to FP32.
|
| 114 |
+
relative_times=np.asarray(times,np.float64)-float(times[0])
|
| 115 |
+
t=torch.as_tensor(relative_times,dtype=torch.float64,device=device);dt=t[1:]-t[:-1]
|
| 116 |
if (dt<=0).any():raise ValueError('refinement_clock_not_increasing')
|
| 117 |
distortion=tensor(distortion) if distortion is not None else None
|
| 118 |
sigma=heights[:,None]*settings['observation_scale_box_fraction']
|
|
|
|
| 126 |
((dt[:-1]+dt[1:])/2)[:,None]).detach()
|
| 127 |
root_tolerance=(.005*size+.03*torch.maximum(root_speed[:-1],root_speed[1:])*
|
| 128 |
((dt[:-1]+dt[1:])/2)).detach()
|
| 129 |
+
def evaluate(xyz=None):
|
| 130 |
+
if xyz is None:
|
| 131 |
+
with torch.no_grad():xyz=body(p,c)
|
| 132 |
projected=project_torch(xyz,k,distortion)
|
| 133 |
e=(projected-observed)/sigma[...,None]
|
| 134 |
image=((torch.sqrt(1+e.square().sum(-1))-1)*w).sum()/w.sum().clamp(min=1)
|
|
|
|
| 158 |
change=(relative-initial_relative).norm(dim=-1).max()/size
|
| 159 |
return bool(torch.isfinite(xyz).all() and (xyz[...,2]>0).all() and change<=settings['maximum_body_change_fraction'])
|
| 160 |
for _ in range(settings['iterations']):
|
| 161 |
+
optimizer.zero_grad()
|
| 162 |
+
with torch.no_grad():values=body(p,c)
|
| 163 |
+
xyz=values.detach().requires_grad_(True)
|
| 164 |
+
loss,_,_=evaluate(xyz)
|
| 165 |
if not torch.isfinite(loss):raise ValueError('refinement_nonfinite_objective')
|
| 166 |
value=float(loss.detach())
|
| 167 |
if value<best and feasible(xyz.detach()):best=value;best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 168 |
loss.backward()
|
| 169 |
+
accumulate_body_gradients(forward,p,c,xyz.grad.detach(),settings.get('native_batch_frames',8))
|
| 170 |
if any(q.grad is None or not torch.isfinite(q.grad).all() for q in (p,c)):
|
| 171 |
raise ValueError('refinement_native_gradients_unavailable')
|
| 172 |
torch.nn.utils.clip_grad_norm_([p,c],5.);optimizer.step()
|
| 173 |
with torch.no_grad():
|
| 174 |
loss,xyz,_=evaluate()
|
| 175 |
if torch.isfinite(loss) and float(loss)<best and feasible(xyz):best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 176 |
+
xyz=body(best_pose,best_camera);xy=project_torch(xyz,k,distortion)
|
| 177 |
return {'points_camera':xyz.detach().cpu().numpy(),'projection':xy.detach().cpu().numpy(),
|
| 178 |
'pose':best_pose.cpu().numpy(),'camera':best_camera.cpu().numpy(),
|
| 179 |
'normalized_initializer':normalized.cpu().numpy()}
|
|
|
|
| 260 |
scenario_valid=np.zeros((len(scenarios),n),bool)
|
| 261 |
windows=[];fitted_pose=np.array(parameters['pose'],copy=True);fitted_camera=np.array(parameters['camera'],copy=True)
|
| 262 |
distortion=evidence.get('distortion');serial=np.array(sequence,copy=True)
|
| 263 |
+
# One optimization trajectory per true continuous segment. Small native
|
| 264 |
+
# forward/backward batches bound GPU memory; diagnostic windows never splice
|
| 265 |
+
# separately fitted trajectories and never introduce derivative boundaries.
|
| 266 |
for contiguous in segments(valid,times,max_gap):
|
| 267 |
for segment in np.split(contiguous,np.flatnonzero(np.diff(sequence[contiguous])!=0)+1):
|
| 268 |
if len(segment)<4:continue
|
| 269 |
forward=forward_factory(segment)
|
| 270 |
+
pixels=evidence['pixels'][segment];weights=evidence['weights'][segment]
|
| 271 |
+
arguments=(forward,parameters['pose'][segment],parameters['camera'][segment],points[segment],pixels,weights,
|
| 272 |
+
times[segment],raw['intrinsics'][segment],evidence['box_heights'][segment],settings)
|
| 273 |
local_valid=np.zeros(n,bool);local_valid[segment]=True
|
| 274 |
+
diagnostics=list(continuous_windows(local_valid,times,sequence,settings['window_frames'],settings['context_frames'],max_gap,activity))
|
| 275 |
+
try:
|
| 276 |
+
if progress:progress('whole_body_refinement',int(segment[0]),n)
|
| 277 |
+
fit=fit_window(*arguments,distortion=distortion,device=device)
|
| 278 |
+
from .geometry import project
|
| 279 |
+
original_xy=np.stack([project(p,k,distortion) for p,k in zip(points[segment],raw['intrinsics'][segment])])
|
| 280 |
+
def check(candidate,ids):
|
| 281 |
+
local=np.searchsorted(segment,ids)
|
| 282 |
+
return acceptance(points[ids],candidate['points_camera'][local],original_xy[local],candidate['projection'][local],
|
| 283 |
+
evidence['pixels'][ids],evidence['weights'][ids],times[ids],evidence['box_heights'][ids],settings,
|
| 284 |
+
reference=candidate['normalized_initializer'][local])
|
| 285 |
+
primary_checks=[check(fit,ids) for ids,_ in diagnostics]
|
| 286 |
+
alternatives=[]
|
| 287 |
+
if any(ok for ok,_ in primary_checks):
|
| 288 |
+
for factor in settings['sensitivity_factors']:
|
| 289 |
+
try:alternatives.append(fit_window(*arguments,distortion=distortion,device=device,temporal_factor=factor))
|
| 290 |
+
except (ValueError,FloatingPointError):alternatives.append(None)
|
| 291 |
+
for (ids,owned),(ok,checks) in zip(diagnostics,primary_checks):
|
| 292 |
+
take=np.searchsorted(segment,owned);maximum=np.zeros((len(owned),len(indices)))
|
| 293 |
+
sensitivity_complete=bool(ok and len(alternatives)==len(settings['sensitivity_factors']) and all(v is not None for v in alternatives))
|
| 294 |
if ok:
|
| 295 |
+
for scenario_index,alternative in enumerate(alternatives):
|
| 296 |
+
if alternative is None:continue
|
| 297 |
+
good,_=check(alternative,ids)
|
| 298 |
+
sensitivity_complete &= good
|
|
|
|
| 299 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 300 |
+
alt_relative=alternative['points_camera'][take]-alternative['points_camera'][take][:,hip].mean(1)[:,None]
|
| 301 |
+
fit_relative=fit['points_camera'][take]-fit['points_camera'][take][:,hip].mean(1)[:,None]
|
| 302 |
+
maximum=np.maximum(maximum,np.linalg.norm(alt_relative-fit_relative,axis=-1))
|
|
|
|
| 303 |
scenarios[scenario_index][np.ix_(owned,indices)]=alternative['points_camera'][take]-alternative['camera'][take,None]
|
| 304 |
scenario_valid[scenario_index,owned]=good
|
|
|
|
| 305 |
accepted[owned]=True
|
| 306 |
fitted_pose[owned]=fit['pose'][take];fitted_camera[owned]=fit['camera'][take]
|
| 307 |
result['camera_translation'][owned]=fit['camera'][take]
|
| 308 |
result['points_body'][np.ix_(owned,indices)]=fit['points_camera'][take]-fit['camera'][take,None]
|
| 309 |
result['projection'][np.ix_(owned,indices)]=fit['projection'][take]
|
| 310 |
+
if sensitivity_complete:sensitivity[np.ix_(owned,indices)]=maximum
|
| 311 |
+
checks['sensitivity_complete']=bool(sensitivity_complete)
|
| 312 |
+
windows.append({'start_frame':int(owned[0]),'end_frame':int(owned[-1]),
|
| 313 |
+
'context_start_frame':int(ids[0]),'context_end_frame':int(ids[-1]),'accepted':bool(ok),**checks})
|
| 314 |
+
except (ValueError,FloatingPointError) as error:
|
| 315 |
+
code=str(error) if str(error) in {'refinement_native_gradients_unavailable','refinement_body_scale_unresolved','refinement_nonfinite_objective'} else 'refinement_numerical_failure'
|
| 316 |
+
windows.append({'start_frame':int(segment[0]),'end_frame':int(segment[-1]),'accepted':False,
|
| 317 |
+
'reasons':[code],'error_type':type(error).__name__})
|
| 318 |
+
if progress:progress('whole_body_refinement',int(segment[-1])+1,n)
|
| 319 |
+
# No derivative spans an actual switch between accepted and native fallback motion.
|
|
|
|
| 320 |
boundaries[1:]|=accepted[1:]!=accepted[:-1];boundaries[:-1]|=accepted[1:]!=accepted[:-1]
|
| 321 |
extra=np.cumsum(np.r_[0,(boundaries[1:]|boundaries[:-1])])
|
| 322 |
result['sequence_ids']=serial*(n+1)+extra
|
|
|
|
| 343 |
'gap_interpolation':'disabled; no image evidence invented','parameter_limits':'native_rig_and_initializer_prior; no invented anatomical bounds',
|
| 344 |
'sensitivity_kind':'temporal_regularization_sensitivity; not a calibrated error interval',
|
| 345 |
'sensitivity_factors':settings['sensitivity_factors'],'accuracy_validated':False}
|
| 346 |
+
metadata['window_boundaries']='diagnostic windows only; no fitted trajectory joins'
|
| 347 |
+
metadata['trajectory_fit']='one continuous native-parameter trajectory per identity/model/clock segment; exact batched native vector-Jacobian products'
|
| 348 |
metadata['image_conflicting_joint_count']=int(conflict.sum())
|
| 349 |
return result,metadata
|
docs/MOTION_PLAYER_API.md
CHANGED
|
@@ -111,16 +111,23 @@ Each continuous identity/model segment uses a shared robust body-shape estimate.
|
|
| 111 |
The optimizer changes native pose and camera translation, using soft image
|
| 112 |
constraints, initializer priors and timestamp-aware temporal penalties. RTMW
|
| 113 |
landmarks are homologous observations, not asserted identical anatomical joint
|
| 114 |
-
centres or calibrated visibility/depth scores. LK
|
| 115 |
-
|
|
|
|
|
|
|
| 116 |
not establish physical calibration. Native rig constraints and initializer priors
|
| 117 |
apply; no unsupported anatomical angle limits are invented.
|
| 118 |
|
| 119 |
-
Fitting
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
is generated through a missing interval. Rapid movement receives weaker temporal
|
| 125 |
regularization. Image-supported fast hand peaks are checked for timing and speed
|
| 126 |
distortion. Accepted fitted points bypass the old independent-joint filter so
|
|
@@ -142,7 +149,7 @@ recorded, so measurements remain reproducible. Background displacement is not a
|
|
| 142 |
calibrated camera trajectory or ground frame. No unsupported foot locking or
|
| 143 |
field direction is inferred.
|
| 144 |
|
| 145 |
-
Each
|
| 146 |
Summary `stability` gives the resulting minimum/maximum in the metric's own units
|
| 147 |
only when both alternative fits and the complete swing are supported. Otherwise
|
| 148 |
it supplies `not_evaluated` with a reason. This is sensitivity to regularization,
|
|
@@ -150,8 +157,9 @@ it supplies `not_evaluated` with a reason. This is sensitivity to regularization
|
|
| 150 |
uncertainty is fabricated for unsupported sections. Acceptance defaults are
|
| 151 |
configurable engineering gates, not established biomechanical error limits.
|
| 152 |
|
| 153 |
-
Defaults are
|
| 154 |
-
|
|
|
|
| 155 |
the actual inference/refinement runtime must be evaluated on the deployed GPU.
|
| 156 |
Options and bounds are published in `/input-schema`. Progress includes
|
| 157 |
`image_motion_evidence`, `loading_native_refinement`, and `whole_body_refinement`.
|
|
|
|
| 111 |
The optimizer changes native pose and camera translation, using soft image
|
| 112 |
constraints, initializer priors and timestamp-aware temporal penalties. RTMW
|
| 113 |
landmarks are homologous observations, not asserted identical anatomical joint
|
| 114 |
+
centres or calibrated visibility/depth scores. LK checks both neighboring images;
|
| 115 |
+
only reliable forward/backward cycles can contradict a detector, and either
|
| 116 |
+
neighbor can corroborate it. A tracking failure alone does not invalidate a 2D
|
| 117 |
+
observation. These checks adjust weights and never create a missing landmark. Shape/scale priors do
|
| 118 |
not establish physical calibration. Native rig constraints and initializer priors
|
| 119 |
apply; no unsupported anatomical angle limits are invented.
|
| 120 |
|
| 121 |
+
Fitting optimizes one continuous native-parameter trajectory per valid segment.
|
| 122 |
+
Native rig evaluation and gradient recomputation use batches of eight frames,
|
| 123 |
+
bounding mesh activation memory without splicing separately fitted trajectories.
|
| 124 |
+
Vector–Jacobian products use the full trajectory's point gradients, including
|
| 125 |
+
temporal terms across batch boundaries; this is the same gradient as one complete
|
| 126 |
+
native evaluation, verified by a cross-boundary gradient-equivalence test.
|
| 127 |
+
Overlapping quality windows accept/reject regions of that same fit; they do not
|
| 128 |
+
introduce processing seams or derivative gaps by themselves. Missing observations,
|
| 129 |
+
identity/model boundaries, clock gaps and actual raw/refined switches remain
|
| 130 |
+
derivative boundaries. No pose
|
| 131 |
is generated through a missing interval. Rapid movement receives weaker temporal
|
| 132 |
regularization. Image-supported fast hand peaks are checked for timing and speed
|
| 133 |
distortion. Accepted fitted points bypass the old independent-joint filter so
|
|
|
|
| 149 |
calibrated camera trajectory or ground frame. No unsupported foot locking or
|
| 150 |
field direction is inferred.
|
| 151 |
|
| 152 |
+
Each supported continuous trajectory is fitted again with temporal-weight factors 0.5 and 2.0.
|
| 153 |
Summary `stability` gives the resulting minimum/maximum in the metric's own units
|
| 154 |
only when both alternative fits and the complete swing are supported. Otherwise
|
| 155 |
it supplies `not_evaluated` with a reason. This is sensitivity to regularization,
|
|
|
|
| 157 |
uncertainty is fabricated for unsupported sections. Acceptance defaults are
|
| 158 |
configurable engineering gates, not established biomechanical error limits.
|
| 159 |
|
| 160 |
+
Defaults are eight native frames/batch, 48 frames/quality window, eight context
|
| 161 |
+
frames/side and 25 optimizer steps per continuous fit. Three fits are performed
|
| 162 |
+
for each supported continuous segment. This adds GPU work;
|
| 163 |
the actual inference/refinement runtime must be evaluated on the deployed GPU.
|
| 164 |
Options and bounds are published in `/input-schema`. Progress includes
|
| 165 |
`image_motion_evidence`, `loading_native_refinement`, and `whole_body_refinement`.
|
docs/MOTION_REQUIREMENTS_AUDIT.md
CHANGED
|
@@ -9,7 +9,7 @@ Against `Motion_Player_Backend_Requirements.md` v1.0, 15 October 2026.
|
|
| 9 |
| Manifest, lineage and versions | Immutable analysis/job/revision/person IDs; model/source/asset hashes, adapter, correction inputs and definition revision. |
|
| 10 |
| Original PTS, VFR, retiming | Every source frame retained. Video and capture clocks exported separately. GVHMR explicitly maps a 30-Hz model grid back to original times; rotation interpolation uses SO(3). |
|
| 11 |
| Athlete selection and identity | Required box when ambiguous; bounded short-loss recovery requires spatial/motion/size/appearance agreement. Lost frames remain gaps; ambiguous crossings cannot be recovered on clothing alone. |
|
| 12 |
-
| Correct and check motion |
|
| 13 |
| Anatomy and canonical names | Both export all 20 names. Native joint definitions/indices verified. SMPL-X surface-derived landmarks explicitly marked; no claim that its hips/shoulders equal MHR70 landmarks. |
|
| 14 |
| Coordinates, scale and root | Fixed camera/declared reference axes; hip-relative positions, root separate, added once for projection. Model scale documented; unknown scale disables absolute measurements. Native global predictions are not promoted to calibrated ground motion. |
|
| 15 |
| Motion and quality artifacts | Finite positions or null, status/confidence/reasons for every joint/frame, explicit gaps/segments, stable skeleton/bones. No invented cross-model confidence. |
|
|
|
|
| 9 |
| Manifest, lineage and versions | Immutable analysis/job/revision/person IDs; model/source/asset hashes, adapter, correction inputs and definition revision. |
|
| 10 |
| Original PTS, VFR, retiming | Every source frame retained. Video and capture clocks exported separately. GVHMR explicitly maps a 30-Hz model grid back to original times; rotation interpolation uses SO(3). |
|
| 11 |
| Athlete selection and identity | Required box when ambiguous; bounded short-loss recovery requires spatial/motion/size/appearance agreement. Lost frames remain gaps; ambiguous crossings cannot be recovered on clothing alone. |
|
| 12 |
+
| Correct and check motion | One continuous native MHR/SMPL-X parameter fit per valid segment; bounded-memory exact gradient accumulation, separate RTMW evidence, two-neighbor cycle-checked LK, shared shape, initializer/temporal priors, quality-window acceptance/rollback, image contradiction gates, hand-peak protection and sensitivity fits. Computational batches create no motion/derivative seams. Accepted rig points bypass independent smoothing. Real gaps/model boundaries and raw/fitted switches stay explicit. Engineering diagnostics do not establish depth accuracy. |
|
| 13 |
| Anatomy and canonical names | Both export all 20 names. Native joint definitions/indices verified. SMPL-X surface-derived landmarks explicitly marked; no claim that its hips/shoulders equal MHR70 landmarks. |
|
| 14 |
| Coordinates, scale and root | Fixed camera/declared reference axes; hip-relative positions, root separate, added once for projection. Model scale documented; unknown scale disables absolute measurements. Native global predictions are not promoted to calibrated ground motion. |
|
| 15 |
| Motion and quality artifacts | Finite positions or null, status/confidence/reasons for every joint/frame, explicit gaps/segments, stable skeleton/bones. No invented cross-model confidence. |
|
docs/motion-input.schema.json
CHANGED
|
@@ -301,6 +301,13 @@
|
|
| 301 |
"title": "Enabled",
|
| 302 |
"type": "boolean"
|
| 303 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
"window_frames": {
|
| 305 |
"default": 48,
|
| 306 |
"maximum": 120,
|
|
|
|
| 301 |
"title": "Enabled",
|
| 302 |
"type": "boolean"
|
| 303 |
},
|
| 304 |
+
"native_batch_frames": {
|
| 305 |
+
"default": 8,
|
| 306 |
+
"maximum": 16,
|
| 307 |
+
"minimum": 1,
|
| 308 |
+
"title": "Native Batch Frames",
|
| 309 |
+
"type": "integer"
|
| 310 |
+
},
|
| 311 |
"window_frames": {
|
| 312 |
"default": 48,
|
| 313 |
"maximum": 120,
|
tests/test_motion_refinement.py
CHANGED
|
@@ -63,6 +63,22 @@ def test_constrained_fit_improves_known_motion_without_stretching_limbs():
|
|
| 63 |
np.testing.assert_allclose(np.linalg.norm(result['points_camera'][:,a]-result['points_camera'][:,b],axis=-1),.3,atol=2e-6)
|
| 64 |
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def test_acceptance_rejects_worse_image_alignment_and_deformation():
|
| 67 |
_,_,_,_,truth,pixels,times,k=articulated_fixture(12)
|
| 68 |
candidate=truth.copy();candidate[:,LOCAL['left_wrist'],0]+=.4
|
|
@@ -84,6 +100,14 @@ def test_ambiguous_image_fit_cannot_select_a_pose_outside_its_trust_region():
|
|
| 84 |
assert np.max(np.linalg.norm(a-b,axis=-1))/body_size(raw)<=.025001
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
def test_windows_preserve_every_owner_and_never_cross_identity_clock_or_missing_frames():
|
| 88 |
t=np.arange(100)/60;t[60:]+=.3;valid=np.ones(100,bool);valid[30:33]=False
|
| 89 |
sequence=np.zeros(100,int);sequence[80:]=1
|
|
@@ -152,6 +176,25 @@ def test_spatial_overlap_cannot_override_an_appearance_conflict():
|
|
| 152 |
assert tracker.update(blue,[person],.02)[1]=='athlete_appearance_conflict'
|
| 153 |
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
def test_camera_input_preserves_legacy_sam_contract_and_rejects_bad_distortion():
|
| 156 |
camera={'fx':700,'fy':690,'cx':320,'cy':240,'source':'calibration fixture','distortion':[-.2,.03,.001,-.002,.01]}
|
| 157 |
options=MotionInput(camera=camera)
|
|
@@ -201,6 +244,32 @@ def test_numerically_bad_fit_rolls_back_without_filling_gap(monkeypatch):
|
|
| 201 |
assert len(metadata['windows'])==2
|
| 202 |
|
| 203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
def test_supported_fast_peak_cannot_be_delayed_by_fitting():
|
| 205 |
_,_,_,_,truth,pixels,times,k=articulated_fixture(25)
|
| 206 |
candidate=np.concatenate([truth[:1].repeat(3,axis=0),truth[:-3]])
|
|
|
|
| 63 |
np.testing.assert_allclose(np.linalg.norm(result['points_camera'][:,a]-result['points_camera'][:,b],axis=-1),.3,atol=2e-6)
|
| 64 |
|
| 65 |
|
| 66 |
+
def test_batched_native_gradients_match_whole_trajectory_gradients_across_batch_joins():
|
| 67 |
+
torch=pytest.importorskip('torch')
|
| 68 |
+
from baseball_batting.motion_refinement import accumulate_body_gradients
|
| 69 |
+
forward,pose,camera,*_=articulated_fixture(12)
|
| 70 |
+
def loss(points):
|
| 71 |
+
return points.square().mean()+3*(points[2:]-2*points[1:-1]+points[:-2]).square().mean()
|
| 72 |
+
p=torch.tensor(pose,dtype=torch.float32,requires_grad=True);c=torch.tensor(camera,dtype=torch.float32,requires_grad=True)
|
| 73 |
+
loss(forward(p,c)).backward();expected_p=p.grad.clone();expected_c=c.grad.clone()
|
| 74 |
+
p=torch.tensor(pose,dtype=torch.float32,requires_grad=True);c=torch.tensor(camera,dtype=torch.float32,requires_grad=True)
|
| 75 |
+
with torch.no_grad():values=forward(p,c)
|
| 76 |
+
points=values.detach().requires_grad_(True);loss(points).backward()
|
| 77 |
+
accumulate_body_gradients(forward,p,c,points.grad,3)
|
| 78 |
+
torch.testing.assert_close(p.grad,expected_p,atol=1e-6,rtol=1e-5)
|
| 79 |
+
torch.testing.assert_close(c.grad,expected_c,atol=1e-6,rtol=1e-5)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
def test_acceptance_rejects_worse_image_alignment_and_deformation():
|
| 83 |
_,_,_,_,truth,pixels,times,k=articulated_fixture(12)
|
| 84 |
candidate=truth.copy();candidate[:,LOCAL['left_wrist'],0]+=.4
|
|
|
|
| 100 |
assert np.max(np.linalg.norm(a-b,axis=-1))/body_size(raw)<=.025001
|
| 101 |
|
| 102 |
|
| 103 |
+
def test_large_pts_origin_does_not_change_temporal_fit():
|
| 104 |
+
f,p,c,raw,_,xy,t,k=articulated_fixture(12)
|
| 105 |
+
s=RefinementSettings(iterations=8).model_dump();w=np.ones(xy.shape[:2]);heights=np.full(len(t),300)
|
| 106 |
+
a=fit_window(f,p,c,raw,xy,w,t,k,heights,s,device='cpu')
|
| 107 |
+
b=fit_window(f,p,c,raw,xy,w,t+1e7,k,heights,s,device='cpu')
|
| 108 |
+
np.testing.assert_allclose(a['points_camera'],b['points_camera'],atol=1e-5)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
def test_windows_preserve_every_owner_and_never_cross_identity_clock_or_missing_frames():
|
| 112 |
t=np.arange(100)/60;t[60:]+=.3;valid=np.ones(100,bool);valid[30:33]=False
|
| 113 |
sequence=np.zeros(100,int);sequence[80:]=1
|
|
|
|
| 176 |
assert tracker.update(blue,[person],.02)[1]=='athlete_appearance_conflict'
|
| 177 |
|
| 178 |
|
| 179 |
+
def test_neighboring_images_reject_an_isolated_2d_detector_error_without_inventing_points():
|
| 180 |
+
import cv2
|
| 181 |
+
from baseball_batting.motion_evidence import flow_support,observation_weights
|
| 182 |
+
rng=np.random.default_rng(6);source=cv2.GaussianBlur(rng.integers(0,255,(512,512),dtype=np.uint8),(5,5),0)
|
| 183 |
+
middle=cv2.warpAffine(source,np.float32([[1,0,4],[0,1,0]]),(512,512),borderMode=cv2.BORDER_REFLECT)
|
| 184 |
+
future=cv2.warpAffine(source,np.float32([[1,0,8],[0,1,0]]),(512,512),borderMode=cv2.BORDER_REFLECT)
|
| 185 |
+
score=np.ones(1);wrong=np.array([[288.,256.]])
|
| 186 |
+
f,ft=flow_support(source,middle,np.array([[256.,256.]]),wrong,score,score,.45)
|
| 187 |
+
b,bt=flow_support(future,middle,np.array([[264.,256.]]),wrong,score,score,.45)
|
| 188 |
+
assert ft[0] and bt[0] and not f[0] and not b[0]
|
| 189 |
+
assert observation_weights(score,f,ft,b,bt)[0]==.25
|
| 190 |
+
correct=np.array([[260.,256.]])
|
| 191 |
+
f,ft=flow_support(source,middle,np.array([[256.,256.]]),correct,score,score,.45)
|
| 192 |
+
b,bt=flow_support(future,middle,np.array([[264.,256.]]),correct,score,score,.45)
|
| 193 |
+
assert observation_weights(score,f,ft,b,bt)[0]==1.
|
| 194 |
+
# One corroborating neighbor wins over the other pair's failed observation.
|
| 195 |
+
assert observation_weights(score,np.array([False]),np.array([True]),np.array([True]),np.array([True]))[0]==1.
|
| 196 |
+
|
| 197 |
+
|
| 198 |
def test_camera_input_preserves_legacy_sam_contract_and_rejects_bad_distortion():
|
| 199 |
camera={'fx':700,'fy':690,'cx':320,'cy':240,'source':'calibration fixture','distortion':[-.2,.03,.001,-.002,.01]}
|
| 200 |
options=MotionInput(camera=camera)
|
|
|
|
| 244 |
assert len(metadata['windows'])==2
|
| 245 |
|
| 246 |
|
| 247 |
+
@pytest.mark.parametrize('sensitivity_failure',[False,True])
|
| 248 |
+
def test_continuous_fit_has_no_artificial_derivative_seams_between_quality_windows(monkeypatch,sensitivity_failure):
|
| 249 |
+
import baseball_batting.motion_refinement as module
|
| 250 |
+
_,pose,camera,_,points,pixels,times,k=articulated_fixture(70);n=len(times)
|
| 251 |
+
body=np.full((n,70,3),np.nan);body[:,list(INDICES)]=points-camera[:,None]
|
| 252 |
+
raw={'points_body':body,'camera_translation':camera,'intrinsics':k,'projection_valid':np.ones(n,bool),
|
| 253 |
+
'projection':np.full((n,70,2),np.nan),'image_size':np.array([640,480])}
|
| 254 |
+
evidence={'pixels':pixels,'weights':np.ones((n,20)),'box_heights':np.full(n,300),'frame_usable':np.ones(n,bool)}
|
| 255 |
+
calls=[]
|
| 256 |
+
def known_fit(forward,p,c,target,*args,**kwargs):
|
| 257 |
+
calls.append(len(p))
|
| 258 |
+
if sensitivity_failure and len(calls)==2:raise FloatingPointError('Injected sensitivity failure')
|
| 259 |
+
return {'points_camera':target.copy(),'projection':pixels.copy(),'pose':p.copy(),'camera':c.copy(),
|
| 260 |
+
'normalized_initializer':target.copy()}
|
| 261 |
+
monkeypatch.setattr(module,'fit_window',known_fit)
|
| 262 |
+
result,metadata=refine_sequence(lambda ids:None,{'pose':pose,'camera':camera},raw,evidence,times,
|
| 263 |
+
RefinementSettings().model_dump(),.1,device='cpu')
|
| 264 |
+
assert calls==[n,n,n] # One complete trajectory, plus its two sensitivity fits.
|
| 265 |
+
assert len(metadata['windows'])>1 and result['refinement_accepted'].all()
|
| 266 |
+
assert not result['refinement_boundary'].any()
|
| 267 |
+
assert len(np.unique(result['sequence_ids']))==1
|
| 268 |
+
if sensitivity_failure:
|
| 269 |
+
assert not result['refinement_scenario_valid'][0].any()
|
| 270 |
+
assert all(not w['sensitivity_complete'] for w in metadata['windows'])
|
| 271 |
+
|
| 272 |
+
|
| 273 |
def test_supported_fast_peak_cannot_be_delayed_by_fitting():
|
| 274 |
_,_,_,_,truth,pixels,times,k=articulated_fixture(25)
|
| 275 |
candidate=np.concatenate([truth[:1].repeat(3,axis=0),truth[:-3]])
|