"""Helpers: episode loading, pose math, Habitat agent control.""" from __future__ import annotations import math import os import sys from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple import numpy as np from .config import WIW_ROOT, WalkthroughConfig def ensure_wiw_on_path(wiw_root: Path = WIW_ROOT) -> Path: """Put world-in-world on sys.path and chdir there for relative data paths.""" root = Path(wiw_root).resolve() root_s = str(root) if root_s not in sys.path: sys.path.insert(0, root_s) # Scene configs and relative paths in simulator assume CWD = world-in-world os.chdir(root) return root def load_ignav_dataset(cfg: WalkthroughConfig): """Load IGNav portable dataset (144 episodes by default).""" ensure_wiw_on_path(cfg.wiw_root) from downstream.process_IGnav_dataset.pickle_dataset import load_igdataset_from_zip ds = load_igdataset_from_zip( str(cfg.goal_zip), str(cfg.episodes_path), remote_hm3d_root=str(cfg.hm3d_root), ) return ds def filter_episodes(data: List[Dict[str, Any]], cfg: WalkthroughConfig) -> List[Dict[str, Any]]: episodes = list(data) if cfg.episode_ids: wanted = {str(x) for x in cfg.episode_ids} episodes = [ e for e in episodes if str(e.get("datum_id", "")) in wanted or str(e.get("episode_id", "")) in wanted ] if cfg.max_episodes is not None: episodes = episodes[: cfg.max_episodes] return episodes def episode_key(datum: Dict[str, Any]) -> str: scene = Path(str(datum.get("scene_id", "unknown"))).stem ep = int(datum.get("episode_id", 0)) datum_id = str(datum.get("datum_id", f"{scene}_{ep}")) return f"{datum_id}" def to_np_pos(x) -> np.ndarray: return np.asarray(x, dtype=np.float32).reshape(3) def rotation_to_quat(rotation) -> np.quaternion: """ Convert stored rotation to numpy-quaternion. IGNav / Habitat agent.state.rotation.components uses (w, x, y, z). `set_agent_coordinates` likewise expects (w, x, y, z) via np.quaternion(*r). """ r = np.asarray(rotation, dtype=np.float64).reshape(4) return np.quaternion(float(r[0]), float(r[1]), float(r[2]), float(r[3])) def quat_to_list(q: np.quaternion) -> List[float]: # components == (w, x, y, z) return [float(x) for x in q.components] def yaw_from_quat(q: np.quaternion) -> float: """Extract yaw (radians) about +Y for Habitat agent quaternion.""" from habitat_sim.utils.common import quat_to_angle_axis theta, axis = quat_to_angle_axis(q) if axis[1] < 0: theta = 2 * math.pi - theta # normalize to [-pi, pi] theta = (theta + math.pi) % (2 * math.pi) - math.pi return float(theta) def yaw_diff(a: float, b: float) -> float: """Signed shortest yaw difference a->b in radians, range (-pi, pi].""" d = (b - a + math.pi) % (2 * math.pi) - math.pi return float(d) def geodesic_distance(pathfinder, p1, p2) -> Tuple[float, Optional[np.ndarray]]: import habitat_sim path = habitat_sim.ShortestPath() path.requested_start = to_np_pos(p1) path.requested_end = to_np_pos(p2) ok = pathfinder.find_path(path) if not ok: return float("inf"), None return float(path.geodesic_distance), np.asarray(path.points, dtype=np.float32) def sample_coverage_waypoints( pathfinder, start: np.ndarray, goal: np.ndarray, num_points: int, min_spacing: float, seed: int, max_tries: int = 5000, ) -> List[np.ndarray]: """Sample navigable points covering the scene, away from each other and GT ends.""" rng = np.random.RandomState(seed) points: List[np.ndarray] = [] anchors = [to_np_pos(start), to_np_pos(goal)] tries = 0 while len(points) < num_points and tries < max_tries: tries += 1 p = pathfinder.get_random_navigable_point() if p is None or np.isnan(p).any(): continue p = to_np_pos(p) # Keep same floor roughly (y close to start) if abs(float(p[1] - start[1])) > 0.5: continue # Must be reachable from start and goal d_s, _ = geodesic_distance(pathfinder, start, p) d_g, _ = geodesic_distance(pathfinder, goal, p) if not np.isfinite(d_s) or not np.isfinite(d_g): continue # Spacing vs existing + anchors too_close = False for q in anchors + points: if float(np.linalg.norm(p - q)) < min_spacing: too_close = True break d_geo, _ = geodesic_distance(pathfinder, p, q) if d_geo < min_spacing * 0.5: too_close = True break if too_close: continue points.append(p) # Deterministic shuffle for pre/post split order = list(range(len(points))) rng.shuffle(order) return [points[i] for i in order] def nearest_neighbor_order( pathfinder, origin: np.ndarray, waypoints: Sequence[np.ndarray], ) -> List[np.ndarray]: """Greedy TSP order starting from origin (origin itself not included in return).""" remaining = [to_np_pos(w) for w in waypoints] ordered: List[np.ndarray] = [] cur = to_np_pos(origin) while remaining: best_i = None best_d = float("inf") for i, w in enumerate(remaining): d, _ = geodesic_distance(pathfinder, cur, w) if d < best_d: best_d = d best_i = i if best_i is None or not np.isfinite(best_d): # drop unreachable remaining.pop(0) continue nxt = remaining.pop(best_i) ordered.append(nxt) cur = nxt return ordered def build_continuous_visit_order( pathfinder, start: np.ndarray, goal: np.ndarray, coverage: List[np.ndarray], pre_gt_ratio: float, ) -> List[Tuple[str, np.ndarray]]: """ Build a continuous visit list of labeled waypoints: [S0, ..., start, goal, ...] Labels: - "explore": coverage waypoint - "gt_start": episode start - "gt_goal": episode goal """ start = to_np_pos(start) goal = to_np_pos(goal) n_pre = int(round(len(coverage) * pre_gt_ratio)) pre = coverage[:n_pre] post = coverage[n_pre:] visit: List[Tuple[str, np.ndarray]] = [] if pre: # Choose S0 as the pre-point farthest (geodesic) from start, then NN toward start. dists = [geodesic_distance(pathfinder, start, p)[0] for p in pre] if any(np.isfinite(dists)): s0_idx = int(np.nanargmax(np.asarray(dists, dtype=np.float64))) else: s0_idx = 0 s0 = pre[s0_idx] rest_pre = [p for i, p in enumerate(pre) if i != s0_idx] ordered_pre = nearest_neighbor_order(pathfinder, s0, rest_pre) # Reverse so we end near start: farthest -> ... -> nearest to start # Re-order by NN from s0 already ends somewhere; force last approach to start. visit.append(("explore", s0)) for p in ordered_pre: visit.append(("explore", p)) else: # No pre coverage: start video a short random offset before GT if possible # Fall back to starting at episode start. pass visit.append(("gt_start", start)) visit.append(("gt_goal", goal)) if post: ordered_post = nearest_neighbor_order(pathfinder, goal, post) for p in ordered_post: visit.append(("explore", p)) return visit