| from __future__ import annotations |
|
|
| import json |
| from dataclasses import dataclass |
| from functools import lru_cache |
| from pathlib import Path |
| from typing import Dict, List, Optional, Tuple |
|
|
| import numpy as np |
| import torch |
| import yaml |
| from torch_geometric.data import Data |
|
|
|
|
| TYPE_ENCODING_DIM = 10 |
| SAM2_EMB_DIM = 256 |
| POS_DIM = 3 |
| VIS_DIM = 1 |
| NODE_DIM = SAM2_EMB_DIM + POS_DIM + TYPE_ENCODING_DIM + VIS_DIM |
| ROBOT_STATE_DIM = 13 |
|
|
| DATASET_ROOT = Path(__file__).resolve().parent |
| TYPE_ENCODING_ROOT = DATASET_ROOT / "config" |
|
|
|
|
| @lru_cache(maxsize=4) |
| def load_type_encoding(encoding_method: str = "random") -> Dict[str, np.ndarray]: |
| path = TYPE_ENCODING_ROOT / f"type_encoding_{encoding_method}.yaml" |
| with path.open("r", encoding="utf-8") as f: |
| raw = yaml.safe_load(f) |
| return {k: np.asarray(v, dtype=np.float32) for k, v in raw.items()} |
|
|
|
|
| def type_encode(comp_type: str, encoding_method: str = "random") -> np.ndarray: |
| table = load_type_encoding(encoding_method) |
| vec = table.get(comp_type) |
| if vec is None: |
| return np.zeros(TYPE_ENCODING_DIM, dtype=np.float32) |
| return vec.astype(np.float32) |
|
|
|
|
| def list_labeled_frames(episode_dir: str | Path) -> List[int]: |
| mask_dir = Path(episode_dir) / "annotations" / "side_masks" |
| if not mask_dir.exists(): |
| return [] |
| frames = [] |
| for p in mask_dir.glob("frame_*.npz"): |
| try: |
| frames.append(int(p.stem.split("_")[1])) |
| except (ValueError, IndexError): |
| continue |
| return sorted(frames) |
|
|
|
|
| def resolve_frame_state(graph_json: dict, frame_idx: int) -> Tuple[Dict[str, bool], Dict[str, bool], Dict[str, bool]]: |
| constraints: Dict[str, bool] = {} |
| visibility: Dict[str, bool] = {} |
| held: Dict[str, bool] = {} |
|
|
| for c in graph_json["components"]: |
| cid = c["id"] |
| visibility[cid] = True |
| held[cid] = False |
| for e in graph_json["edges"]: |
| constraints[f"{e['src']}->{e['dst']}"] = True |
|
|
| fs_dict = graph_json.get("frame_states", {}) |
| for f in sorted(int(k) for k in fs_dict): |
| if f > frame_idx: |
| break |
| fs = fs_dict[str(f)] |
| constraints.update(fs.get("constraints", {})) |
| visibility.update(fs.get("visibility", {})) |
| held.update(fs.get("held", {})) |
|
|
| return constraints, visibility, held |
|
|
|
|
| @dataclass |
| class FrameData: |
| graph: dict |
| masks: dict |
| embeddings: dict |
| depth_info: dict |
| robot: Optional[dict] |
| constraints: Dict[str, bool] |
| visibility: Dict[str, bool] |
| held: Dict[str, bool] |
|
|
|
|
| def _npz_dict(path: Path) -> Dict[str, np.ndarray]: |
| if not path.exists(): |
| return {} |
| data = np.load(path) |
| return {k: data[k] for k in data.files} |
|
|
|
|
| def load_frame_data(episode_dir: str | Path, frame_idx: int) -> FrameData: |
| episode_dir = Path(episode_dir) |
| anno = episode_dir / "annotations" |
| with (anno / "side_graph.json").open("r", encoding="utf-8") as f: |
| graph = json.load(f) |
|
|
| masks = _npz_dict(anno / "side_masks" / f"frame_{frame_idx:06d}.npz") |
| embeddings = _npz_dict(anno / "side_embeddings" / f"frame_{frame_idx:06d}.npz") |
| depth_info = _npz_dict(anno / "side_depth_info" / f"frame_{frame_idx:06d}.npz") |
|
|
| robot = None |
| robot_path = anno / "side_robot" / f"frame_{frame_idx:06d}.npz" |
| if robot_path.exists(): |
| r = np.load(robot_path) |
| if "visible" in r.files and int(r["visible"][0]) == 1: |
| robot = {k: r[k] for k in r.files} |
|
|
| constraints, visibility, held = resolve_frame_state(graph, frame_idx) |
| return FrameData(graph, masks, embeddings, depth_info, robot, constraints, visibility, held) |
|
|
|
|
| def _build_product_node_features(nodes: List[dict], fd: FrameData, encoding_method: str) -> torch.Tensor: |
| feats = [] |
| for node in nodes: |
| cid = node["id"] |
| emb = fd.embeddings.get(cid, np.zeros(SAM2_EMB_DIM, dtype=np.float32)) |
| depth_valid_key = f"{cid}_depth_valid" |
| centroid_key = f"{cid}_centroid" |
| if depth_valid_key in fd.depth_info and int(fd.depth_info[depth_valid_key][0]) == 1: |
| pos = fd.depth_info[centroid_key].astype(np.float32) |
| else: |
| pos = np.zeros(POS_DIM, dtype=np.float32) |
|
|
| visible = 1.0 if fd.visibility.get(cid, True) else 0.0 |
| if visible == 0.0: |
| emb = np.zeros(SAM2_EMB_DIM, dtype=np.float32) |
| pos = np.zeros(POS_DIM, dtype=np.float32) |
|
|
| feats.append( |
| np.concatenate( |
| [ |
| emb.astype(np.float32), |
| pos, |
| type_encode(node["type"], encoding_method), |
| np.array([visible], dtype=np.float32), |
| ] |
| ) |
| ) |
|
|
| if not feats: |
| return torch.empty((0, NODE_DIM), dtype=torch.float32) |
| return torch.tensor(np.stack(feats), dtype=torch.float32) |
|
|
|
|
| def _build_product_edges(nodes: List[dict], graph: dict, fd: FrameData): |
| constraint_set = {(edge["src"], edge["dst"]) for edge in graph["edges"]} |
| pair_forward = {frozenset([src, dst]): (src, dst) for src, dst in constraint_set} |
|
|
| src_idx, dst_idx, edge_attr = [], [], [] |
| for i, src_node in enumerate(nodes): |
| for j, dst_node in enumerate(nodes): |
| if i == j: |
| continue |
| src_id = src_node["id"] |
| dst_id = dst_node["id"] |
| src_idx.append(i) |
| dst_idx.append(j) |
|
|
| pair_key = frozenset([src_id, dst_id]) |
| if pair_key in pair_forward: |
| forward = pair_forward[pair_key] |
| constraint_key = f"{forward[0]}->{forward[1]}" |
| is_locked = bool(fd.constraints.get(constraint_key, True)) |
| if fd.held.get(src_id, False) or fd.held.get(dst_id, False): |
| is_locked = False |
| src_blocks_dst = 1.0 if src_id == forward[0] else 0.0 |
| edge_attr.append([1.0, 1.0 if is_locked else 0.0, src_blocks_dst]) |
| else: |
| edge_attr.append([0.0, 0.0, 0.0]) |
|
|
| return src_idx, dst_idx, edge_attr |
|
|
|
|
| def load_pyg_frame_products_only( |
| episode_dir: str | Path, |
| frame_idx: int, |
| encoding_method: str = "random", |
| ) -> Data: |
| fd = load_frame_data(episode_dir, frame_idx) |
| nodes = fd.graph["components"] |
| x = _build_product_node_features(nodes, fd, encoding_method) |
| src, dst, edge_attr = _build_product_edges(nodes, fd.graph, fd) |
| return Data( |
| x=x, |
| edge_index=torch.tensor([src, dst], dtype=torch.long), |
| edge_attr=torch.tensor(edge_attr, dtype=torch.float32), |
| y=torch.tensor([frame_idx], dtype=torch.long), |
| num_nodes=len(nodes), |
| ) |
|
|
|
|
| def load_pyg_frame_with_robot( |
| episode_dir: str | Path, |
| frame_idx: int, |
| encoding_method: str = "random", |
| ) -> Data: |
| fd = load_frame_data(episode_dir, frame_idx) |
| if fd.robot is None: |
| return load_pyg_frame_products_only(episode_dir, frame_idx, encoding_method) |
|
|
| products = fd.graph["components"] |
| product_count = len(products) |
| x_prod = _build_product_node_features(products, fd, encoding_method) |
| robot_emb = fd.robot["embedding"].astype(np.float32) |
| robot_pos = ( |
| fd.robot["centroid"].astype(np.float32) |
| if int(fd.robot["depth_valid"][0]) == 1 |
| else np.zeros(POS_DIM, dtype=np.float32) |
| ) |
| robot_feat = np.concatenate( |
| [ |
| robot_emb, |
| robot_pos, |
| type_encode("robot", encoding_method), |
| np.array([1.0], dtype=np.float32), |
| ] |
| ) |
| x = torch.cat([x_prod, torch.tensor(robot_feat, dtype=torch.float32).unsqueeze(0)], dim=0) |
|
|
| src, dst, edge_attr = _build_product_edges(products, fd.graph, fd) |
| robot_idx = product_count |
| for i in range(product_count): |
| src.append(robot_idx) |
| dst.append(i) |
| edge_attr.append([0.0, 0.0, 0.0]) |
| src.append(i) |
| dst.append(robot_idx) |
| edge_attr.append([0.0, 0.0, 0.0]) |
|
|
| data = Data( |
| x=x, |
| edge_index=torch.tensor([src, dst], dtype=torch.long), |
| edge_attr=torch.tensor(edge_attr, dtype=torch.float32), |
| y=torch.tensor([frame_idx], dtype=torch.long), |
| num_nodes=product_count + 1, |
| ) |
| data.robot_point_cloud = torch.tensor(fd.robot["point_cloud"], dtype=torch.float32) |
| data.robot_pixel_coords = torch.tensor(fd.robot["pixel_coords"], dtype=torch.int32) |
| data.robot_mask = torch.tensor(fd.robot["mask"], dtype=torch.uint8) |
| return data |
|
|
|
|
| def load_pyg_frame_with_robot_state( |
| episode_dir: str | Path, |
| frame_idx: int, |
| encoding_method: str = "random", |
| ) -> Data: |
| episode_dir = Path(episode_dir) |
| data = load_pyg_frame_products_only(episode_dir, frame_idx, encoding_method) |
| robot_states = np.load(episode_dir / "robot_states.npy") |
| data.robot_state = torch.tensor(robot_states[frame_idx].astype(np.float32), dtype=torch.float32) |
| return data |
|
|
|
|
| def load_pyg_frame_with_robot_action( |
| episode_dir: str | Path, |
| frame_idx: int, |
| encoding_method: str = "random", |
| ) -> Data: |
| episode_dir = Path(episode_dir) |
| data = load_pyg_frame_with_robot_state(episode_dir, frame_idx, encoding_method) |
| robot_states = np.load(episode_dir / "robot_states.npy") |
| if frame_idx + 1 < robot_states.shape[0]: |
| action = robot_states[frame_idx + 1] - robot_states[frame_idx] |
| else: |
| action = np.zeros(ROBOT_STATE_DIM, dtype=np.float32) |
| data.robot_action = torch.tensor(action.astype(np.float32), dtype=torch.float32) |
| return data |
|
|
|
|
| _VARIANTS = { |
| "products_only": load_pyg_frame_products_only, |
| "with_robot": load_pyg_frame_with_robot, |
| "with_robot_state": load_pyg_frame_with_robot_state, |
| "with_robot_action": load_pyg_frame_with_robot_action, |
| } |
|
|
|
|
| def list_all_frame_graphs( |
| episode_dir: str | Path, |
| variant: str = "with_robot_state", |
| encoding_method: str = "random", |
| ): |
| if variant not in _VARIANTS: |
| raise ValueError(f"variant must be one of {list(_VARIANTS)}, got {variant!r}") |
| loader = _VARIANTS[variant] |
| for frame_idx in list_labeled_frames(episode_dir): |
| yield frame_idx, loader(episode_dir, frame_idx, encoding_method=encoding_method) |
|
|