Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
11fcb85
1
Parent(s): 0a35b6f
Automated Deploy: ee9c9933ade3954259ef5fb181831dae8ea45062
Browse files- baseball_batting/api.py +1 -1
- baseball_batting/motion_contract.py +1 -0
- baseball_batting/motion_export.py +25 -5
- baseball_batting/motion_refine_worker.py +19 -10
- baseball_batting/motion_refinement.py +69 -21
- baseball_batting/motion_tracking.py +3 -0
- docs/MOTION_PLAYER_API.md +15 -3
- docs/motion-input.schema.json +7 -0
- tests/test_motion_refinement.py +33 -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.1", 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
|
@@ -29,6 +29,7 @@ class RefinementSettings(Strict):
|
|
| 29 |
maximum_bone_change_fraction: float = Field(default=.06, gt=0, le=.2)
|
| 30 |
temporal_weight: float = Field(default=.02, ge=0, le=1)
|
| 31 |
initializer_weight: float = Field(default=.1, gt=0, le=10)
|
|
|
|
| 32 |
maximum_peak_time_shift_s: float = Field(default=.025, gt=0, le=.1)
|
| 33 |
maximum_peak_speed_change_fraction: float = Field(default=.2, gt=0, le=.5)
|
| 34 |
maximum_static_background_motion_fraction: float = Field(default=.003, gt=0, le=.05)
|
|
|
|
| 29 |
maximum_bone_change_fraction: float = Field(default=.06, gt=0, le=.2)
|
| 30 |
temporal_weight: float = Field(default=.02, ge=0, le=1)
|
| 31 |
initializer_weight: float = Field(default=.1, gt=0, le=10)
|
| 32 |
+
initializer_scale_body_fraction: float = Field(default=.03, ge=.005, le=.1)
|
| 33 |
maximum_peak_time_shift_s: float = Field(default=.025, gt=0, le=.1)
|
| 34 |
maximum_peak_speed_change_fraction: float = Field(default=.2, gt=0, le=.5)
|
| 35 |
maximum_static_background_motion_fraction: float = Field(default=.003, gt=0, le=.05)
|
baseball_batting/motion_export.py
CHANGED
|
@@ -51,6 +51,18 @@ def _jsonl(path, records):
|
|
| 51 |
|
| 52 |
def _calculate(corrected, times, options, known):
|
| 53 |
groups, contexts = calculate_measurements(corrected, times, options.sam_options(), clock_known=known)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
if options.model=='gvhmr':
|
| 55 |
for swings in groups.values():
|
| 56 |
for swing in swings:
|
|
@@ -140,7 +152,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 140 |
if not usable.any(): raise ValueError('no_usable_motion')
|
| 141 |
groups,contexts=_calculate(corrected,times,calculation_options,known)
|
| 142 |
baseline=next((c['baseline'] for c in contexts if corrected['valid'][c['baseline'],[9,10]].all()),int(np.flatnonzero(usable)[0]))
|
| 143 |
-
rotation,reference=orientation(corrected['points_relative'],
|
| 144 |
if rotation is None: rotation=np.eye(3); reference='camera_oriented_hip_relative'
|
| 145 |
scale=options.scale_factor
|
| 146 |
positions=corrected['points_relative']@rotation.T*scale
|
|
@@ -203,6 +215,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 203 |
motion_rows.append(row.model_dump(mode='json'))
|
| 204 |
projection_rows.append(ProjectionFrame(**common,image_width=frame['width'],image_height=frame['height'],
|
| 205 |
camera_intrinsics=_finite(k),camera_distortion=distortion,joints=projected).model_dump(mode='json'))
|
|
|
|
| 206 |
_jsonl(job/'motion.jsonl',motion_rows)
|
| 207 |
if projection_count:_jsonl(job/'projections.jsonl',projection_rows)
|
| 208 |
progress('motion_artifacts',n,n)
|
|
@@ -258,11 +271,17 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 258 |
# Recompute each summary from alternate accepted rig fits, rather than
|
| 259 |
# interpreting a positional residual as an angular/timing error bar.
|
| 260 |
alternative_values=[]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
for scenario,accepted_scenario in zip(raw.get('refinement_scenario_points_body',[]),raw.get('refinement_scenario_valid',[])):
|
| 262 |
hip=(scenario[:,9]+scenario[:,10])/2
|
| 263 |
alternate={'points_relative':np.where(corrected['valid'][...,None],scenario-hip[:,None],np.nan),
|
| 264 |
'boundary':corrected['boundary']}
|
| 265 |
-
alternate_groups,_=_calculate(alternate,times,
|
| 266 |
alternative_values.append(({(s.rep,m.key):m.value for swings in alternate_groups.values() for s in swings for m in s.measurements},accepted_scenario))
|
| 267 |
for summary in summaries:
|
| 268 |
context=next((c for c in contexts if c['rep']==summary['rep']),None)
|
|
@@ -274,13 +293,14 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 274 |
if value is not None:values.append(value)
|
| 275 |
complete=bool(alternative_values and len(values)==len(alternative_values) and summary['value'] is not None)
|
| 276 |
summary['stability']={'kind':'temporal_regularization_sensitivity; not an accuracy interval',
|
|
|
|
| 277 |
'status':'evaluated' if complete else 'not_evaluated',
|
| 278 |
'reason_code':None if complete else 'accepted_alternative_fits_required_for_complete_swing',
|
| 279 |
'minimum':min([summary['value'],*values]) if complete else None,
|
| 280 |
'maximum':max([summary['value'],*values]) if complete else None,'unit':summary['unit']}
|
| 281 |
atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
|
| 282 |
-
|
| 283 |
-
'calculation_inputs':
|
| 284 |
atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
|
| 285 |
atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
|
| 286 |
'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
|
|
@@ -349,7 +369,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 349 |
'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
|
| 350 |
'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
|
| 351 |
'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
|
| 352 |
-
'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics); add root exactly once',
|
| 353 |
'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
|
| 354 |
'lead_foot':options.lead_foot or {'right':'left','left':'right'}.get(options.handedness),
|
| 355 |
'lead_foot_source':options.lead_foot_source or ('caller_supplied' if options.lead_foot else 'inferred_from_handedness' if options.handedness else None)},
|
|
|
|
| 51 |
|
| 52 |
def _calculate(corrected, times, options, known):
|
| 53 |
groups, contexts = calculate_measurements(corrected, times, options.sam_options(), clock_known=known)
|
| 54 |
+
if options.camera_stability!='fixed_verified':
|
| 55 |
+
# Camera rotation changes camera-oriented hip-relative vectors too.
|
| 56 |
+
dependent={'head_excursion_relative_cm','hand_speed_relative_m_s','hands_peak_time_ms','shoulder_to_hands_ms'}
|
| 57 |
+
for swings in groups.values():
|
| 58 |
+
for swing in swings:
|
| 59 |
+
swing.movement_peak_order=None;swing.peak_order_reason_code='camera_stability_unverified'
|
| 60 |
+
for metric in swing.measurements:
|
| 61 |
+
if metric.key in dependent:
|
| 62 |
+
metric.value=None;metric.status='unavailable';metric.reason_code='camera_stability_unverified'
|
| 63 |
+
for context in contexts:
|
| 64 |
+
for key in dependent:context['curves'][key][:]=np.nan
|
| 65 |
+
context['peaks']['hands']=None
|
| 66 |
if options.model=='gvhmr':
|
| 67 |
for swings in groups.values():
|
| 68 |
for swing in swings:
|
|
|
|
| 152 |
if not usable.any(): raise ValueError('no_usable_motion')
|
| 153 |
groups,contexts=_calculate(corrected,times,calculation_options,known)
|
| 154 |
baseline=next((c['baseline'] for c in contexts if corrected['valid'][c['baseline'],[9,10]].all()),int(np.flatnonzero(usable)[0]))
|
| 155 |
+
rotation,reference=orientation(corrected['points_relative'],calculation_options,baseline)
|
| 156 |
if rotation is None: rotation=np.eye(3); reference='camera_oriented_hip_relative'
|
| 157 |
scale=options.scale_factor
|
| 158 |
positions=corrected['points_relative']@rotation.T*scale
|
|
|
|
| 215 |
motion_rows.append(row.model_dump(mode='json'))
|
| 216 |
projection_rows.append(ProjectionFrame(**common,image_width=frame['width'],image_height=frame['height'],
|
| 217 |
camera_intrinsics=_finite(k),camera_distortion=distortion,joints=projected).model_dump(mode='json'))
|
| 218 |
+
if distortion is None:projection_rows[-1].pop('camera_distortion')
|
| 219 |
_jsonl(job/'motion.jsonl',motion_rows)
|
| 220 |
if projection_count:_jsonl(job/'projections.jsonl',projection_rows)
|
| 221 |
progress('motion_artifacts',n,n)
|
|
|
|
| 271 |
# Recompute each summary from alternate accepted rig fits, rather than
|
| 272 |
# interpreting a positional residual as an angular/timing error bar.
|
| 273 |
alternative_values=[]
|
| 274 |
+
from .sam_batting_contract import SwingWindow
|
| 275 |
+
directions={s.rep:s.forward_rotation_sign for s in groups['rotation']}
|
| 276 |
+
sensitivity_windows=[SwingWindow.model_validate({**c['window'],'baseline_frame':c['baseline'],
|
| 277 |
+
'forward_start_frame':c['forward_start'],'forward_end_frame':c['forward_end'],
|
| 278 |
+
'forward_rotation_sign':directions.get(c['rep'])}) for c in contexts]
|
| 279 |
+
sensitivity_options=calculation_options.model_copy(update={'windows':sensitivity_windows})
|
| 280 |
for scenario,accepted_scenario in zip(raw.get('refinement_scenario_points_body',[]),raw.get('refinement_scenario_valid',[])):
|
| 281 |
hip=(scenario[:,9]+scenario[:,10])/2
|
| 282 |
alternate={'points_relative':np.where(corrected['valid'][...,None],scenario-hip[:,None],np.nan),
|
| 283 |
'boundary':corrected['boundary']}
|
| 284 |
+
alternate_groups,_=_calculate(alternate,times,sensitivity_options,known)
|
| 285 |
alternative_values.append(({(s.rep,m.key):m.value for swings in alternate_groups.values() for s in swings for m in s.measurements},accepted_scenario))
|
| 286 |
for summary in summaries:
|
| 287 |
context=next((c for c in contexts if c['rep']==summary['rep']),None)
|
|
|
|
| 293 |
if value is not None:values.append(value)
|
| 294 |
complete=bool(alternative_values and len(values)==len(alternative_values) and summary['value'] is not None)
|
| 295 |
summary['stability']={'kind':'temporal_regularization_sensitivity; not an accuracy interval',
|
| 296 |
+
'window_scope':'main_analysis_swing_windows_and_baselines_held_fixed',
|
| 297 |
'status':'evaluated' if complete else 'not_evaluated',
|
| 298 |
'reason_code':None if complete else 'accepted_alternative_fits_required_for_complete_swing',
|
| 299 |
'minimum':min([summary['value'],*values]) if complete else None,
|
| 300 |
'maximum':max([summary['value'],*values]) if complete else None,'unit':summary['unit']}
|
| 301 |
atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
|
| 302 |
+
'definition_version':definition_version,'summaries':summaries,'series':series,
|
| 303 |
+
'calculation_inputs':calculation_options.model_dump(mode='json')})
|
| 304 |
atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
|
| 305 |
atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
|
| 306 |
'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
|
|
|
|
| 369 |
'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
|
| 370 |
'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
|
| 371 |
'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
|
| 372 |
+
'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics'+(', camera_distortion' if distortion is not None else '')+'); add root exactly once',
|
| 373 |
'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
|
| 374 |
'lead_foot':options.lead_foot or {'right':'left','left':'right'}.get(options.handedness),
|
| 375 |
'lead_foot_source':options.lead_foot_source or ('caller_supplied' if options.lead_foot else 'inferred_from_handedness' if options.handedness else None)},
|
baseball_batting/motion_refine_worker.py
CHANGED
|
@@ -16,19 +16,22 @@ def load_adapter(job,record,model,raw,device='cuda'):
|
|
| 16 |
with np.load(job/'sam-parameters-private.npz',allow_pickle=False) as a:data=dict(a)
|
| 17 |
native=MHRForward(record['mhr_path'],job/'sam-mhr-adapter-private.npz',device)
|
| 18 |
motion=data['mhr_model_params']
|
| 19 |
-
if motion.shape[1]!=204:raise ValueError('
|
| 20 |
-
parameters={'pose':motion[:,:136],'camera':raw['camera_translation']
|
|
|
|
| 21 |
def factory(segment):
|
| 22 |
shape=tensor(np.nanmedian(data['shape_params'][segment],axis=0))
|
| 23 |
scales=tensor(np.nanmedian(motion[segment,136:],axis=0))
|
| 24 |
# Check native forward conventions before changing shape or pose.
|
| 25 |
-
first=segment[0]
|
| 26 |
with torch.no_grad():
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
| 32 |
def forward(pose,camera):
|
| 33 |
# Fix native translation; camera is the single translation gauge.
|
| 34 |
pose=torch.cat([pose[:,:3].detach(),pose[:,3:]],1)
|
|
@@ -55,7 +58,7 @@ def load_adapter(job,record,model,raw,device='cuda'):
|
|
| 55 |
first=segment[0]
|
| 56 |
with torch.no_grad():original=forward(tensor(parameters['pose'][first:first+1]),tensor(parameters['camera'][first:first+1]))[0].cpu().numpy()
|
| 57 |
expected=raw['points_body'][first,list(INDICES)]+raw['camera_translation'][first]
|
| 58 |
-
if np.max(np.linalg.norm(original-expected,axis=-1))>.001:raise ValueError('
|
| 59 |
return forward
|
| 60 |
return parameters,factory
|
| 61 |
|
|
@@ -73,6 +76,8 @@ def run(request):
|
|
| 73 |
raw['sequence_ids']=np.asarray(raw.get('sequence_ids',np.zeros(len(parameters['pose']),int)))*(len(parameters['pose'])+1)+evidence['sequence_ids']
|
| 74 |
def progress(stage,done,total):atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total})
|
| 75 |
refined,metadata=refine_sequence(factory,parameters,raw,evidence,np.array(request['times']),request['settings'],request['max_gap_s'],progress=progress)
|
|
|
|
|
|
|
| 76 |
if 'distortion' in evidence:refined['distortion']=evidence['distortion']
|
| 77 |
# Private parameter/candidate arrays never enter the artifact allowlist.
|
| 78 |
np.savez_compressed(job/'motion-refined-private.npz',**refined)
|
|
@@ -84,8 +89,12 @@ def main():
|
|
| 84 |
request=read_json(args.request)
|
| 85 |
try:run(request);return 0
|
| 86 |
except Exception as error:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
atomic_json(Path(request['job'])/'motion-refinement-error-private.json',
|
| 88 |
-
{'reason_code':
|
| 89 |
print(type(error).__name__+': '+str(error),flush=True);return 1
|
| 90 |
|
| 91 |
|
|
|
|
| 16 |
with np.load(job/'sam-parameters-private.npz',allow_pickle=False) as a:data=dict(a)
|
| 17 |
native=MHRForward(record['mhr_path'],job/'sam-mhr-adapter-private.npz',device)
|
| 18 |
motion=data['mhr_model_params']
|
| 19 |
+
if motion.shape[1]!=204:raise ValueError('refinement_mhr_parameter_topology_mismatch')
|
| 20 |
+
parameters={'pose':motion[:,:136],'camera':raw['camera_translation'],
|
| 21 |
+
'native_reconstruction_error_m':np.full(len(motion),np.nan)}
|
| 22 |
def factory(segment):
|
| 23 |
shape=tensor(np.nanmedian(data['shape_params'][segment],axis=0))
|
| 24 |
scales=tensor(np.nanmedian(motion[segment,136:],axis=0))
|
| 25 |
# Check native forward conventions before changing shape or pose.
|
|
|
|
| 26 |
with torch.no_grad():
|
| 27 |
+
for start in range(0,len(segment),4):
|
| 28 |
+
take=segment[start:start+4]
|
| 29 |
+
original=native(tensor(data['shape_params'][take]),tensor(motion[take,:136]),
|
| 30 |
+
tensor(motion[take,136:]),tensor(raw['camera_translation'][take]))[:,list(INDICES)].cpu().numpy()
|
| 31 |
+
expected=raw['points_body'][take][:,list(INDICES)]+raw['camera_translation'][take,None]
|
| 32 |
+
error=np.max(np.linalg.norm(original-expected,axis=-1),axis=-1)
|
| 33 |
+
parameters['native_reconstruction_error_m'][take]=error
|
| 34 |
+
if np.max(error)>.001:raise ValueError('refinement_mhr_native_reconstruction_mismatch')
|
| 35 |
def forward(pose,camera):
|
| 36 |
# Fix native translation; camera is the single translation gauge.
|
| 37 |
pose=torch.cat([pose[:,:3].detach(),pose[:,3:]],1)
|
|
|
|
| 58 |
first=segment[0]
|
| 59 |
with torch.no_grad():original=forward(tensor(parameters['pose'][first:first+1]),tensor(parameters['camera'][first:first+1]))[0].cpu().numpy()
|
| 60 |
expected=raw['points_body'][first,list(INDICES)]+raw['camera_translation'][first]
|
| 61 |
+
if np.max(np.linalg.norm(original-expected,axis=-1))>.001:raise ValueError('refinement_smplx_native_reconstruction_mismatch')
|
| 62 |
return forward
|
| 63 |
return parameters,factory
|
| 64 |
|
|
|
|
| 76 |
raw['sequence_ids']=np.asarray(raw.get('sequence_ids',np.zeros(len(parameters['pose']),int)))*(len(parameters['pose'])+1)+evidence['sequence_ids']
|
| 77 |
def progress(stage,done,total):atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total})
|
| 78 |
refined,metadata=refine_sequence(factory,parameters,raw,evidence,np.array(request['times']),request['settings'],request['max_gap_s'],progress=progress)
|
| 79 |
+
errors=parameters.get('native_reconstruction_error_m')
|
| 80 |
+
if errors is not None and np.isfinite(errors).any():metadata['maximum_native_parameter_reconstruction_error_m']=float(np.nanmax(errors))
|
| 81 |
if 'distortion' in evidence:refined['distortion']=evidence['distortion']
|
| 82 |
# Private parameter/candidate arrays never enter the artifact allowlist.
|
| 83 |
np.savez_compressed(job/'motion-refined-private.npz',**refined)
|
|
|
|
| 89 |
request=read_json(args.request)
|
| 90 |
try:run(request);return 0
|
| 91 |
except Exception as error:
|
| 92 |
+
code=str(error) if isinstance(error,ValueError) and str(error) in {
|
| 93 |
+
'refinement_mhr_parameter_topology_mismatch','refinement_mhr_native_reconstruction_mismatch',
|
| 94 |
+
'refinement_smplx_native_reconstruction_mismatch'} else (
|
| 95 |
+
'refinement_gpu_memory_exhausted' if type(error).__name__=='OutOfMemoryError' else 'native_refinement_failed')
|
| 96 |
atomic_json(Path(request['job'])/'motion-refinement-error-private.json',
|
| 97 |
+
{'reason_code':code,'error_type':type(error).__name__})
|
| 98 |
print(type(error).__name__+': '+str(error),flush=True);return 1
|
| 99 |
|
| 100 |
|
baseball_batting/motion_refinement.py
CHANGED
|
@@ -11,10 +11,13 @@ VERSION = 'native-body-refinement-v1'
|
|
| 11 |
NAMES = tuple(MHR)
|
| 12 |
INDICES = tuple(MHR.values())
|
| 13 |
LOCAL = {name:i for i,name in enumerate(NAMES)}
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
-
def continuous_windows(valid,times,sequence,maximum,context,max_gap):
|
| 18 |
"""One owner per source frame; missing frames/clocks/model boundaries split fits."""
|
| 19 |
for run in segments(valid,times,max_gap):
|
| 20 |
for ids in np.split(run,np.flatnonzero(np.diff(sequence[run])!=0)+1):
|
|
@@ -23,9 +26,18 @@ def continuous_windows(valid,times,sequence,maximum,context,max_gap):
|
|
| 23 |
if len(ids)<=maximum:
|
| 24 |
yield ids,ids
|
| 25 |
else:
|
| 26 |
-
|
|
|
|
| 27 |
end=min(start+core,len(ids))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
yield ids[max(0,start-context):min(len(ids),end+context)],ids[start:end]
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def project_torch(points,k,distortion=None):
|
|
@@ -63,7 +75,11 @@ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_he
|
|
| 63 |
"""
|
| 64 |
import torch
|
| 65 |
def tensor(v):return torch.as_tensor(v,dtype=torch.float32,device=device)
|
| 66 |
-
initial_pose=tensor(pose);initial_camera=tensor(camera)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
p=torch.nn.Parameter(initial_pose.clone());c=torch.nn.Parameter(initial_camera.clone())
|
| 68 |
w=tensor(weights);observed=tensor(np.nan_to_num(pixels));k=tensor(intrinsics)
|
| 69 |
heights=tensor(box_heights).clamp(min=1)
|
|
@@ -75,21 +91,32 @@ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_he
|
|
| 75 |
sigma=heights[:,None]*settings['observation_scale_box_fraction']
|
| 76 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 77 |
initial_relative=target-target[:,hip].mean(1)[:,None]
|
|
|
|
| 78 |
speed=(initial_relative[1:]-initial_relative[:-1]).norm(dim=-1)/dt[:,None]
|
|
|
|
| 79 |
# Fast motion receives a larger allowable curvature. No speed rejection.
|
| 80 |
tolerance=(.005*size+.03*torch.maximum(speed[:-1],speed[1:])*
|
| 81 |
((dt[:-1]+dt[1:])/2)[:,None]).detach()
|
|
|
|
|
|
|
| 82 |
def evaluate():
|
| 83 |
xyz=forward(p,c)
|
| 84 |
projected=project_torch(xyz,k,distortion)
|
| 85 |
e=(projected-observed)/sigma[...,None]
|
| 86 |
image=((torch.sqrt(1+e.square().sum(-1))-1)*w).sum()/w.sum().clamp(min=1)
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
relative=xyz-xyz[:,hip].mean(1)[:,None]
|
| 89 |
fraction=(dt[:-1]/(dt[:-1]+dt[1:]))[:,None,None]
|
| 90 |
middle=relative[:-2]+fraction*(relative[2:]-relative[:-2])
|
| 91 |
q=(relative[1:-1]-middle)/tolerance[...,None]
|
| 92 |
temporal=(torch.sqrt(1+q.square().sum(-1))-1).mean()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
cheirality=torch.relu(.02-xyz[...,2]).square().mean()
|
| 94 |
# Native coordinate units differ. A weak parameter anchor complements
|
| 95 |
# the unitless 3D anchor; no invented anatomical angle limits are used.
|
|
@@ -98,27 +125,36 @@ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_he
|
|
| 98 |
return loss,xyz,projected
|
| 99 |
optimizer=torch.optim.Adam([p,c],lr=settings['learning_rate'])
|
| 100 |
best=float('inf');best_pose=p.detach().clone();best_camera=c.detach().clone()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
for _ in range(settings['iterations']):
|
| 102 |
-
optimizer.zero_grad();loss,
|
| 103 |
if not torch.isfinite(loss):raise ValueError('refinement_nonfinite_objective')
|
| 104 |
value=float(loss.detach())
|
| 105 |
-
if value<best:best=value;best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 106 |
-
loss.backward()
|
|
|
|
|
|
|
|
|
|
| 107 |
with torch.no_grad():
|
| 108 |
-
loss,
|
| 109 |
-
if torch.isfinite(loss) and float(loss)<best:best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 110 |
xyz=forward(best_pose,best_camera);xy=project_torch(xyz,k,distortion)
|
| 111 |
return {'points_camera':xyz.detach().cpu().numpy(),'projection':xy.detach().cpu().numpy(),
|
| 112 |
-
'pose':best_pose.cpu().numpy(),'camera':best_camera.cpu().numpy()
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
-
def acceptance(original,candidate,original_xy,candidate_xy,pixels,weights,times,box_heights,settings):
|
| 116 |
"""Independent diagnostics, beyond the optimizer's scalar objective.
|
| 117 |
|
| 118 |
Thresholds are configurable engineering gates, not validated accuracy limits.
|
| 119 |
Accept/reject a complete window to avoid framewise replacement artifacts.
|
| 120 |
"""
|
| 121 |
-
|
|
|
|
| 122 |
if size is None or not np.isfinite(candidate).all() or (candidate[...,2]<=0).any():
|
| 123 |
return False,{'reasons':['nonfinite_or_invalid_body_geometry']}
|
| 124 |
observed=(weights>0)&np.isfinite(pixels).all(-1)
|
|
@@ -133,14 +169,16 @@ def acceptance(original,candidate,original_xy,candidate_xy,pixels,weights,times,
|
|
| 133 |
if after>before+1e-5:reasons.append('image_alignment_worsened')
|
| 134 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 135 |
old=original-original[:,hip].mean(1)[:,None];new=candidate-candidate[:,hip].mean(1)[:,None]
|
| 136 |
-
|
|
|
|
|
|
|
| 137 |
if change>settings['maximum_body_change_fraction']:reasons.append('excessive_body_adjustment')
|
| 138 |
bone_change=0.
|
| 139 |
for a,b in EDGES:
|
| 140 |
lengths=np.linalg.norm(new[:,a]-new[:,b],axis=-1)
|
| 141 |
-
baseline=np.
|
| 142 |
-
if baseline>size*.01:
|
| 143 |
-
bone_change=max(bone_change,float(np.max(np.abs(lengths-baseline)
|
| 144 |
if bone_change>settings['maximum_bone_change_fraction']:reasons.append('body_proportions_changed')
|
| 145 |
# A fast, image-supported hand peak cannot be erased or moved by smoothing.
|
| 146 |
peak_checks=[]
|
|
@@ -168,6 +206,7 @@ def acceptance(original,candidate,original_xy,candidate_xy,pixels,weights,times,
|
|
| 168 |
if ratio>settings['maximum_peak_speed_change_fraction']:reasons.append('fast_hand_peak_distorted')
|
| 169 |
return not reasons,{'reasons':sorted(set(reasons)),'image_error_before_box_fraction':before,
|
| 170 |
'image_error_after_box_fraction':after,'maximum_body_adjustment_fraction':change,
|
|
|
|
| 171 |
'maximum_bone_change_fraction':bone_change,'fast_hand_peak_checks':peak_checks}
|
| 172 |
|
| 173 |
|
|
@@ -177,6 +216,13 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 177 |
points=raw['points_body'][:,indices]+raw['camera_translation'][:,None]
|
| 178 |
valid=np.isfinite(points).all((1,2))&raw['projection_valid']&evidence['frame_usable']
|
| 179 |
sequence=np.asarray(raw.get('sequence_ids',np.zeros(n,int)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
accepted=np.zeros(n,bool);sensitivity=np.full((n,70),np.nan);boundaries=np.zeros(n,bool)
|
| 181 |
scenarios=np.repeat(raw['points_body'][None],len(settings['sensitivity_factors']),axis=0)
|
| 182 |
scenario_valid=np.zeros((len(scenarios),n),bool)
|
|
@@ -188,7 +234,7 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 188 |
if len(segment)<4:continue
|
| 189 |
forward=forward_factory(segment)
|
| 190 |
local_valid=np.zeros(n,bool);local_valid[segment]=True
|
| 191 |
-
for ids,owned in continuous_windows(local_valid,times,sequence,settings['window_frames'],settings['context_frames'],max_gap):
|
| 192 |
take=np.searchsorted(ids,owned)
|
| 193 |
pixels=evidence['pixels'][ids];weights=evidence['weights'][ids]
|
| 194 |
arguments=(forward,parameters['pose'][ids],parameters['camera'][ids],points[ids],pixels,weights,
|
|
@@ -198,14 +244,14 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 198 |
from .geometry import project
|
| 199 |
original_xy=np.stack([project(p,k,distortion) for p,k in zip(points[ids],raw['intrinsics'][ids])])
|
| 200 |
ok,checks=acceptance(points[ids],fit['points_camera'],original_xy,fit['projection'],pixels,weights,
|
| 201 |
-
times[ids],evidence['box_heights'][ids],settings)
|
| 202 |
maximum=np.zeros((len(ids),len(indices)))
|
| 203 |
sensitivity_complete=True
|
| 204 |
if ok:
|
| 205 |
for scenario_index,factor in enumerate(settings['sensitivity_factors']):
|
| 206 |
alternative=fit_window(*arguments,distortion=distortion,device=device,temporal_factor=factor)
|
| 207 |
good,_=acceptance(points[ids],alternative['points_camera'],original_xy,alternative['projection'],pixels,weights,
|
| 208 |
-
times[ids],evidence['box_heights'][ids],settings)
|
| 209 |
if not good:sensitivity_complete=False
|
| 210 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 211 |
alt_relative=alternative['points_camera']-alternative['points_camera'][:,hip].mean(1)[:,None]
|
|
@@ -223,7 +269,8 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 223 |
if sensitivity_complete:sensitivity[np.ix_(owned,indices)]=maximum[take]
|
| 224 |
checks['sensitivity_complete']=sensitivity_complete if ok else False
|
| 225 |
except (ValueError,FloatingPointError) as error:
|
| 226 |
-
|
|
|
|
| 227 |
windows.append({'start_frame':int(owned[0]),'end_frame':int(owned[-1]),
|
| 228 |
'context_start_frame':int(ids[0]),'context_end_frame':int(ids[-1]),'accepted':bool(ok),**checks})
|
| 229 |
if len(segment)>settings['window_frames']:
|
|
@@ -256,5 +303,6 @@ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_g
|
|
| 256 |
'gap_interpolation':'disabled; no image evidence invented','parameter_limits':'native_rig_and_initializer_prior; no invented anatomical bounds',
|
| 257 |
'sensitivity_kind':'temporal_regularization_sensitivity; not a calibrated error interval',
|
| 258 |
'sensitivity_factors':settings['sensitivity_factors'],'accuracy_validated':False}
|
|
|
|
| 259 |
metadata['image_conflicting_joint_count']=int(conflict.sum())
|
| 260 |
return result,metadata
|
|
|
|
| 11 |
NAMES = tuple(MHR)
|
| 12 |
INDICES = tuple(MHR.values())
|
| 13 |
LOCAL = {name:i for i,name in enumerate(NAMES)}
|
| 14 |
+
# Torso/shoulder spans and toe tips can legitimately change with articulation.
|
| 15 |
+
# Only long-bone links are used as approximate constant-length diagnostics.
|
| 16 |
+
EDGES = [(LOCAL[side+'_'+a],LOCAL[side+'_'+b]) for side in ('left','right')
|
| 17 |
+
for a,b in (('shoulder','elbow'),('elbow','wrist'),('hip','knee'),('knee','ankle'))]
|
| 18 |
|
| 19 |
|
| 20 |
+
def continuous_windows(valid,times,sequence,maximum,context,max_gap,boundary_scores=None):
|
| 21 |
"""One owner per source frame; missing frames/clocks/model boundaries split fits."""
|
| 22 |
for run in segments(valid,times,max_gap):
|
| 23 |
for ids in np.split(run,np.flatnonzero(np.diff(sequence[run])!=0)+1):
|
|
|
|
| 26 |
if len(ids)<=maximum:
|
| 27 |
yield ids,ids
|
| 28 |
else:
|
| 29 |
+
start=0
|
| 30 |
+
while start<len(ids):
|
| 31 |
end=min(start+core,len(ids))
|
| 32 |
+
if boundary_scores is not None and end<len(ids):
|
| 33 |
+
choices=np.arange(start+max(4,core//2),end+1)
|
| 34 |
+
scores=np.array([np.max(np.asarray(boundary_scores)[ids[max(0,c-2):min(len(ids),c+2)]]) for c in choices])
|
| 35 |
+
if np.isfinite(scores).any():
|
| 36 |
+
# Latest boundary wins ties; otherwise prefer a quiet
|
| 37 |
+
# interval so derivative masks avoid a fast swing peak.
|
| 38 |
+
best=np.nanmin(scores);end=int(choices[np.flatnonzero(scores==best)[-1]])
|
| 39 |
yield ids[max(0,start-context):min(len(ids),end+context)],ids[start:end]
|
| 40 |
+
start=end
|
| 41 |
|
| 42 |
|
| 43 |
def project_torch(points,k,distortion=None):
|
|
|
|
| 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=forward(initial_pose,initial_camera).detach()
|
| 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)
|
|
|
|
| 91 |
sigma=heights[:,None]*settings['observation_scale_box_fraction']
|
| 92 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 93 |
initial_relative=target-target[:,hip].mean(1)[:,None]
|
| 94 |
+
initial_root=target[:,hip].mean(1)
|
| 95 |
speed=(initial_relative[1:]-initial_relative[:-1]).norm(dim=-1)/dt[:,None]
|
| 96 |
+
root_speed=(initial_root[1:]-initial_root[:-1]).norm(dim=-1)/dt
|
| 97 |
# Fast motion receives a larger allowable curvature. No speed rejection.
|
| 98 |
tolerance=(.005*size+.03*torch.maximum(speed[:-1],speed[1:])*
|
| 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=forward(p,c)
|
| 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)
|
| 107 |
+
# A body-size-only denominator implied metre-scale uncertainty and let
|
| 108 |
+
# monocular image fitting move joints far in depth. This explicit prior
|
| 109 |
+
# scale is configurable and is not advertised as a measured error bound.
|
| 110 |
+
prior=((xyz-target)/(size*settings.get('initializer_scale_body_fraction',.03))).square().mean()
|
| 111 |
relative=xyz-xyz[:,hip].mean(1)[:,None]
|
| 112 |
fraction=(dt[:-1]/(dt[:-1]+dt[1:]))[:,None,None]
|
| 113 |
middle=relative[:-2]+fraction*(relative[2:]-relative[:-2])
|
| 114 |
q=(relative[1:-1]-middle)/tolerance[...,None]
|
| 115 |
temporal=(torch.sqrt(1+q.square().sum(-1))-1).mean()
|
| 116 |
+
root=xyz[:,hip].mean(1);f=fraction[:,0]
|
| 117 |
+
root_middle=root[:-2]+f*(root[2:]-root[:-2])
|
| 118 |
+
root_q=(root[1:-1]-root_middle)/root_tolerance[:,None]
|
| 119 |
+
temporal=temporal+(torch.sqrt(1+root_q.square().sum(-1))-1).mean()
|
| 120 |
cheirality=torch.relu(.02-xyz[...,2]).square().mean()
|
| 121 |
# Native coordinate units differ. A weak parameter anchor complements
|
| 122 |
# the unitless 3D anchor; no invented anatomical angle limits are used.
|
|
|
|
| 125 |
return loss,xyz,projected
|
| 126 |
optimizer=torch.optim.Adam([p,c],lr=settings['learning_rate'])
|
| 127 |
best=float('inf');best_pose=p.detach().clone();best_camera=c.detach().clone()
|
| 128 |
+
def feasible(xyz):
|
| 129 |
+
relative=xyz-xyz[:,hip].mean(1)[:,None]
|
| 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();loss,xyz,_=evaluate()
|
| 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=forward(best_pose,best_camera);xy=project_torch(xyz,k,distortion)
|
| 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()}
|
| 148 |
|
| 149 |
|
| 150 |
+
def acceptance(original,candidate,original_xy,candidate_xy,pixels,weights,times,box_heights,settings,reference=None):
|
| 151 |
"""Independent diagnostics, beyond the optimizer's scalar objective.
|
| 152 |
|
| 153 |
Thresholds are configurable engineering gates, not validated accuracy limits.
|
| 154 |
Accept/reject a complete window to avoid framewise replacement artifacts.
|
| 155 |
"""
|
| 156 |
+
reference=original if reference is None else reference
|
| 157 |
+
size=body_size(reference);reasons=[]
|
| 158 |
if size is None or not np.isfinite(candidate).all() or (candidate[...,2]<=0).any():
|
| 159 |
return False,{'reasons':['nonfinite_or_invalid_body_geometry']}
|
| 160 |
observed=(weights>0)&np.isfinite(pixels).all(-1)
|
|
|
|
| 169 |
if after>before+1e-5:reasons.append('image_alignment_worsened')
|
| 170 |
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 171 |
old=original-original[:,hip].mean(1)[:,None];new=candidate-candidate[:,hip].mean(1)[:,None]
|
| 172 |
+
anchor=reference-reference[:,hip].mean(1)[:,None]
|
| 173 |
+
normalization=float(np.max(np.linalg.norm(anchor-old,axis=-1))/size)
|
| 174 |
+
change=float(np.max(np.linalg.norm(new-anchor,axis=-1))/size)
|
| 175 |
if change>settings['maximum_body_change_fraction']:reasons.append('excessive_body_adjustment')
|
| 176 |
bone_change=0.
|
| 177 |
for a,b in EDGES:
|
| 178 |
lengths=np.linalg.norm(new[:,a]-new[:,b],axis=-1)
|
| 179 |
+
baseline=np.linalg.norm(anchor[:,a]-anchor[:,b],axis=-1)
|
| 180 |
+
if np.median(baseline)>size*.01:
|
| 181 |
+
bone_change=max(bone_change,float(np.max(np.abs(lengths-baseline)/np.maximum(baseline,size*.01))))
|
| 182 |
if bone_change>settings['maximum_bone_change_fraction']:reasons.append('body_proportions_changed')
|
| 183 |
# A fast, image-supported hand peak cannot be erased or moved by smoothing.
|
| 184 |
peak_checks=[]
|
|
|
|
| 206 |
if ratio>settings['maximum_peak_speed_change_fraction']:reasons.append('fast_hand_peak_distorted')
|
| 207 |
return not reasons,{'reasons':sorted(set(reasons)),'image_error_before_box_fraction':before,
|
| 208 |
'image_error_after_box_fraction':after,'maximum_body_adjustment_fraction':change,
|
| 209 |
+
'maximum_shared_shape_normalization_fraction':normalization,
|
| 210 |
'maximum_bone_change_fraction':bone_change,'fast_hand_peak_checks':peak_checks}
|
| 211 |
|
| 212 |
|
|
|
|
| 216 |
points=raw['points_body'][:,indices]+raw['camera_translation'][:,None]
|
| 217 |
valid=np.isfinite(points).all((1,2))&raw['projection_valid']&evidence['frame_usable']
|
| 218 |
sequence=np.asarray(raw.get('sequence_ids',np.zeros(n,int)))
|
| 219 |
+
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 220 |
+
relative=points-points[:,hip].mean(1)[:,None]
|
| 221 |
+
activity=np.full(n,np.inf)
|
| 222 |
+
pairs=valid[:-1]&valid[1:]&(sequence[:-1]==sequence[1:])&(np.diff(times)<=max_gap)
|
| 223 |
+
speeds=np.linalg.norm(np.diff(relative,axis=0),axis=-1)/np.diff(times)[:,None]
|
| 224 |
+
if pairs.any():activity[1:][pairs]=np.percentile(speeds[pairs],90,axis=1)
|
| 225 |
+
if n>1:activity[0]=activity[1]
|
| 226 |
accepted=np.zeros(n,bool);sensitivity=np.full((n,70),np.nan);boundaries=np.zeros(n,bool)
|
| 227 |
scenarios=np.repeat(raw['points_body'][None],len(settings['sensitivity_factors']),axis=0)
|
| 228 |
scenario_valid=np.zeros((len(scenarios),n),bool)
|
|
|
|
| 234 |
if len(segment)<4:continue
|
| 235 |
forward=forward_factory(segment)
|
| 236 |
local_valid=np.zeros(n,bool);local_valid[segment]=True
|
| 237 |
+
for ids,owned in continuous_windows(local_valid,times,sequence,settings['window_frames'],settings['context_frames'],max_gap,activity):
|
| 238 |
take=np.searchsorted(ids,owned)
|
| 239 |
pixels=evidence['pixels'][ids];weights=evidence['weights'][ids]
|
| 240 |
arguments=(forward,parameters['pose'][ids],parameters['camera'][ids],points[ids],pixels,weights,
|
|
|
|
| 244 |
from .geometry import project
|
| 245 |
original_xy=np.stack([project(p,k,distortion) for p,k in zip(points[ids],raw['intrinsics'][ids])])
|
| 246 |
ok,checks=acceptance(points[ids],fit['points_camera'],original_xy,fit['projection'],pixels,weights,
|
| 247 |
+
times[ids],evidence['box_heights'][ids],settings,reference=fit['normalized_initializer'])
|
| 248 |
maximum=np.zeros((len(ids),len(indices)))
|
| 249 |
sensitivity_complete=True
|
| 250 |
if ok:
|
| 251 |
for scenario_index,factor in enumerate(settings['sensitivity_factors']):
|
| 252 |
alternative=fit_window(*arguments,distortion=distortion,device=device,temporal_factor=factor)
|
| 253 |
good,_=acceptance(points[ids],alternative['points_camera'],original_xy,alternative['projection'],pixels,weights,
|
| 254 |
+
times[ids],evidence['box_heights'][ids],settings,reference=alternative['normalized_initializer'])
|
| 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]
|
|
|
|
| 269 |
if sensitivity_complete:sensitivity[np.ix_(owned,indices)]=maximum[take]
|
| 270 |
checks['sensitivity_complete']=sensitivity_complete if ok else False
|
| 271 |
except (ValueError,FloatingPointError) as error:
|
| 272 |
+
code=str(error) if str(error) in {'refinement_native_gradients_unavailable','refinement_body_scale_unresolved','refinement_nonfinite_objective'} else 'refinement_numerical_failure'
|
| 273 |
+
ok=False;checks={'reasons':[code],'error_type':type(error).__name__}
|
| 274 |
windows.append({'start_frame':int(owned[0]),'end_frame':int(owned[-1]),
|
| 275 |
'context_start_frame':int(ids[0]),'context_end_frame':int(ids[-1]),'accepted':bool(ok),**checks})
|
| 276 |
if len(segment)>settings['window_frames']:
|
|
|
|
| 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']='prefer low native hand/body activity within bounded windows; unresolved seams remain derivative boundaries'
|
| 307 |
metadata['image_conflicting_joint_count']=int(conflict.sum())
|
| 308 |
return result,metadata
|
baseball_batting/motion_tracking.py
CHANGED
|
@@ -57,6 +57,9 @@ class AthleteRecovery:
|
|
| 57 |
box=np.asarray(selected['box'],float);h,w=image.shape[:2]
|
| 58 |
box=np.maximum([0,0,0,0],np.minimum([w,h,w,h],box))
|
| 59 |
feature=appearance(image,box)
|
|
|
|
|
|
|
|
|
|
| 60 |
if self.box is not None:
|
| 61 |
velocity=(box-self.box)/(t-self.last_time)
|
| 62 |
self.velocity=.5*self.velocity+.5*velocity
|
|
|
|
| 57 |
box=np.asarray(selected['box'],float);h,w=image.shape[:2]
|
| 58 |
box=np.maximum([0,0,0,0],np.minimum([w,h,w,h],box))
|
| 59 |
feature=appearance(image,box)
|
| 60 |
+
if self.template is not None and feature is not None and float(self.template@feature)<self.settings.minimum_appearance_similarity-.15:
|
| 61 |
+
self.lost=True
|
| 62 |
+
return None,'athlete_appearance_conflict'
|
| 63 |
if self.box is not None:
|
| 64 |
velocity=(box-self.box)/(t-self.last_time)
|
| 65 |
self.velocity=.5*self.velocity+.5*velocity
|
docs/MOTION_PLAYER_API.md
CHANGED
|
@@ -117,6 +117,8 @@ not establish physical calibration. Native rig constraints and initializer prior
|
|
| 117 |
apply; no unsupported anatomical angle limits are invented.
|
| 118 |
|
| 119 |
Fitting uses bounded overlapping windows with one owner per original frame.
|
|
|
|
|
|
|
| 120 |
Missing observations, identity/model boundaries and clock gaps split fits.
|
| 121 |
Window boundaries and raw/refined switches are derivative boundaries. No pose
|
| 122 |
is generated through a missing interval. Rapid movement receives weaker temporal
|
|
@@ -154,6 +156,15 @@ the actual inference/refinement runtime must be evaluated on the deployed GPU.
|
|
| 154 |
Options and bounds are published in `/input-schema`. Progress includes
|
| 155 |
`image_motion_evidence`, `loading_native_refinement`, and `whole_body_refinement`.
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
Short person-detection losses can be recovered through consistent predicted box
|
| 158 |
motion, size and torso appearance. Maximum recovery gap defaults to 0.2 s of
|
| 159 |
video time. Ambiguous overlapping people are never recovered on clothing alone.
|
|
@@ -168,8 +179,9 @@ No usable motion, fewer than four decoded frames, invalid timestamps, ambiguous
|
|
| 168 |
athlete selection or inference failure produces a failed job with a reason.
|
| 169 |
|
| 170 |
Multiple plausible athletes require `athlete_box`. Tracking uses conservative
|
| 171 |
-
box
|
| 172 |
-
|
|
|
|
| 173 |
|
| 174 |
## Manifest and artifacts
|
| 175 |
|
|
@@ -237,7 +249,7 @@ camera root in the same export axes/units, **not ground motion**. For projection
|
|
| 237 |
|
| 238 |
```text
|
| 239 |
camera_point = (joint.position + frame.root_translation) @ camera_to_export_rotation
|
| 240 |
-
pixel =
|
| 241 |
```
|
| 242 |
|
| 243 |
Add root exactly once. Uniform scale cancels in perspective division. Projections
|
|
|
|
| 117 |
apply; no unsupported anatomical angle limits are invented.
|
| 118 |
|
| 119 |
Fitting uses bounded overlapping windows with one owner per original frame.
|
| 120 |
+
Core boundaries prefer quieter body/hand movement where the memory bound allows,
|
| 121 |
+
reducing the chance that a derivative boundary removes a swing peak.
|
| 122 |
Missing observations, identity/model boundaries and clock gaps split fits.
|
| 123 |
Window boundaries and raw/refined switches are derivative boundaries. No pose
|
| 124 |
is generated through a missing interval. Rapid movement receives weaker temporal
|
|
|
|
| 156 |
Options and bounds are published in `/input-schema`. Progress includes
|
| 157 |
`image_motion_evidence`, `loading_native_refinement`, and `whole_body_refinement`.
|
| 158 |
|
| 159 |
+
The 3D initializer anchor has an explicit body-relative scale
|
| 160 |
+
(`initializer_scale_body_fraction`, default 0.03), rather than an implicit metre
|
| 161 |
+
of uncertainty. This is a regularization parameter, not a measured accuracy
|
| 162 |
+
bound. Candidate selection respects the pose-adjustment trust region throughout
|
| 163 |
+
optimization. Shared-shape normalization and subsequent pose adjustment are
|
| 164 |
+
reported separately; long-limb diagnostics compare the same pose's normalized
|
| 165 |
+
body, not a constant shoulder/torso span. Native MHR parameters must reproduce
|
| 166 |
+
every fitted source frame within the arithmetic tolerance before fitting.
|
| 167 |
+
|
| 168 |
Short person-detection losses can be recovered through consistent predicted box
|
| 169 |
motion, size and torso appearance. Maximum recovery gap defaults to 0.2 s of
|
| 170 |
video time. Ambiguous overlapping people are never recovered on clothing alone.
|
|
|
|
| 179 |
athlete selection or inference failure produces a failed job with a reason.
|
| 180 |
|
| 181 |
Multiple plausible athletes require `athlete_box`. Tracking uses conservative
|
| 182 |
+
box, motion and appearance agreement, not biometric identity recognition.
|
| 183 |
+
Bounded short losses may be recovered; ambiguous crossings and uncertain frames
|
| 184 |
+
remain unusable.
|
| 185 |
|
| 186 |
## Manifest and artifacts
|
| 187 |
|
|
|
|
| 249 |
|
| 250 |
```text
|
| 251 |
camera_point = (joint.position + frame.root_translation) @ camera_to_export_rotation
|
| 252 |
+
pixel = project(camera_point, projection_frame.camera_intrinsics, optional_camera_distortion)
|
| 253 |
```
|
| 254 |
|
| 255 |
Add root exactly once. Uniform scale cancels in perspective division. Projections
|
docs/motion-input.schema.json
CHANGED
|
@@ -385,6 +385,13 @@
|
|
| 385 |
"title": "Initializer Weight",
|
| 386 |
"type": "number"
|
| 387 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
"maximum_peak_time_shift_s": {
|
| 389 |
"default": 0.025,
|
| 390 |
"exclusiveMinimum": 0,
|
|
|
|
| 385 |
"title": "Initializer Weight",
|
| 386 |
"type": "number"
|
| 387 |
},
|
| 388 |
+
"initializer_scale_body_fraction": {
|
| 389 |
+
"default": 0.03,
|
| 390 |
+
"maximum": 0.1,
|
| 391 |
+
"minimum": 0.005,
|
| 392 |
+
"title": "Initializer Scale Body Fraction",
|
| 393 |
+
"type": "number"
|
| 394 |
+
},
|
| 395 |
"maximum_peak_time_shift_s": {
|
| 396 |
"default": 0.025,
|
| 397 |
"exclusiveMinimum": 0,
|
tests/test_motion_refinement.py
CHANGED
|
@@ -72,6 +72,18 @@ def test_acceptance_rejects_worse_image_alignment_and_deformation():
|
|
| 72 |
assert 'image_alignment_worsened' in checks['reasons']
|
| 73 |
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
def test_windows_preserve_every_owner_and_never_cross_identity_clock_or_missing_frames():
|
| 76 |
t=np.arange(100)/60;t[60:]+=.3;valid=np.ones(100,bool);valid[30:33]=False
|
| 77 |
sequence=np.zeros(100,int);sequence[80:]=1
|
|
@@ -83,6 +95,16 @@ def test_windows_preserve_every_owner_and_never_cross_identity_clock_or_missing_
|
|
| 83 |
assert (owners[valid]==1).all() and (owners[~valid]==0).all()
|
| 84 |
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
def test_torch_and_public_distortion_projection_agree_and_have_gradients():
|
| 87 |
torch=pytest.importorskip('torch')
|
| 88 |
points=torch.tensor([[[.4,.3,2.],[-.3,.2,3.]]],requires_grad=True)
|
|
@@ -122,6 +144,14 @@ def test_ambiguous_crossing_does_not_reidentify_by_clothing_alone():
|
|
| 122 |
assert tracker.update(image,[box(30)],.04)[0] is None
|
| 123 |
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
def test_camera_input_preserves_legacy_sam_contract_and_rejects_bad_distortion():
|
| 126 |
camera={'fx':700,'fy':690,'cx':320,'cy':240,'source':'calibration fixture','distortion':[-.2,.03,.001,-.002,.01]}
|
| 127 |
options=MotionInput(camera=camera)
|
|
@@ -193,6 +223,7 @@ def test_stability_reports_measurement_units_and_camera_conflict_is_reproducible
|
|
| 193 |
{'analysis_id':'fixture','analysis_revision':1},refinement=metadata)
|
| 194 |
assert manifest.pipeline['inputs']['camera_stability']=='fixed_verified'
|
| 195 |
assert manifest.pipeline['calculation_inputs']['camera_stability']=='moving'
|
|
|
|
| 196 |
report=json.loads((tmp_path/'measurements.json').read_text())['summaries']
|
| 197 |
groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
|
| 198 |
values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
|
|
@@ -201,3 +232,5 @@ def test_stability_reports_measurement_units_and_camera_conflict_is_reproducible
|
|
| 201 |
if summary['value'] is not None:
|
| 202 |
assert summary['stability']['status']=='evaluated'
|
| 203 |
assert summary['stability']['minimum']==summary['stability']['maximum']==summary['value']
|
|
|
|
|
|
|
|
|
| 72 |
assert 'image_alignment_worsened' in checks['reasons']
|
| 73 |
|
| 74 |
|
| 75 |
+
def test_ambiguous_image_fit_cannot_select_a_pose_outside_its_trust_region():
|
| 76 |
+
forward,pose,camera,raw,truth,pixels,times,k=articulated_fixture(16)
|
| 77 |
+
pixels[:,LOCAL['left_wrist'],0]+=80
|
| 78 |
+
settings=RefinementSettings(iterations=30,learning_rate=.03,maximum_body_change_fraction=.025).model_dump()
|
| 79 |
+
fit=fit_window(forward,pose,camera,raw,pixels,np.ones(pixels.shape[:2]),times,k,np.full(len(times),300),settings,device='cpu')
|
| 80 |
+
from baseball_batting.motion_refinement import body_size
|
| 81 |
+
hip=[LOCAL['left_hip'],LOCAL['right_hip']]
|
| 82 |
+
a=fit['points_camera']-fit['points_camera'][:,hip].mean(1)[:,None]
|
| 83 |
+
b=fit['normalized_initializer']-fit['normalized_initializer'][:,hip].mean(1)[:,None]
|
| 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
|
|
|
|
| 95 |
assert (owners[valid]==1).all() and (owners[~valid]==0).all()
|
| 96 |
|
| 97 |
|
| 98 |
+
def test_window_seams_prefer_quiet_motion_without_losing_or_duplicating_frames():
|
| 99 |
+
n=70;t=np.arange(n)/60;score=np.ones(n);score[24:43]=100
|
| 100 |
+
windows=list(continuous_windows(np.ones(n,bool),t,np.zeros(n,int),48,8,.1,score))
|
| 101 |
+
owners=np.zeros(n,int)
|
| 102 |
+
for context,core in windows:
|
| 103 |
+
assert len(context)<=48;owners[core]+=1
|
| 104 |
+
if core[-1]!=n-1:assert not 26<=core[-1]<=40
|
| 105 |
+
assert (owners==1).all()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
def test_torch_and_public_distortion_projection_agree_and_have_gradients():
|
| 109 |
torch=pytest.importorskip('torch')
|
| 110 |
points=torch.tensor([[[.4,.3,2.],[-.3,.2,3.]]],requires_grad=True)
|
|
|
|
| 144 |
assert tracker.update(image,[box(30)],.04)[0] is None
|
| 145 |
|
| 146 |
|
| 147 |
+
def test_spatial_overlap_cannot_override_an_appearance_conflict():
|
| 148 |
+
tracker=AthleteRecovery(MotionTrackingSettings());red=np.full((200,300,3),[0,0,255],np.uint8)
|
| 149 |
+
blue=np.full((200,300,3),[255,0,0],np.uint8)
|
| 150 |
+
person={'class_id':0,'score':.9,'box':[30,20,120,180]}
|
| 151 |
+
tracker.update(red,[person],0)
|
| 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)
|
|
|
|
| 223 |
{'analysis_id':'fixture','analysis_revision':1},refinement=metadata)
|
| 224 |
assert manifest.pipeline['inputs']['camera_stability']=='fixed_verified'
|
| 225 |
assert manifest.pipeline['calculation_inputs']['camera_stability']=='moving'
|
| 226 |
+
assert manifest.coordinates['frame']=='camera_oriented_hip_relative'
|
| 227 |
report=json.loads((tmp_path/'measurements.json').read_text())['summaries']
|
| 228 |
groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
|
| 229 |
values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
|
|
|
|
| 232 |
if summary['value'] is not None:
|
| 233 |
assert summary['stability']['status']=='evaluated'
|
| 234 |
assert summary['stability']['minimum']==summary['stability']['maximum']==summary['value']
|
| 235 |
+
for key in ('head_excursion_relative_cm','hand_speed_relative_m_s'):
|
| 236 |
+
assert next(m for m in report if m['metric_id']==key)['value'] is None
|