Datasets:
File size: 5,140 Bytes
6fc8f88 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | """Read an EEF companion and construct explicitly selected OpenWAM-style targets.
No temporal shift is applied to command actions. next_state is an explicitly
derived, one-retained-frame-ahead achieved-state target, with terminal masking.
"""
import io
import json
from pathlib import Path
import tarfile
import numpy as np
def load_index(path):
with open(path, encoding='utf-8') as stream:
return {row['episode_id']:row for row in map(json.loads,stream)}
def load_indexed_episode(dataset_root, record, *, action_mode, unify_action=True, allow_copied_commands=False):
with (Path(dataset_root)/record['shard']).open('rb') as stream:
stream.seek(record['json_offset']);metadata=json.loads(stream.read(record['json_bytes']))
stream.seek(record['npz_offset']);data=stream.read(record['npz_bytes'])
if metadata['episode_id']!=record['episode_id']:
raise ValueError('EEF episode index does not match shard contents')
with np.load(io.BytesIO(data),allow_pickle=False) as archive:
arrays={key:archive[key] for key in archive.files}
result=build_arrays(arrays,metadata,action_mode=action_mode,unify_action=unify_action,
allow_copied_commands=allow_copied_commands)
result['metadata']=metadata
return result
def _pose20(pose, grip, pose_valid, grip_valid):
q = pose[..., 3:7]
x, y, z, w = np.moveaxis(q, -1, 0)
col0 = np.stack([1-2*(y*y+z*z), 2*(x*y+z*w), 2*(x*z-y*w)], axis=-1)
col1 = np.stack([2*(x*y-z*w), 1-2*(x*x+z*z), 2*(y*z+x*w)], axis=-1)
value = np.concatenate([pose[..., :3], col0, col1, grip[..., None]], axis=-1).reshape(len(pose), 20)
mask = np.concatenate([np.repeat(pose_valid[..., None], 9, axis=-1), grip_valid[..., None]], axis=-1).reshape(len(pose), 20)
return np.where(mask, value, 0).astype(np.float32), mask
def build_arrays(arrays, metadata, *, action_mode, unify_action=True, allow_copied_commands=False):
if action_mode not in {'command', 'next_state'}:
raise ValueError('Explicitly choose action_mode=command or next_state')
state, state_mask = _pose20(arrays['state_pose'], arrays['state_gripper'],
arrays['state_pose_valid'], arrays['state_gripper_valid'])
if action_mode == 'next_state':
action = np.zeros_like(state); action_mask = np.zeros_like(state_mask)
action[:-1] = state[1:]; action_mask[:-1] = state_mask[1:]
else:
pose = arrays['command_pose'] if 'command_pose' in arrays else arrays['state_pose']
pose_mask = arrays['command_pose_valid'].copy()
if not allow_copied_commands:
pose_mask[:, np.asarray(metadata.get('command_pose_is_state_copy', [False, False]), dtype=bool)] = False
action, action_mask = _pose20(pose, arrays['command_gripper'], pose_mask, arrays['command_gripper_valid'])
if metadata.get('command_quality_review_required', False):
action_mask[:]=False;action[:]=0
if unify_action:
def scatter(value):
out = np.zeros((len(value), 80), dtype=value.dtype)
out[:, :10] = value[:, :10]; out[:, 34:44] = value[:, 10:20]
return out
state, action, state_mask, action_mask = map(scatter, [state, action, state_mask, action_mask])
return {'state': state, 'action': action, 'state_mask': state_mask, 'action_mask': action_mask,
'episode_id': metadata['episode_id'], 'fps': metadata['fps'], 'action_mode': action_mode}
def load_episode(shard_path, episode_id, *, action_mode, unify_action=True, allow_copied_commands=False):
with tarfile.open(shard_path, 'r') as shard:
metadata = json.load(shard.extractfile(episode_id+'.json'))
data = shard.extractfile(episode_id+'.npz').read()
with np.load(io.BytesIO(data), allow_pickle=False) as archive:
arrays = {key: archive[key] for key in archive.files}
result = build_arrays(arrays, metadata, action_mode=action_mode, unify_action=unify_action,
allow_copied_commands=allow_copied_commands)
result['metadata'] = metadata
return result
def iter_episodes(shard_path, *, action_mode, unify_action=True, allow_copied_commands=False):
"""Stream companions without repeatedly scanning the TAR directory."""
with tarfile.open(shard_path, 'r|') as shard:
pending = {}
for member in shard:
if not member.isfile():
continue
key, suffix = member.name.rsplit('.', 1)
data = shard.extractfile(member).read()
if suffix == 'npz':
pending[key] = data
elif suffix == 'json':
metadata = json.loads(data)
with np.load(io.BytesIO(pending.pop(key)), allow_pickle=False) as archive:
arrays = {name: archive[name] for name in archive.files}
result = build_arrays(arrays, metadata, action_mode=action_mode, unify_action=unify_action,
allow_copied_commands=allow_copied_commands)
result['metadata'] = metadata
yield result
|