DROID-Sim / package /tools /validate_release_contracts.py
shutzang's picture
Add files using upload-large-folder tool
da6a6c0 verified
Raw History Blame Contribute Delete
5.98 kB
"""Validate active scene-local rendering, trajectory and physics dependencies.
Historical provenance paths are not runtime dependencies. This checks all active
paths, matrix consistency, hashes, and collision file readability. Mesh-readability
is NOT Isaac cooking, cavity quality, contact or dynamics validation.
"""
import argparse
import json
from pathlib import Path
import time
import numpy as np
from PIL import Image
import trimesh
import yaml
from package_trajectories import digest, write_json
def local(scene, value):
path = Path(value)
assert not path.is_absolute(), f'Absolute active path: {value}'
path = (scene / path).resolve()
assert path.is_relative_to(scene.resolve()), f'Escapes scene: {value}'
assert 'backup' not in path.relative_to(scene.resolve()).parts, f'Active dependency on backup: {value}'
assert path.is_file(), f'Missing active file: {value}'
return path
def check(scene, mesh_check):
start = time.monotonic()
c = json.loads((scene / 'render/scene.json').read_text())
fg, bg, image = [local(scene, c[k]) for k in ('foreground', 'background', 'target_image')]
sha = digest(fg)
assert sha == c['canonical_foreground_sha256'], 'Render contract foreground hash changed'
assert list(Image.open(image).size) == c['image_size_wh']
wf, wb, g = [np.asarray(c[k]) for k in ('world_to_camera_foreground', 'world_to_camera_background', 'transform_foreground_from_background')]
assert all(x.shape == (4, 4) and np.isfinite(x).all() for x in (wf, wb, g))
assert np.allclose(wf @ g, wb, atol=1e-6), 'Not the same camera across layers'
assert c['same_camera'] and c['compositing_policy'] == 'foreground_alpha_priority_over_real_gs'
assert c['background_renderer'] in ('world', 'camera_gauge_sh0')
# PLY header, not merely an existing filename, must contain Gaussian fields.
with open(bg, 'rb') as f:
lines = []
for _ in range(256):
line = f.readline()
lines.append(line)
if line.strip() == b'end_header':
break
header = b''.join(lines)
assert all(x in header for x in (b'opacity', b'scale_0', b'rot_0', b'f_dc_0')), 'Not a Gaussian PLY'
trajectory = json.loads((scene / 'trajectory/manifest.json').read_text())
for name, expected in trajectory['sha256'].items():
assert digest(local(scene, 'trajectory/' + name)) == expected, f'Trajectory hash mismatch: {name}'
cal = json.loads(local(scene, 'trajectory/camera.json').read_text())
assert np.allclose(np.array(cal['transform_camera_from_robot_base']) @ np.array(cal['transform_robot_base_from_camera']), np.eye(4), atol=1e-8)
parameters = yaml.safe_load((scene / 'parameters.yaml').read_text())
assert parameters['foreground_sha256'] == sha
mesh_scene = trimesh.load(fg, force='scene', process=False)
assert set(mesh_scene.graph.nodes_geometry) == {o['node'] for o in parameters['objects']}
parts, readable, unmatched = 0, 0, []
issues = []
for obj in parameters['objects']:
collision = obj['collision']
node_transform = np.asarray(mesh_scene.graph[obj['node']][0])
assert np.allclose(node_transform, obj['visual']['transform_world_from_node'], atol=1e-8)
matrix = collision['transform_world_from_collision']
if matrix is None:
unmatched.append(obj['node'])
else:
assert np.isfinite(matrix).all() and np.asarray(matrix).shape == (4, 4)
assert abs(np.linalg.det(np.asarray(matrix)[:3, :3])) > 1e-12
assert collision['parts'], 'Registered collision has no parts'
if collision['input_mesh']:
local(scene, collision['input_mesh'])
for path in collision['parts']:
part = local(scene, path)
parts += 1
if mesh_check:
try:
loaded = trimesh.load(part, force='scene', process=False)
assert len(loaded.geometry) > 0
for mesh in loaded.geometry.values():
assert len(mesh.vertices) >= 4 and len(mesh.faces) >= 4
assert np.isfinite(mesh.vertices).all()
assert mesh.faces.min() >= 0 and mesh.faces.max() < len(mesh.vertices)
readable += 1
except Exception as error:
issues.append(dict(path=path, error=str(error)))
return dict(scene=scene.name, status='valid' if not issues else 'collision_read_errors',
active_paths_scene_local=True, backup_runtime_dependencies=0,
same_camera_matrix_identity_verified=True, gaussian_background=True,
trajectory_hashes_verified=True, foreground_sha256=sha,
final_nodes=len(parameters['objects']), collision_parts=parts,
collision_parts_readable=readable if mesh_check else None,
collision_read_errors=issues, unregistered_collision_nodes=unmatched,
physics_validated=False, elapsed_seconds=round(time.monotonic()-start, 3))
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--dataset', type=Path, required=True)
p.add_argument('--report', type=Path, required=True)
p.add_argument('--mesh-check', action='store_true')
a = p.parse_args()
rows = []
for scene in sorted(a.dataset.iterdir()):
if not scene.is_dir() or not scene.name[:4].isdigit():
continue
try:
row = check(scene, a.mesh_check)
except Exception as error:
row = dict(scene=scene.name, status='failed', error=str(error))
rows.append(row)
print(json.dumps(row), flush=True)
write_json(a.report, dict(total=len(rows), valid=sum(r['status'] == 'valid' for r in rows), scenes=rows))
if any(r['status'] != 'valid' for r in rows):
raise SystemExit(1)
if __name__ == '__main__':
main()