Datasets:
Download scripts/capture_physics_videos.py from hcltech-robotics/simrepairbench: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/datasets/hcltech-robotics/simrepairbench/resolve/main/scripts/capture_physics_videos.py
- Command line
-
hf download hf://datasets/hcltech-robotics/simrepairbench/scripts/capture_physics_videos.py
-
curl -L -o capture_physics_videos.py https://huggingface.co/datasets/hcltech-robotics/simrepairbench/resolve/main/scripts/capture_physics_videos.py
12.7 kB
| """Retain matched Isaac physics and moving-illumination comparison captures.""" | |
| import argparse | |
| import fcntl | |
| import hashlib | |
| from importlib.metadata import version | |
| import json | |
| from pathlib import Path | |
| import random | |
| import shutil | |
| import subprocess | |
| import time | |
| import traceback | |
| def digest(path): | |
| with Path(path).open('rb') as stream: | |
| return hashlib.file_digest(stream, 'sha256').hexdigest() | |
| def save(path, data): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(data, indent=2) + '\n') | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--case', required=True) | |
| parser.add_argument('--mode', choices=['drop_push', 'illumination'], required=True) | |
| parser.add_argument('--source', type=Path, required=True) | |
| parser.add_argument('--damaged', type=Path, required=True) | |
| parser.add_argument('--output', type=Path, required=True) | |
| parser.add_argument('--frames', type=int, default=150) | |
| parser.add_argument('--width', type=int, default=1280) | |
| parser.add_argument('--height', type=int, default=720) | |
| parser.add_argument('--push-force', type=float, default=100.) | |
| args = parser.parse_args() | |
| output = args.output.resolve() | |
| output.mkdir(parents=True, exist_ok=True) | |
| settings = {'fps': 30, 'physics_dt': 1 / 120, 'frames': args.frames, | |
| 'resolution': [args.width, args.height], 'seed': 1729, | |
| 'renderer': 'RaytracedLighting', 'drop_height_m': .5, | |
| 'gravity_m_s2': 9.81, 'force_N': [args.push_force, 0., 0.], | |
| 'force_interval_s': [2., 2.35], 'dome_intensity': 350., | |
| 'key_intensity': 2200., 'key_elevation_degrees': 18., | |
| 'illumination_azimuth_degrees': [-110., 250.], | |
| 'diagnostic': 'moving_raking_illumination' if args.mode == 'illumination' else 'simulated_drop_and_applied_force_push', | |
| 'projected_stripes': False, 'reflection_zebra': False, | |
| 'calibrated_scanning': False, 'playback_speed': 1.0} | |
| receipt = {'schema': 'simrepairbench-retained-video-v1', 'case_id': args.case, | |
| 'mode': args.mode, 'settings': settings, 'completed': False, | |
| 'source_repository': 'nvidia/simready-assets', | |
| 'source_revision': '4763fbfaa4f8e97658e68b57d01b4c86659e08b5', | |
| 'isaacsim_version': version('isaacsim'), 'clips': [], | |
| 'scope': 'Rendered comparison captures; no repair acceptance or calibrated surface measurement'} | |
| shutil.copyfile(__file__, output / 'capture_driver.py') | |
| receipt['driver_sha256'] = digest(output / 'capture_driver.py') | |
| app = None | |
| lock = open('/dev/shm/simready-global-gpu.lock', 'a') | |
| started = time.monotonic() | |
| try: | |
| fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| random.seed(1729) | |
| import numpy as np | |
| np.random.seed(1729) | |
| from isaacsim import SimulationApp | |
| app = SimulationApp({'headless': True, 'width': args.width, 'height': args.height, | |
| 'renderer': 'RaytracedLighting', | |
| 'extra_args': ['--/app/extensions/registryEnabled=false']}) | |
| import carb | |
| import omni.usd | |
| import omni.physx | |
| from isaacsim.core.api import SimulationContext | |
| from isaacsim.sensors.camera import Camera | |
| from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdPhysics, UsdUtils, PhysicsSchemaTools | |
| from PIL import Image | |
| def light_matrix(azimuth): | |
| return Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(0, 1, 0), 72)) * Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(0, 0, 1), azimuth)) | |
| receipt['usd_version'] = list(Usd.GetVersion()) | |
| receipt['gpu'] = subprocess.check_output(['nvidia-smi', '--query-gpu=name,driver_version', '--format=csv,noheader'], text=True).strip() | |
| carb.settings.get_settings().set('/rtx/post/histogram/enabled', False) | |
| receipt['auto_exposure_enabled'] = carb.settings.get_settings().get('/rtx/post/histogram/enabled') | |
| # The source determines one camera and placement used for both roles. | |
| reference = Usd.Stage.Open(str(args.source.resolve())) | |
| bounds = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render']).ComputeWorldBound(reference.GetDefaultPrim()).ComputeAlignedRange() | |
| low, high = np.array(bounds.GetMin()), np.array(bounds.GetMax()) | |
| center = (low + high) / 2 | |
| span = float(max(high - low)) | |
| placement = np.array([-center[0], -center[1], (.5 if args.mode == 'drop_push' else .03) - low[2]]) | |
| target = np.array([.45 if args.mode == 'drop_push' else 0., 0., (high[2] - low[2]) * .48 + .03]) | |
| distance = span * (4.2 if args.mode == 'drop_push' else 2.65) | |
| eye = target + np.array([distance * .70, -distance, distance * .62]) | |
| camera_matrix = Gf.Matrix4d().SetLookAt(Gf.Vec3d(*eye), Gf.Vec3d(*target), Gf.Vec3d(0, 0, 1)).GetInverse() | |
| receipt['camera'] = {'position': eye.tolist(), 'target': target.tolist(), | |
| 'camera_to_world_rows': [[float(v) for v in row] for row in camera_matrix], | |
| 'focal_length_mm': 35., 'horizontal_aperture_mm': 36., | |
| 'placement_translation_m': placement.tolist(), | |
| 'source_bounds_m': [low.tolist(), high.tolist()]} | |
| interface = omni.physx.get_physx_simulation_interface() | |
| receipt['force_api'] = str(interface.apply_force_at_pos.__doc__) | |
| for role, path in [('source', args.source), ('broken', args.damaged)]: | |
| folder = output / role | |
| frames = folder / 'frames' | |
| frames.mkdir(parents=True, exist_ok=True) | |
| if not omni.usd.get_context().open_stage(str(path.resolve())): | |
| raise ValueError('Could not open stage: ' + role) | |
| for _ in range(20): | |
| app.update() | |
| stage = omni.usd.get_context().get_stage() | |
| stage.SetEditTarget(stage.GetSessionLayer()) | |
| root = stage.GetDefaultPrim() | |
| xform = UsdGeom.Xformable(root) | |
| original_matrix = xform.GetLocalTransformation() | |
| xform.MakeMatrixXform().Set(original_matrix * Gf.Matrix4d().SetTranslate(Gf.Vec3d(*placement))) | |
| ground = UsdGeom.Mesh.Define(stage, '/CaptureGround') | |
| ground.CreatePointsAttr([(-8, -8, 0), (8, -8, 0), (8, 8, 0), (-8, 8, 0)]) | |
| ground.CreateFaceVertexCountsAttr([4]) | |
| ground.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) | |
| ground.CreateDisplayColorAttr([(0.16, 0.18, 0.20)]) | |
| UsdPhysics.CollisionAPI.Apply(ground.GetPrim()) | |
| dome = UsdLux.DomeLight.Define(stage, '/CaptureDome') | |
| dome.CreateIntensityAttr(settings['dome_intensity']) | |
| key = UsdLux.DistantLight.Define(stage, '/CaptureKey') | |
| key.CreateIntensityAttr(settings['key_intensity']) | |
| key.CreateAngleAttr(.53) | |
| key_transform = UsdGeom.Xformable(key).AddTransformOp() | |
| camera_schema = UsdGeom.Camera.Define(stage, '/CaptureCamera') | |
| camera_schema.CreateFocalLengthAttr(35.) | |
| camera_schema.CreateHorizontalApertureAttr(36.) | |
| camera_schema.CreateVerticalApertureAttr(36. * args.height / args.width) | |
| camera_schema.CreateClippingRangeAttr((.01, 100.)) | |
| UsdGeom.Xformable(camera_schema).AddTransformOp().Set(camera_matrix) | |
| sim = SimulationContext(physics_dt=1 / 120, rendering_dt=1 / 30, | |
| stage_units_in_meters=1., backend='numpy', stage=stage) | |
| sim.initialize_physics() | |
| camera = Camera(prim_path='/CaptureCamera', frequency=30, | |
| resolution=(args.width, args.height)) | |
| camera.initialize() | |
| key_transform.Set(light_matrix(-60)) | |
| for _ in range(30): | |
| sim.render() | |
| body_paths = [str(p.GetPath()) for p in stage.Traverse() if p.HasAPI(UsdPhysics.RigidBodyAPI)] | |
| body = next((p for p in body_paths if 'sm_drum_a02_' in p), body_paths[0]) | |
| stage_id = UsdUtils.StageCache.Get().Insert(stage).ToLongInt() | |
| body_id = PhysicsSchemaTools.sdfPathToInt(Sdf.Path(body)) | |
| force_calls, positions, image_stats, light_directions = 0, [], [], [] | |
| if args.mode == 'drop_push': | |
| sim.play() | |
| for frame in range(args.frames): | |
| if args.mode == 'drop_push': | |
| for substep in range(4): | |
| elapsed = (frame * 4 + substep) / 120 | |
| if 2. <= elapsed < 2.35: | |
| pos = UsdGeom.XformCache().GetLocalToWorldTransform(stage.GetPrimAtPath(body)).ExtractTranslation() | |
| interface.apply_force_at_pos(stage_id, body_id, carb.Float3(args.push_force, 0., 0.), carb.Float3(*pos), 'Force') | |
| force_calls += 1 | |
| sim.step(render=False) | |
| else: | |
| angle = -110 + 360 * frame / max(args.frames - 1, 1) | |
| matrix = light_matrix(angle) | |
| key_transform.Set(matrix) | |
| light_directions.append(list(matrix.TransformDir(Gf.Vec3d(0, 0, -1)))) | |
| sim.render() | |
| rgba = np.asarray(camera.get_rgba()) | |
| if rgba.shape != (args.height, args.width, 4) or rgba.dtype != np.uint8: | |
| raise ValueError('Invalid camera image: ' + repr((rgba.shape, str(rgba.dtype)))) | |
| rgb = rgba[:, :, :3] | |
| if not rgb.max(): | |
| raise ValueError('Camera frame is entirely black') | |
| Image.fromarray(rgb).save(frames / f'{frame:06}.png', compress_level=2) | |
| positions.append({'frame': frame, 'simulation_time': float(sim.current_time), | |
| 'bodies': {p: list(UsdGeom.XformCache().GetLocalToWorldTransform(stage.GetPrimAtPath(p)).ExtractTranslation()) for p in body_paths}}) | |
| if frame in (0, args.frames // 2, args.frames - 1): | |
| image_stats.append({'frame': frame, 'mean_rgb': rgb.mean(axis=(0, 1)).tolist(), 'min': int(rgb.min()), 'max': int(rgb.max())}) | |
| if frame % 30 == 0: | |
| print(json.dumps({'case': args.case, 'role': role, 'frame': frame}), flush=True) | |
| if args.mode == 'drop_push' and not force_calls: | |
| raise ValueError('No physical push was applied') | |
| if args.mode == 'illumination' and np.linalg.norm(np.array(light_directions[0]) - np.array(light_directions[args.frames // 2])) < 1.: | |
| raise ValueError('Insufficient world-space illumination sweep') | |
| sim.stop() | |
| camera.destroy() | |
| SimulationContext.clear_instance() | |
| clip = folder / f'{args.case}_{role}_{args.mode}.mp4' | |
| subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-framerate', '30', '-i', str(frames / '%06d.png'), | |
| '-c:v', 'libx264', '-crf', '18', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(clip)], check=True) | |
| probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', | |
| 'stream=codec_name,width,height,avg_frame_rate,nb_frames:format=duration', '-of', 'json', str(clip)], text=True)) | |
| save(folder / 'positions.json', positions) | |
| entry = {'role': role, 'input': str(path.resolve()), 'input_sha256': digest(path), | |
| 'clip': str(clip), 'clip_sha256': digest(clip), 'raw_frames': str(frames), | |
| 'frame_count': args.frames, 'force_calls': force_calls, 'force_body': body, | |
| 'light_directions_world': light_directions, | |
| 'image_statistics': image_stats, 'ffprobe': probe} | |
| save(folder / 'capture.json', {**entry, 'settings': settings, 'camera': receipt['camera']}) | |
| receipt['clips'].append(entry) | |
| save(output / 'inventory.json', receipt) | |
| receipt['completed'] = True | |
| except Exception as exc: | |
| receipt['error'] = {'type': type(exc).__name__, 'message': str(exc)} | |
| traceback.print_exc() | |
| finally: | |
| receipt['wall_seconds'] = time.monotonic() - started | |
| save(output / 'inventory.json', receipt) | |
| print(json.dumps(receipt), flush=True) | |
| if app: | |
| app.close() | |
| lock.close() | |
| return 0 if receipt['completed'] else 1 | |
| if __name__ == '__main__': | |
| raise SystemExit(main()) | |