Datasets:
Download code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/runtime/render.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 39.5 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/runtime/render.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/runtime/render.py
-
curl -L -o render.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/runtime/render.py
39.5 kB
| """One frozen control clock owns all body updates, readback, cameras and frame capture.""" | |
| from dataclasses import asdict | |
| import sys | |
| import hashlib | |
| import math | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| from ..artifacts import Bundle, ContractError, dump, verify_ref | |
| from ..rendering.artifact import StageJournal, TableWriter, chain_version, publish, verify_observation | |
| from ..domain.contracts import observation_id, validate_spec | |
| from ..rendering import validate_release_spec | |
| from ..gen.legjitter import render_check | |
| from ..rendering.coordinates import angular_error, camera_to_world, reference_matrix, reference_to_script | |
| from ..rendering.diagnostics import distribution, pelvis_summary, pixel_bounds | |
| from ..rendering.quality import image_statistics | |
| from ..rendering.visibility import semantic_statistics,subject_measurement,no_body_measurement,in_frustum,view_geometry,FramePixelIndex,viewport_edge_summary | |
| from ..rendering.media import StreamingEncoder, verify_video | |
| from ..rendering.scene import FrameChannels | |
| from ..rendering.sampling import audit_indices,ground_indices | |
| from ..rendering.instance_masks import mask_row | |
| from ..rendering.replay_tolerance import compare_frames,judge,replay_policy,violations | |
| def _evidence_copy(frame): | |
| return FrameChannels(*(getattr(frame,name).copy() for name in | |
| ('rgb','depth','semantic','camera_world_matrix','projection_matrix'))) | |
| def _sample(out,key,frame,identities,label): | |
| from PIL import Image,ImageDraw | |
| rgb=frame.rgb.copy();legend={} | |
| colors=[(255,70,70),(60,160,255),(80,255,100),(255,220,40)] | |
| entries=[(aid,item) for aid,item in identities.items() if item['kind'] in ('actor','observer_body') and item['semantic_id'] is not None] | |
| for (aid,item),color in zip(entries,colors): | |
| mask=frame.semantic==item['semantic_id'];inside=mask.copy() | |
| inside[1:,:]&=mask[:-1,:];inside[:-1,:]&=mask[1:,:];inside[:,1:]&=mask[:,:-1];inside[:,:-1]&=mask[:,1:] | |
| rgb[mask&~inside]=color;legend[aid]=int(mask.sum()) | |
| image=Image.fromarray(rgb);draw=ImageDraw.Draw(image) | |
| draw.rectangle((0,0,image.width,30),fill=(0,0,0));draw.text((6,6), | |
| f'{key.observer_id} frame={key.frame_index} tick={key.control_tick} {label} {legend}',fill=(255,255,255)) | |
| name=f'{key.observer_id}-{key.frame_index:05d}-{label}.png';image.save(out/name) | |
| return dict(**asdict(key),label=label,png=name,pixels=legend) | |
| def _close_all(closers): | |
| """逐项释放:前一项出错不跳过后面的编码器、场景、日志;全部做完后,没有正在传播的异常就抛第一个错。""" | |
| errors = [] | |
| for close in closers: | |
| try: close() | |
| except Exception as error: errors.append(error) | |
| if errors and sys.exc_info()[0] is None: raise errors[0] | |
| def render_script(inputs,spec,out,*,scene_factory,bindings,requested_gpu=None,max_wall_s=600, | |
| code_commit=None,progress_every=20,backend='habitat'): | |
| """Write one new attempt. Existing valid identity skips; bad attempts are never reused/deleted.""" | |
| validate_release_spec(spec) | |
| out=Path(out);version,version_sources=chain_version(backend) | |
| if out.exists(): | |
| existing=verify_observation(out/'observation/artifact.json') | |
| if existing['data'].get('bindings')!=bindings: | |
| raise ContractError('Changed asset binding request requires a new attempt; never reuse old fingerprints') | |
| expected=observation_id(inputs,spec,existing['data']['asset_fingerprints'],chain_version=version) | |
| verify_observation(out/'observation/artifact.json',expected) | |
| return dict(status='SKIPPED',obs_id=expected,artifact=str(out/'observation/artifact.json')) | |
| clock=validate_spec(inputs,spec) | |
| rgb_samples={aid:set(audit_indices(len(keys),spec.rgb_audit_policy)) for aid,keys in clock.frames.items()} | |
| interaction=inputs.script.get('plan_visibility',{}).get('interaction',{}) | |
| step=interaction.get('ground_step_s') | |
| ground_requested=spec.ground_policy.get('status')=='ENABLED' | |
| if ground_requested and (step is None or not math.isfinite(step) or step<=0):raise ContractError('Explicit plan ground sample step required') | |
| span=inputs.script['span_s'];plan_times=np.arange(span[0],span[1]+1e-9,step) if ground_requested else [] | |
| ground_samples={};ground_sampling={} | |
| for aid,keys in clock.frames.items(): | |
| selected,record=ground_indices(keys,spec.ground_sampling,plan_times) | |
| ground_samples[aid]=set(selected);ground_sampling[aid]=record | |
| replay_ticks={key.control_tick for aid,keys in clock.frames.items() for key in keys if key.frame_index in rgb_samples[aid]} | |
| out.mkdir(parents=True,exist_ok=False);journal=StageJournal(out/'stages.jsonl') | |
| started=time.monotonic();scene=None;encoders={} | |
| costs={};isolation_by_target={};native_states={};camera_states={};source_rgb={};viewport_counts={} | |
| def measured(category,func,*args,**kwargs): | |
| start=time.perf_counter() | |
| try:return func(*args,**kwargs) | |
| finally:costs[category]=costs.get(category,0.)+time.perf_counter()-start | |
| def remainder(category,start,before): | |
| # Subtract already measured children so component totals do not double count. | |
| elapsed=time.perf_counter()-start-(sum(costs.values())-before) | |
| costs[category]=costs.get(category,0.)+max(0.,elapsed) | |
| def write_table(name,row): | |
| return measured("table_write_s",writers[name].write,row) | |
| def remaining(): | |
| value=max_wall_s-(time.monotonic()-started) | |
| if value<=0: raise TimeoutError('Render attempt wall budget reached') | |
| return value | |
| journal.write('assembly_start',code_commit=code_commit) | |
| try: | |
| scene=measured('assembly_s',scene_factory,inputs,spec,bindings,out/'scratch',requested_gpu) | |
| remaining();journal.write('assembly_end',bodies=len(scene.read_bodies(clock.control_ticks[0]))) | |
| # Stochastic backends: keep the audited source frames for codec comparison; replay is judged separately. | |
| tolerant=replay_policy(scene);retained=out/'scratch'/'replay-source';replay_rows={aid:[] for aid in clock.frames} | |
| if tolerant:retained.mkdir(parents=True,exist_ok=False) | |
| obs_id=observation_id(inputs,spec,scene.asset_fingerprints,chain_version=version) | |
| refs={k:(r['path'],False) for k,r in {**inputs.source_refs,**scene.asset_refs}.items()} | |
| with measured('bundle_setup_s',Bundle,out/'.partial','RenderedObservation',refs) as bundle: | |
| folder=bundle.out;tables=folder/'tables';tables.mkdir();videos=folder/'videos';videos.mkdir() | |
| samples=folder/'samples';samples.mkdir() | |
| writers={name:TableWriter(tables,name) for name in ('frames','body_readback','camera_readback','visibility','quality')} | |
| writers['static_visibility']=TableWriter(tables,'static_visibility') | |
| if spec.export_instance_masks:writers['instance_masks']=TableWriter(tables,'instance_masks',chunk_rows=64) | |
| ground_enabled=spec.ground_policy.get('status')=='ENABLED' | |
| visibility_enabled=spec.visibility_policy.get('status')=='ENABLED' | |
| journal.write('measurement_setup_start',ground=ground_enabled,amodal=visibility_enabled) | |
| if ground_enabled: | |
| from ..rendering.ground import FloorProjector,GroundGrid | |
| projector=FloorProjector(spec.ground_policy) if ground_enabled else None | |
| grid=measured('ground_setup_s',GroundGrid,inputs.capability) if ground_enabled else None | |
| if ground_enabled: | |
| writers.update(ground=TableWriter(tables,'ground',chunk_rows=32), | |
| room_ground=TableWriter(tables,'room_ground'),door_ground=TableWriter(tables,'door_ground')) | |
| identities=dict(scene.identities) | |
| if ground_enabled:identities['derived_floor']=dict(semantic_id=None,kind='floor',name='derived_floor', | |
| source='stage SID0 + depth + actual camera; overlapping raw structure',method=dict(spec.ground_policy)) | |
| dump(folder/'identities.json',identities) | |
| journal.write('measurement_setup_end') | |
| for aid in clock.frames: encoders[aid]=StreamingEncoder(videos/(aid+'.mp4'),spec.width,spec.height,spec.fps) | |
| errors={aid:[] for aid in inputs.curves.actors};yaw_errors={aid:[] for aid in inputs.curves.actors} | |
| pelvis={};camera_errors={aid:[] for aid in clock.frames};camera_angles={aid:[] for aid in clock.frames} | |
| self_pixels={aid:[] for aid in clock.frames};prev_rgb={};selected={aid:{} for aid in clock.frames} | |
| last_sample={};sample_target=next((aid for aid,item in scene.identities.items() if item['kind']=='actor'),None) | |
| initial_static=scene.static_snapshot();body_ids=set(scene.read_bodies(clock.control_ticks[0])) | |
| joint_max=max([len(r['joint_positions']) for r in scene.read_bodies(clock.control_ticks[0]).values()]+[0]) | |
| first=True | |
| for ordinal,tick in enumerate(clock.control_ticks): | |
| body_start=time.perf_counter();body_before=sum(costs.values()) | |
| remaining();poses={aid:inputs.curves.pose_at_tick(aid,tick) for aid in inputs.curves.actors} | |
| scene.apply_bodies(tick,poses);bodies=scene.read_bodies(tick) | |
| if tick in replay_ticks: | |
| native_states[tick]={aid:dict(root_matrix=rb['root_matrix'].copy(),joint_positions=rb['joint_positions'].copy()) | |
| for aid,rb in bodies.items()} | |
| for aid,rb in bodies.items(): | |
| if 'applied_visual_pose' in rb:native_states[tick][aid]['applied_visual_pose']=rb['applied_visual_pose'] | |
| if 'applied_root_matrix' in rb:native_states[tick][aid]['applied_root_matrix']=rb['applied_root_matrix'] | |
| world=float(inputs.curves.t[tick]) | |
| for aid,p in poses.items(): | |
| expected=reference_matrix(p,inputs.capability['floor_height_m']) | |
| row=dict(actor_id=aid,control_tick=tick,world_s=world,body_present=aid in bodies, | |
| expected_reference_matrix=expected) | |
| if aid in bodies: | |
| rb=bodies[aid];ref=rb['reference_matrix'];actual=reference_to_script(ref) | |
| pos_error=float(np.linalg.norm(ref[:3,3]-expected[:3,3])) | |
| yaw_error=abs(math.atan2(math.sin(actual['yaw_rad']-p.yaw_rad),math.cos(actual['yaw_rad']-p.yaw_rad))) | |
| errors[aid].append(pos_error);yaw_errors[aid].append(yaw_error) | |
| joints=np.full(joint_max,np.nan);joints[:len(rb['joint_positions'])]=rb['joint_positions'] | |
| offset=rb['pelvis_offset_world_m'] | |
| pelvis.setdefault(aid,[]).append((world,offset,rb['pelvis_yaw_offset_rad'])) | |
| row.update(status='BODY_READBACK',actual_reference_matrix=ref,actual_native_root=rb['root_matrix'], | |
| native_reference_matrix=rb['native_reference_matrix'],position_error_m=pos_error,yaw_error_rad=yaw_error, | |
| pelvis_offset_world_m=offset,pelvis_yaw_offset_rad=rb['pelvis_yaw_offset_rad'], | |
| joint_count=len(rb['joint_positions']),joint_positions=joints, | |
| animation_s_m=rb['animation_s_m'],animation_phase=rb['animation_phase']) | |
| row.update(pelvis_ground_correction_world_y_m=rb.get('pelvis_ground_correction_world_y_m',0.), | |
| pelvis_ground_correction_limit_m=rb.get('pelvis_ground_correction_limit_m',0.), | |
| foot_support_min_height_m=rb.get('foot_support_min_height_m',np.nan)) | |
| row['pelvis_ground_correction_failure']=rb.get('pelvis_ground_correction_failure',False) | |
| visual=rb.get('applied_visual_pose');vj=np.full(joint_max,np.nan) | |
| if visual:vj[:len(visual['joints'])]=np.asarray(visual['joints']).reshape(-1) | |
| row.update(applied_visual_joints=vj, | |
| applied_visual_offset=visual['offset'] if visual else np.full((4,4),np.nan), | |
| applied_visual_base=visual['base'] if visual else np.full((4,4),np.nan), | |
| applied_root_matrix=rb.get('applied_root_matrix',np.full((4,4),np.nan))) | |
| else: | |
| row.update(status='NO_BODY',actual_reference_matrix=np.full((4,4),np.nan), | |
| actual_native_root=np.full((4,4),np.nan),native_reference_matrix=np.full((4,4),np.nan), | |
| position_error_m=np.nan,yaw_error_rad=np.nan,pelvis_offset_world_m=np.full(3,np.nan), | |
| pelvis_yaw_offset_rad=np.nan,joint_count=0,joint_positions=np.full(joint_max,np.nan), | |
| animation_s_m=np.nan,animation_phase=np.nan) | |
| row.update(pelvis_ground_correction_world_y_m=np.nan,pelvis_ground_correction_limit_m=np.nan, | |
| foot_support_min_height_m=np.nan) | |
| row['pelvis_ground_correction_failure']=False | |
| row.update(applied_visual_joints=np.full(joint_max,np.nan),applied_visual_offset=np.full((4,4),np.nan), | |
| applied_visual_base=np.full((4,4),np.nan),applied_root_matrix=np.full((4,4),np.nan)) | |
| write_table('body_readback',row) | |
| remainder('drive_readback_s',body_start,body_before) | |
| keys=clock.by_tick.get(tick,()) | |
| if keys: | |
| camera_start=time.perf_counter() | |
| requests={} | |
| for key in keys: | |
| aid=key.observer_id;p=poses[aid] | |
| ref=bodies[aid]['reference_matrix'] if aid in bodies else reference_matrix(p,inputs.capability['floor_height_m']) | |
| requests[aid]=camera_to_world(ref,spec.mounts[aid],p.cam_yaw_world_rad,p.cam_pitch_rad) | |
| scene.apply_cameras(requests) | |
| costs['camera_drive_s']=costs.get('camera_drive_s',0.)+time.perf_counter()-camera_start | |
| captured=measured('modal_capture_s',scene.capture,list(requests)) | |
| bounds=scene.body_bounds() if visibility_enabled else {} | |
| for key in keys: | |
| frame_start=time.perf_counter();frame_before=sum(costs.values()) | |
| aid=key.observer_id;frame=captured[aid];key_row=asdict(key) | |
| if (frame.rgb.shape!=(spec.height,spec.width,3) or frame.rgb.dtype!=np.uint8 or | |
| frame.depth.shape!=(spec.height,spec.width) or frame.semantic.shape!=(spec.height,spec.width)): | |
| raise ContractError('Native frame channels do not share release dimensions') | |
| # Compact the RGB view of native RGBA once into an owned | |
| # buffer shared by hashing, pipe input and next-frame MAD. | |
| frame.rgb=np.array(frame.rgb,copy=True,order='C') | |
| actual=frame.camera_world_matrix;requested=requests[aid] | |
| pe=float(np.linalg.norm(actual[:3,3]-requested[:3,3]));angle=angular_error(-actual[:3,2],-requested[:3,2]) | |
| camera_errors[aid].append(pe);camera_angles[aid].append(angle) | |
| rgb_hash=hashlib.sha256(memoryview(frame.rgb)).hexdigest();source_rgb[(aid,tick)]=rgb_hash | |
| if tolerant and key.frame_index in rgb_samples[aid]: | |
| measured('replay_retain_s',np.savez,retained/f'{aid}-{tick}.npz',rgb=frame.rgb,depth=frame.depth,semantic=frame.semantic) | |
| camera_states[(aid,tick)]=(frame.applied_camera_matrix if frame.applied_camera_matrix is not None else requests[aid]).copy() | |
| measured('encoding_write_s',encoders[aid].write,frame.rgb,remaining());write_table('frames',dict(**key_row,rgb_sha256=rgb_hash)) | |
| write_table('camera_readback',dict(**key_row,actual_camera_matrix=actual, | |
| requested_camera_matrix=requested,applied_camera_matrix=camera_states[(aid,tick)],projection_matrix=frame.projection_matrix, | |
| position_error_m=pe,forward_angle_error_rad=angle)) | |
| stats=measured('quality_s',image_statistics,frame.rgb,frame.depth,prev_rgb.get(aid)) | |
| write_table('quality',dict(**key_row,**stats,camera_height_m=actual[1,3]-inputs.capability['floor_height_m'])) | |
| prev_rgb[aid]=frame.rgb;own_sid=scene.identities[aid]['semantic_id'] | |
| self_pixels[aid].append(int((frame.semantic==own_sid).sum()) if own_sid is not None else 0) | |
| static_stats=measured('static_visibility_s',semantic_statistics,frame.semantic) | |
| pixel_index=FramePixelIndex(frame,identities,static_stats) | |
| for target,item in identities.items(): | |
| if item['kind'] not in ('furniture','structure'):continue | |
| count,bbox=static_stats.get(item['semantic_id'],(0,[-1]*4)) | |
| write_table('static_visibility',dict(**key_row,target_id=target,semantic_id=item['semantic_id'], | |
| kind=item['kind'],pixels=count,bbox=bbox)) | |
| batch_isolated=None | |
| if visibility_enabled and hasattr(scene,'capture_isolated_many'): | |
| candidates=[target for target in inputs.curves.actors | |
| if scene.identities[target]['semantic_id'] is not None and | |
| (not scene.identities[target].get('geometric_bounds',{}).get('reliable',True) or | |
| in_frustum(bounds[target],actual,frame.projection_matrix))] | |
| batch_isolated=measured('isolation_setup_draw_s',scene.capture_isolated_many,candidates,aid,frame) | |
| for target in inputs.curves.actors: | |
| item=scene.identities[target];sid=item['semantic_id'] | |
| isolated=None | |
| geometric=dict(geometric_distance_m=np.nan,center_edge_margin_rad=np.nan,body_forward_view_ray_angle_rad=np.nan) | |
| candidate=False;restoration=np.full(5,np.nan) | |
| if sid is None:row=no_body_measurement() | |
| elif visibility_enabled: | |
| reliable=scene.identities[target].get('geometric_bounds',{}).get('reliable',True) | |
| candidate=(not reliable) or in_frustum(bounds[target],actual,frame.projection_matrix) | |
| iso_stats=isolation_by_target.setdefault(target,dict(candidates=0,skipped=0,wall_s=0.,unculled_degenerate_aabb=not reliable)) | |
| isolated=None | |
| if candidate: | |
| start=time.perf_counter() | |
| isolated=(batch_isolated[target] if batch_isolated is not None else | |
| measured('isolation_setup_draw_s',scene.capture_isolated,target,aid,frame)) | |
| iso_stats['wall_s']+=isolated.get('wall_s',time.perf_counter()-start);iso_stats['candidates']+=1 | |
| else:iso_stats['skipped']+=1 | |
| row=measured('visibility_reduce_s',subject_measurement,frame,sid,identities, | |
| isolated['semantic'] if isolated else None,frustum=candidate,pixel_index=pixel_index) | |
| geometric=view_geometry(actual,frame.projection_matrix,bounds[target].mean(axis=0),bodies[target]['reference_matrix'][:3,0]) | |
| if isolated:restoration=np.array([isolated[k] for k in ('root_max_abs_delta','joint_max_abs_delta','camera_max_abs_delta','projection_max_abs_delta','link_max_abs_delta')]) | |
| else: | |
| row=no_body_measurement();row['pixels'],row['bbox']=pixel_bounds(frame.semantic,sid) | |
| row.update(occlusion_status='NOT_CHECKED',pixel_depth_status='NOT_CHECKED') | |
| write_table('visibility',dict(**key_row,target_id=target,semantic_id=-1 if sid is None else sid, | |
| body_present=sid is not None,frustum_candidate=candidate,actual_restoration_max_abs_delta=restoration, | |
| **row,**geometric)) | |
| if sid is not None and aid!=target: | |
| count=viewport_counts.setdefault((aid,target),[0,0]);count[0]+=1 | |
| count[1]+=row['occlusion_status']=='UNKNOWN_VIEWPORT_EDGE' | |
| if spec.export_instance_masks: | |
| mask_start=time.perf_counter() | |
| visible_ids=pixel_index.visible_indices(sid) if sid is not None else np.empty(0,np.int64) | |
| visible_row=mask_row(key_row,target,sid,'visible',visible_ids,frame.semantic.shape, | |
| 'MEASURED' if sid is not None else 'NO_BODY') | |
| amodal_ids=np.flatnonzero(isolated['semantic'].ravel()==sid) if isolated else np.empty(0,np.int64) | |
| amodal_row=mask_row(key_row,target,sid,'amodal',amodal_ids,frame.semantic.shape, | |
| 'MEASURED' if isolated else ('NO_BODY' if sid is None else 'NOT_RENDERED')) | |
| if visible_row['pixels']!=row['pixels'] or (isolated and amodal_row['pixels']!=row['amodal_pixels']): | |
| raise ContractError('Instance mask/visibility pixel mismatch') | |
| costs['instance_masks_encode_s']=costs.get('instance_masks_encode_s',0.)+time.perf_counter()-mask_start | |
| measured('instance_masks_write_s',writers['instance_masks'].write,visible_row) | |
| measured('instance_masks_write_s',writers['instance_masks'].write,amodal_row) | |
| if ground_enabled and key.frame_index in ground_samples[aid]: | |
| before_floor=costs.get('derived_floor_s',0.);before_grid=costs.get('ground_grid_s',0.) | |
| floor=measured('derived_floor_s',projector.derive,frame.depth,frame.semantic,actual,frame.projection_matrix, | |
| inputs.capability['floor_height_m']) | |
| raw,regions,doors=measured('ground_grid_s',grid.measure,floor.world_uv) | |
| floor_counts_start=time.perf_counter() | |
| depth_valid=np.isfinite(frame.depth)&(frame.depth>0);stage=frame.semantic==0 | |
| bins=[0,2,4,7,10,np.inf] | |
| ground_row=dict(**key_row,**raw,stage_pixels=int(stage.sum()), | |
| derived_floor_pixels=int((floor.labels==1).sum()),unknown_stage_pixels=int((floor.labels==2).sum()), | |
| stage_count_by_depth=np.histogram(frame.depth[stage&depth_valid],bins)[0], | |
| unknown_count_by_depth=np.histogram(frame.depth[(floor.labels==2)&depth_valid],bins)[0], | |
| invalid_stage_depth_pixels=int((stage&~depth_valid).sum())) | |
| count_s=time.perf_counter()-floor_counts_start | |
| costs['floor_raw_counts_s']=costs.get('floor_raw_counts_s',0.)+count_s | |
| write_table('ground',dict(ground_row,derived_floor_wall_s=costs['derived_floor_s']-before_floor, | |
| ground_grid_wall_s=costs['ground_grid_s']-before_grid,floor_raw_counts_wall_s=count_s)) | |
| for rid,row in regions.items():write_table('room_ground',dict(**key_row,region_id=rid,**row)) | |
| for did,sides in doors.items(): | |
| for row in sides:write_table('door_ground',dict(**key_row,door_id=did,**row)) | |
| last_sample[aid]=(key,frame) | |
| target_sid=scene.identities[sample_target]['semantic_id'] if sample_target else None | |
| count=int((frame.semantic==target_sid).sum()) if target_sid is not None else 0 | |
| # Keep only three sparse evidence buffers per route; no per-frame images. | |
| if count>0 and ('positive' not in selected[aid] or count>selected[aid]['positive'][2]): | |
| selected[aid]['positive']=(key,_evidence_copy(frame),count) | |
| if count==0 and 'negative' not in selected[aid]: selected[aid]['negative']=(key,_evidence_copy(frame),count) | |
| if key.frame_index==len(clock.frames[aid])//2: selected[aid]['middle']=(key,_evidence_copy(frame),count) | |
| remainder('frame_bookkeeping_s',frame_start,frame_before) | |
| if first: journal.write('first_frame',tick=tick,views=len(keys));first=False | |
| if (ordinal+1)%progress_every==0: | |
| journal.write('control_progress',tick=tick,control_done=ordinal+1,control_total=len(clock.control_ticks), | |
| video_frames={aid:encoder.count for aid,encoder in encoders.items()},component_wall_s=dict(costs)) | |
| viewport_quality=viewport_edge_summary(viewport_counts,spec.visibility_policy['viewport_unknown_max_fraction']) | |
| dump(out/'viewport-edge-summary.json',viewport_quality) | |
| journal.write('viewport_edge_quality',**viewport_quality) | |
| if viewport_quality['status']!='PASS':raise ContractError('Viewport-edge unknown fraction exceeds 0.5%; preserve failed attempt') | |
| journal.write('encoding_finish_start') | |
| encoding={aid:measured('encoding_finish_s',e.finish,remaining()) for aid,e in encoders.items()} | |
| journal.write('encoding_finish_end') | |
| if measured('verification_s',scene.static_snapshot)!=initial_static: | |
| raise ContractError('Static world changed; refuse observation publication') | |
| counts={name:measured('instance_masks_write_s' if name=='instance_masks' else 'table_write_s',w.finish) for name,w in writers.items()} | |
| expected_frames=sum(len(keys) for keys in clock.frames.values()) | |
| if counts['frames']['rows']!=expected_frames or counts['body_readback']['rows']!=len(clock.control_ticks)*len(poses): | |
| raise ContractError('Capture/readback denominator mismatch') | |
| expected_static=sum(item['kind'] in ('furniture','structure') for item in identities.values())*expected_frames | |
| if counts['visibility']['rows']!=expected_frames*len(poses) or counts['static_visibility']['rows']!=expected_static: | |
| raise ContractError('Subject/static visibility denominator mismatch') | |
| if spec.export_instance_masks and counts['instance_masks']['rows']!=2*counts['visibility']['rows']: | |
| raise ContractError('Instance mask denominator mismatch') | |
| expected_ground=sum(len(keys) for keys in ground_samples.values()) | |
| if ground_enabled and (counts['ground']['rows']!=expected_ground or | |
| counts['room_ground']['rows']!=expected_ground*len(grid.regions) or | |
| counts['door_ground']['rows']!=expected_ground*len(grid.doors)*2): | |
| raise ContractError('Ground/region/door denominator mismatch') | |
| decoding={} | |
| for aid,keys in clock.frames.items(): | |
| journal.write('decode_start',observer=aid) | |
| def rgb_reference(key): | |
| def replay(): | |
| scene.restore_native(key.control_tick,native_states[key.control_tick]) | |
| scene.apply_cameras({key.observer_id:camera_states[(key.observer_id,key.control_tick)]}) | |
| replay_frame=scene.capture([key.observer_id])[key.observer_id];rgb=replay_frame.rgb | |
| if tolerant: | |
| with np.load(retained/f'{key.observer_id}-{key.control_tick}.npz') as kept:source=dict(kept) | |
| if hashlib.sha256(memoryview(source['rgb'])).hexdigest()!=source_rgb[(key.observer_id,key.control_tick)]: | |
| raise ContractError('Retained source frame differs from the encoded source') | |
| replayed=dict(rgb=rgb,depth=replay_frame.depth,semantic=replay_frame.semantic) | |
| row=dict(compare_frames(source,replayed),frame=dict(frame_index=key.frame_index,control_tick=key.control_tick)) | |
| replay_rows[key.observer_id].append(row) | |
| if violations(row,tolerant): # keep the replay beside its retained source for diagnosis | |
| (out/'scratch'/'replay-outside').mkdir(exist_ok=True) | |
| np.savez(out/'scratch'/'replay-outside'/f'{key.observer_id}-{key.control_tick}.npz',**replayed) | |
| replay_frame=source['rgb'] | |
| elif hashlib.sha256(memoryview(np.ascontiguousarray(rgb))).hexdigest()!=source_rgb[(key.observer_id,key.control_tick)]: | |
| raise ContractError('Actual-state RGB replay differs from rendered source; cannot compare colour') | |
| if key.frame_index%progress_every==0 or key.frame_index==len(keys)-1: | |
| journal.write('decode_reference_progress',observer=key.observer_id,frame=key.frame_index, | |
| component_wall_s=dict(costs)) | |
| return replay_frame | |
| return measured('rgb_reference_replay_s',replay) | |
| decode_start=time.perf_counter();decode_before=sum(costs.values()) | |
| decoding[aid]=verify_video(videos/(aid+'.mp4'),keys,spec.width,spec.height,spec.fps,remaining(), | |
| rgb_reference=rgb_reference,reference_indices=rgb_samples[aid], | |
| progress=lambda count:journal.write('decode_progress',observer=aid,frames=count) if count%progress_every==0 else None) | |
| comparison=decoding[aid].get('rgb_comparison',{}).get('comparison_wall_s',0.) | |
| costs['rgb_comparison_cpu_s']=costs.get('rgb_comparison_cpu_s',0.)+comparison | |
| remainder('decode_validation_s',decode_start,decode_before) | |
| journal.write('decode_end',observer=aid,frames=decoding[aid]['frames']) | |
| if measured('verification_s',scene.static_snapshot)!=initial_static:raise ContractError('Static world changed during actual-state decode replay') | |
| state_replay=dict(status='PASS',method='exact RGB sha256 of actual-state replay',routes={aid:dict(frames=len(rgb_samples[aid])) for aid in clock.frames}) | |
| if tolerant: | |
| state_replay=dict(method='tolerance; source frames retained for codec comparison',routes={aid:judge(rows,tolerant) for aid,rows in replay_rows.items()}) | |
| failed=[aid for aid,item in state_replay['routes'].items() if item['status']!='PASS'] | |
| state_replay['status']='FAIL' if failed else 'PASS' | |
| if failed: | |
| dump(out/'state-replay-failure.json',state_replay) | |
| raise ContractError('Actual-state replay outside declared backend tolerance: '+','.join(failed)) | |
| evidence_start=time.perf_counter() | |
| sample_records=[];mask_count=0 | |
| for aid in clock.frames: | |
| for label in ('positive','negative','middle'): | |
| key,frame,*_=selected[aid].get(label,(*last_sample[aid],0)) | |
| actual_label=label if label in selected[aid] else 'no_'+label+'_observed' | |
| record=_sample(samples,key,frame,scene.identities,actual_label) | |
| # At most three masks across this observation, not three per route. | |
| if mask_count<spec.mask_evidence_limit: | |
| name=record['png'].replace('.png','.semantic.npz');np.savez_compressed(samples/name,semantic=frame.semantic) | |
| record['semantic_npz']=name;mask_count+=1 | |
| sample_records.append(record) | |
| summary=dict(body={aid:dict(position_error_m=distribution(errors[aid]),yaw_error_rad=distribution(yaw_errors[aid])) | |
| for aid in body_ids},camera={aid:dict(position_error_m=distribution(camera_errors[aid]), | |
| forward_angle_error_rad=distribution(camera_angles[aid])) for aid in clock.frames}, | |
| pelvis={aid:pelvis_summary([v[0] for v in rows],[v[1] for v in rows],[v[2] for v in rows]) for aid,rows in pelvis.items()}, | |
| self_body={aid:dict(pixels=distribution(values),fraction=distribution(np.array(values)/(spec.width*spec.height)), | |
| has_body=scene.identities[aid]['semantic_id'] is not None) for aid,values in self_pixels.items()}) | |
| checks={k:dict(status='PASS') for k in ('assembly','static_world','decode','frame_keys')} | |
| checks['viewport_edge']=viewport_quality;checks['state_replay']=state_replay | |
| checks['leg_stillness']=render_check(tables/'body_readback',{a['id']:a['kind'] for a in inputs.script.get('actors',[])}) # 站着时下肢跳、脚悬空;不在 verify_observation 必过项里 | |
| checks['decode']['routes']=decoding;checks['frame_keys'].update(expected_frames=expected_frames,actual_frames=counts['frames']['rows']) | |
| dump(folder/'checks.json',checks);dump(folder/'readback-summary.json',summary);dump(folder/'samples.json',sample_records) | |
| dump(folder/'tables/schema.json',dict(schema='render-tables/1',counts=counts, | |
| key=['observer_id','control_tick','target_id'],bbox='xmin,ymin,xmax_exclusive,ymax_exclusive; absent=-1', | |
| null='NPZ NaN plus status/presence; never an observed zero',matrix='row matrix; world from camera/native', | |
| root_reference='curve ground reference; native root and local pelvis offsets stored separately', | |
| occlusion='1-intersection(full_visible,individual_amodal)/individual_amodal; zero denominator NaN plus reason; spill separate', | |
| viewport_edge_unknown=dict(method='original one-pixel check retained; exception only when all spill is in outer two rows/columns and Euclidean distance to A <=2px', | |
| status='UNKNOWN_VIEWPORT_EDGE; NaN occlusion; excluded by consumer visible_value', | |
| coordinates='amodal_spill_xy_json: exact [x,y]; amodal_spill_distances_px_json: Euclidean distance to A for unknown rows; unchanged V/A',quality=viewport_quality), | |
| derived_floor=dict(spec.ground_policy) if ground_enabled else 'NOT_CHECKED', | |
| ground_sampling=dict(policy=dict(spec.ground_sampling),routes=ground_sampling, | |
| unsampled='NOT_MEASURED; no interpolation, no false/zero fill') if ground_enabled else None, | |
| ground_grid=dict(inputs.capability['grid'],bitorder='little',flatten='row major; uv=(column,row)', | |
| scope='stage floor only; coverings excluded; each frame is a sample instant, no interpolation') if ground_enabled else None, | |
| ground_depth_bins_m=[0,2,4,7,10,'infinity'],door_sides='0:left of directed segment including centre line; 1:right; width .3m each', | |
| geometric_distance_reference='actual AABB centre when valid; native root for degenerate human AABB; see identities; not pixel depth', | |
| body_forward_reference='actual reconstructed canonical root reference; local pelvis yaw separately in body_readback', | |
| restoration_delta_order=['root','joints','camera','projection','links'], | |
| amodal_raster_support='A and V unchanged; spill=V outside A; categories count A minus intersection(A,V); support_count=A-V+spill', | |
| plan_sample_key='script_id,observer_id,target_id,exact control_tick; no nearest frame/interpolation', | |
| readback_coverage='half-open control sample union; final interval endpoint not observed', | |
| occluder_tie_order=['structure','furniture','actor','observer_body'])) | |
| if spec.export_instance_masks: | |
| schema_path=folder/'tables/schema.json' | |
| import json | |
| schema=json.loads(schema_path.read_text()) | |
| schema['instance_masks']=dict(schema='instance-masks/1',rle='JSON foreground [start,length] pairs; C/row-major flat index=y*width+x; adjacent runs merged', | |
| mask_kind=['visible','amodal'],bbox='exclusive maximum; absent -1', | |
| status='visible MEASURED or NO_BODY; amodal MEASURED only after isolation, otherwise NOT_RENDERED or NO_BODY', | |
| source='same complete/isolated instance buffers as visibility; no extra rendering') | |
| dump(schema_path,schema) | |
| costs['evidence_summary_s']=time.perf_counter()-evidence_start | |
| provenance=dict(**scene.provenance,code_commit=code_commit,chain_version=version,render_backend=backend, | |
| chain_source_sha256=version_sources,spec=spec.as_dict(),source_refs=inputs.source_refs, | |
| asset_fingerprints=scene.asset_fingerprints,encoding=encoding,component_wall_s=costs,isolation_by_target=isolation_by_target, | |
| active_duration_s=len(clock.control_ticks)/inputs.script['control_hz'],scope='unit3 raw measurements; no Q5/P6/front-back decision') | |
| dump(folder/'provenance.json',provenance) | |
| for ref in inputs.source_refs.values(): measured('verification_s',verify_ref,ref) | |
| journal.write('checks_complete',obs_id=obs_id) | |
| measured('bundle_verification_s',bundle.finish,dict(schema='rendered-observation/1',access='private_evidence',obs_id=obs_id, | |
| source_group_id=inputs.script['script_id'],asset_fingerprints=scene.asset_fingerprints,bindings=bindings, | |
| checks=checks,table_counts=counts,summary=summary,public_answerability='NOT_CHECKED')) | |
| measured('publication_verification_s',publish,out/'.partial',out/'observation',obs_id) | |
| journal.write('published',obs_id=obs_id,total_wall_s=time.monotonic()-started, | |
| component_wall_s=dict(costs),outside_component_timers_s=max(0.,time.monotonic()-started-sum(costs.values()))) | |
| return dict(status='PASS',obs_id=obs_id,artifact=str(out/'observation/artifact.json'), | |
| frames=expected_frames,wall_s=time.monotonic()-started,component_wall_s=dict(costs)) | |
| except BaseException as error: | |
| journal.write('failed',error_type=type(error).__name__,reason=str(error)) | |
| dump(out/'attempt-failure.json',dict(status='FAIL',error_type=type(error).__name__,reason=str(error))) | |
| raise | |
| finally: | |
| _close_all([e.close for e in encoders.values()]+([scene.close] if scene is not None else [])+[journal.close]) | |