Data / version /1.1 /read_delivery.py
JK2727's picture
Publish v1.1 single-KeyFrame human motion references
ccef179 verified
Raw History Blame
19.1 kB
"""Standalone NumPy reader and complete validator for ManipSyn v1.1 deliveries."""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import shlex
import tarfile
import xml.etree.ElementTree as ET
import numpy as np
def read(path):
return json.loads(Path(path).read_text())
def sha(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def require(condition, message):
if not condition:
raise ValueError(message)
def arrays(path):
with np.load(path, allow_pickle=False) as data:
result = {key: data[key] for key in data.files}
for key, value in result.items():
if value.dtype.kind in 'fc':
require(np.isfinite(value).all(), f'Nonfinite array: {path}:{key}')
return result
def rotation(axis, angle):
axis = np.asarray(axis, dtype=float)
axis = axis / np.linalg.norm(axis)
x, y, z = axis
skew = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]])
return np.eye(3) + np.sin(angle) * skew + (1 - np.cos(angle)) * (skew @ skew)
def origin_matrix(element, scale):
matrix = np.eye(4)
if element is not None:
matrix[:3, 3] = np.fromstring(element.get('xyz', '0 0 0'), sep=' ') * scale
r, p, y = np.fromstring(element.get('rpy', '0 0 0'), sep=' ')
matrix[:3, :3] = rotation([0, 0, 1], y) @ rotation([0, 1, 0], p) @ rotation([1, 0, 0], r)
return matrix
def check_assets(urdf):
"""Resolve URDF→OBJ→MTL→texture dependencies without the source repository."""
tree = ET.parse(urdf)
dependencies = set()
pending = [(urdf.parent / node.attrib['filename']).resolve()
for node in tree.findall('.//mesh')]
for node in tree.findall('.//texture'):
pending.append((urdf.parent / node.attrib['filename']).resolve())
while pending:
path = pending.pop()
require(path.is_relative_to(urdf.parent.resolve()), f'Asset escapes directory: {path}')
require(path.is_file(), f'Missing asset dependency: {path}')
if path in dependencies:
continue
dependencies.add(path)
if path.suffix.lower() not in ('.obj', '.mtl'):
continue
for line in path.read_text(errors='strict').splitlines():
words = shlex.split(line, comments=True)
if not words:
continue
names = words[1:] if words[0] == 'mtllib' else []
if words[0].lower().startswith('map_') or words[0].lower() in ('bump', 'disp', 'decal'):
names = [words[-1]]
pending.extend((path.parent / name).resolve() for name in names)
return tree, len(dependencies)
def check_fk(tree, scene, info):
scale = info['asset_scale_to_meters']
links = {node.attrib['name'] for node in tree.findall('link')}
joints = tree.findall('joint')
roots = links - {node.find('child').attrib['link'] for node in joints}
require(len(roots) == 1, 'URDF must have exactly one root')
names = info['joint_names']
require(scene['joint_positions'].shape == (60, len(names)), 'Joint trajectory shape')
maximum = 0.0
for frame in range(60):
poses = {next(iter(roots)): scene['object_root_poses'][frame]}
remaining = list(joints)
while remaining:
ready = [j for j in remaining if j.find('parent').attrib['link'] in poses]
require(bool(ready), 'Disconnected URDF joint graph')
for joint in ready:
parent = joint.find('parent').attrib['link']
child = joint.find('child').attrib['link']
axis_node = joint.find('axis')
axis = np.fromstring('1 0 0' if axis_node is None else axis_node.get('xyz', '1 0 0'), sep=' ')
value = scene['joint_positions'][frame, names.index(joint.attrib['name'])]
motion = np.eye(4)
kind = joint.attrib['type']
if kind in ('continuous', 'revolute'):
motion[:3, :3] = rotation(axis, value)
elif kind == 'prismatic':
motion[:3, 3] = axis / np.linalg.norm(axis) * value
else:
require(kind == 'fixed', f'Unsupported joint type: {kind}')
poses[child] = poses[parent] @ origin_matrix(joint.find('origin'), scale) @ motion
remaining.remove(joint)
for name, pose in poses.items():
maximum = max(maximum, float(np.abs(pose - scene['link_poses_' + name][frame]).max()))
require(maximum <= 1e-6, f'Object FK error: {maximum}')
return maximum
class Delivery:
def __init__(self, root):
self.root = Path(root).resolve()
self.manifest = read(self.root / 'manifest.json')
self.samples = [json.loads(line) for line in (self.root / 'samples.jsonl').read_text().splitlines() if line]
def path(self, relative):
require(isinstance(relative, str) and not Path(relative).is_absolute(), f'Expected relative path: {relative}')
path = (self.root / relative).resolve()
require(path.is_relative_to(self.root), f'Path escapes package: {relative}')
require(path.is_file(), f'Missing payload: {relative}')
return path
def load(self, sample_id):
matches = [row for row in self.samples if row['sample_id'] == sample_id]
require(len(matches) == 1, f'Expected one sample: {sample_id}')
row = matches[0]
motion = arrays(self.path(row['motion_path']))
return {
'index': row,
'metadata': read(self.path(row['metadata_path'])),
'quality': read(self.path(row['quality_path'])),
'input': read(self.path(row['input_manifest_path'])),
'joints_world_m': np.stack([motion[h + '_joints_world_m'] for h in ('left', 'right')], axis=1),
'hand_used': np.array([motion[h + '_hand_used'].item() for h in ('left', 'right')]),
'scene': arrays(self.path(row['scene_path'])),
'affordance': read(self.path(row['affordance_path'])),
}
def verify(self, integrity=True):
require(self.manifest['schema_version'] == 'manipsyn.physical-reference/1.1.0', 'Unsupported schema')
expected = {(obj, f'{op:03d}', seed) for obj in ('3571', '3616', '3635')
for op in range(5) for seed in range(42, 47)}
require(len(self.samples) == 75 and
{(r['instance_id'], r['operation_id'], r['seed']) for r in self.samples} == expected,
'Expected exactly 15 operations × 5 seeds')
require(len({r['sample_id'] for r in self.samples}) == 75, 'Duplicate sample IDs')
require(not any(p.is_symlink() for p in self.root.rglob('*')), 'Package contains symlinks')
if integrity:
indexed = self.manifest['files']
actual = {str(p.relative_to(self.root)) for p in self.root.rglob('*')
if p.is_file() and '__pycache__' not in p.relative_to(self.root).parts}
require(actual == set(indexed) | {'manifest.json', 'SHA256SUMS'}, 'Payload inventory mismatch')
for name, identity in indexed.items():
path = self.path(name)
require(path.stat().st_size == identity['size_bytes'] and sha(path) == identity['sha256'], f'Hash mismatch: {name}')
checksums = {}
for line in (self.root / 'SHA256SUMS').read_text().splitlines():
digest, name = line.split(' ', 1)
checksums[name] = digest
require(set(checksums) == set(indexed) | {'manifest.json'}, 'Checksum inventory mismatch')
require(all(sha(self.path(name)) == digest for name, digest in checksums.items()), 'Checksum mismatch')
operations = {}
max_feature = max_fk = max_kf = 0.0
asset_dependencies = 0
source_index = read(self.path(self.manifest['source_index']))
require(len(source_index['input_archives']) == 15, 'Input evidence coverage')
for archived in source_index['input_archives']:
with tarfile.open(self.path(archived['path'])) as stream:
members = stream.getmembers()
require(all(m.isfile() and not Path(m.name).is_absolute() and '..' not in Path(m.name).parts for m in members), 'Unsafe archive member')
require({m.name for m in members} == set(archived['member_sha256']), 'Input archive inventory mismatch')
for member in members:
digest = hashlib.sha256(stream.extractfile(member).read()).hexdigest()
require(digest == archived['member_sha256'][member.name], 'Original input evidence changed')
for archived in source_index['runtime_archives']:
with tarfile.open(self.path(archived['path'])) as stream:
require(all(m.isfile() and not Path(m.name).is_absolute() and '..' not in Path(m.name).parts for m in stream.getmembers()), 'Unsafe runtime archive')
digest = hashlib.sha256(stream.extractfile('execution_manifest.json').read()).hexdigest()
require(digest == archived['execution_manifest_sha256'], 'Runtime execution identity mismatch')
for row in self.samples:
sample = self.load(row['sample_id'])
joints = sample['joints_world_m']
require(joints.shape == (60, 2, 21, 3) and joints.dtype == np.float32, 'Motion array contract')
require(sample['hand_used'].dtype == np.bool_, 'Hand-used dtype')
meta, quality, info, scene = [sample[k] for k in ('metadata', 'quality', 'input', 'scene')]
require(meta['sample_id'] == row['sample_id'] and meta['seed'] == row['seed'], 'Sample identity mismatch')
require(meta['best_step'] in range(501) and meta['actual_final_step'] == 500, 'Saved step mismatch')
require(quality['physical_certified'] is False, 'Unexpected physical certification')
require(sha(self.path(row['motion_path'])) == meta['source_motion_sha256'], 'Changed source motion')
evidence = meta['evidence_path']
marker = read(self.path(evidence + '/optimization_complete.json'))
require(sha(self.path(evidence + '/optimization_complete.json')) == meta['source_marker_sha256'], 'Completion marker changed')
for name, path in [('motion_best.npz', row['motion_path']), ('handx_best.npz', row['handx_path']),
('state_best.pt', evidence + '/state_best.pt')]:
require(sha(self.path(path)) == marker['files'][name], f'Source best file changed: {name}')
with gzip.open(self.path(evidence + '/audit_best.json.gz'), 'rb') as stream:
audit_bytes = stream.read()
require(hashlib.sha256(audit_bytes).hexdigest() == marker['files']['audit_best.json'], 'Best audit identity mismatch')
audit = json.loads(audit_bytes)
replay = read(self.path(evidence + '/replay_best.json'))
require(replay['pass'] and replay['max_absolute_joint_difference_m'] <= 1e-6, 'Saved replay failed')
require(marker['best_step'] == meta['best_step'] and marker['seed'] == row['seed'], 'Best checkpoint identity mismatch')
for field in ('package_sha256', 'config_digest', 'canonical_sha256'):
require(marker[field] == audit[field] == replay[field], 'Evidence identity mismatch')
require(marker['package_sha256'] == info['source_input_manifest_sha256'], 'Input source binding mismatch')
require(quality['skeleton_qualified'] == audit['skeleton_qualified'] and
quality['source_static_flags'] == info['source_static_flags'], 'Quality flag mismatch')
require(info['frames'] == 60 and info['fps'] == 30 and info['world_frame'] == 'right_handed_z_up', 'Time/frame contract')
require(info['operation']['id'] == row['operation_id'] and
bool(info['operation_description']['overall']), 'Operation semantics missing')
require(np.allclose(scene['time_s'], np.arange(60) / 30, atol=1e-12, rtol=0), 'Time grid mismatch')
key = (row['instance_id'], row['operation_id'])
if key not in operations:
condition = arrays(self.path(info['condition_path']))
canonical = read(self.path(info['canonical_path']))
tree, count = check_assets(self.path(info['asset_urdf_path']))
asset_dependencies += count
max_fk = max(max_fk, check_fk(tree, scene, info))
for name, value in scene.items():
if name.startswith('link_poses_') or name == 'object_root_poses':
require(value.shape == (60, 4, 4) and np.allclose(value[:, 3], [0, 0, 0, 1]), 'Pose matrix contract')
require(np.allclose(value[:, :3, :3] @ value[:, :3, :3].transpose(0, 2, 1), np.eye(3), atol=1e-6), 'Pose rotation contract')
require(np.allclose(value, condition[name], atol=1e-12, rtol=0), 'Changed saved object poses')
obj = read(self.path(info['object_motion_path']))
require(obj['object']['asset_urdf'] == info['asset_urdf_path'], 'Object asset path mismatch')
for name, values in obj['object_motion']['joint_trajectories'].items():
require(np.allclose(scene['joint_positions'][:, info['joint_names'].index(name)], values, atol=1e-12, rtol=0), 'Changed joint motion')
for stage in sample['affordance']['stages']:
require('link_poses_' + stage['target_link'] in scene, 'Affordance target link missing')
start, end = stage['active_interval_frames']
require(0 <= start < end <= 60, 'Invalid active interval')
for finger in stage['fingers'].values():
require(np.isfinite(finger['point_link_m']).all() and np.isclose(np.linalg.norm(finger['surface_normal_local']), 1, atol=1e-5), 'Affordance geometry contract')
operations[key] = condition, canonical
condition, canonical = operations[key]
require(sha(self.path(info['canonical_path'])) == marker['canonical_sha256'], 'Canonical source binding mismatch')
tips = {'thumb': 16, 'index': 17, 'middle': 18, 'ring': 19, 'pinky': 20}
gaps = []
for stage in sample['affordance']['stages']:
hand = ('left', 'right').index(stage['hand'])
poses = scene['link_poses_' + stage['target_link']]
for finger, binding in stage['fingers'].items():
target = poses[:, :3, :3] @ np.asarray(binding['point_link_m']) + poses[:, :3, 3]
distance = np.linalg.norm(joints[:, hand, tips[finger]] - target, axis=-1)
gaps.extend(distance[1:59])
recomputed = {'mean_frozen_gap_mm': np.mean(gaps) * 1000,
'p95_frozen_gap_mm': np.quantile(gaps, .95) * 1000,
'max_frozen_gap_mm': np.max(gaps) * 1000,
'interior_max_speed_m_s': np.linalg.norm(joints[2:59] - joints[1:58], axis=-1).max() * 30,
'endpoint_max_speed_m_s': np.linalg.norm(joints[[1, 59]] - joints[[0, 58]], axis=-1).max() * 30}
for name, value in recomputed.items():
require(np.isclose(value, quality[name], rtol=1e-5, atol=1e-3 if name.endswith('_mm') else 1e-6), f'Quality metric mismatch: {row["sample_id"]}:{name}')
features = arrays(self.path(row['handx_path']))
require(all(features[k].shape == (1, 42, 4, 60) for k in ('normalized', 'condition', 'mask')), 'HandX feature shape')
raw = features['normalized'].astype(float) * condition['normalization_std'][None, :, :, None] + condition['normalization_mean'][None, :, :, None]
model = raw[0, :, :3].transpose(2, 0, 1).reshape(60, 2, 21, 3)
flip = np.asarray(canonical['flip_matrix'])
require(np.isclose(np.linalg.det(flip), 1) and np.array_equal(flip @ flip.T, np.eye(3)), 'Canonical rotation')
local = model @ flip + canonical['center_object_root_m']
roots = scene['object_root_poses']
world = np.einsum('tij,thqj->thqi', roots[:, :3, :3], local) + roots[:, None, None, :3, 3]
error = float(np.abs(world - joints).max())
require(error <= 1e-6, f'Feature→world mismatch: {error}')
max_feature = max(max_feature, error)
compiled = np.zeros((1, 42, 4, 60), dtype=bool)
for interval in info['intervals']:
hand = ('left', 'right').index(interval['hand'])
frame = interval['start']
compiled[0, hand * 21:(hand + 1) * 21, :, frame] = True
error = float(np.linalg.norm(joints[frame, hand] - condition['world_joints_m'][frame, hand], axis=-1).max())
require(error <= 1e-5, f'Hard KeyFrame mismatch: {error}')
max_kf = max(max_kf, error)
require(features['mask'].dtype == np.bool_ and np.array_equal(features['mask'], compiled), 'Hard mask mismatch')
require(np.max(np.abs(features['normalized'][compiled] - features['condition'][compiled])) <= 1e-6, 'Normalized hard condition mismatch')
return {'status': 'passed', 'samples': 75, 'operations': len(operations),
'frames_per_sample': 60, 'total_motion_frames': 4500,
'asset_dependency_checks': asset_dependencies,
'max_feature_world_component_error_m': max_feature,
'max_object_fk_component_error': max_fk,
'max_hard_keyframe_joint_error_m': max_kf,
'physical_simulation_executed': False,
'scope': 'Saved payload integrity, portable reading, object FK, feature decoding and hard conditions; no DNO or physics rerun.'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('root', type=Path)
parser.add_argument('--verify', action='store_true')
parser.add_argument('--sample')
args = parser.parse_args()
data = Delivery(args.root)
if args.verify:
print(json.dumps(data.verify(), indent=2))
elif args.sample:
sample = data.load(args.sample)
print(json.dumps({'sample_id': args.sample,
'joints_shape': list(sample['joints_world_m'].shape),
'hand_used': sample['hand_used'].tolist(),
'best_step': sample['metadata']['best_step'],
'quality': sample['quality']}, indent=2))
else:
print(json.dumps({'samples': len(data.samples), 'first_sample': data.samples[0]['sample_id']}))
if __name__ == '__main__':
main()