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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Skeleton graph representation for topology-agnostic motion processing.
|
| 3 |
+
|
| 4 |
+
Each skeleton is represented as a directed tree graph with:
|
| 5 |
+
- Joint features: rest offset, bone length, depth, degree, parent type, side tag
|
| 6 |
+
- Edge features: parent-child relations, geodesic distances
|
| 7 |
+
- Joint name embeddings: CLIP-encoded semantic features
|
| 8 |
+
|
| 9 |
+
This is the foundation for the TopoSlots slot assignment module.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class SkeletonGraph:
|
| 19 |
+
"""Unified skeleton graph representation for arbitrary topologies."""
|
| 20 |
+
|
| 21 |
+
# Basic structure
|
| 22 |
+
joint_names: list[str] # [J] joint names
|
| 23 |
+
parent_indices: list[int] # [J] parent index (-1 for root)
|
| 24 |
+
rest_offsets: np.ndarray # [J, 3] rest-pose offsets from parent
|
| 25 |
+
|
| 26 |
+
# Derived features (computed in __post_init__)
|
| 27 |
+
num_joints: int = 0
|
| 28 |
+
bone_lengths: np.ndarray = field(default_factory=lambda: np.array([])) # [J]
|
| 29 |
+
depths: np.ndarray = field(default_factory=lambda: np.array([])) # [J] tree depth
|
| 30 |
+
degrees: np.ndarray = field(default_factory=lambda: np.array([])) # [J] num children
|
| 31 |
+
adjacency: np.ndarray = field(default_factory=lambda: np.array([])) # [J, J] binary
|
| 32 |
+
geodesic_dist: np.ndarray = field(default_factory=lambda: np.array([])) # [J, J]
|
| 33 |
+
side_tags: list[str] = field(default_factory=list) # [J] 'left'/'right'/'center'
|
| 34 |
+
symmetry_pairs: list[tuple[int, int]] = field(default_factory=list)
|
| 35 |
+
|
| 36 |
+
# Semantic features (filled by encode_joint_names)
|
| 37 |
+
name_embeddings: Optional[np.ndarray] = None # [J, D_clip]
|
| 38 |
+
|
| 39 |
+
def __post_init__(self):
|
| 40 |
+
self.num_joints = len(self.joint_names)
|
| 41 |
+
J = self.num_joints
|
| 42 |
+
|
| 43 |
+
if J == 0:
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
# Bone lengths
|
| 47 |
+
self.bone_lengths = np.linalg.norm(self.rest_offsets, axis=-1) # [J]
|
| 48 |
+
|
| 49 |
+
# Tree depth via BFS from root
|
| 50 |
+
self.depths = np.zeros(J, dtype=np.int32)
|
| 51 |
+
for j in range(J):
|
| 52 |
+
d = 0
|
| 53 |
+
p = self.parent_indices[j]
|
| 54 |
+
while p >= 0:
|
| 55 |
+
d += 1
|
| 56 |
+
p = self.parent_indices[p]
|
| 57 |
+
self.depths[j] = d
|
| 58 |
+
|
| 59 |
+
# Degree (number of children)
|
| 60 |
+
self.degrees = np.zeros(J, dtype=np.int32)
|
| 61 |
+
for j in range(J):
|
| 62 |
+
p = self.parent_indices[j]
|
| 63 |
+
if p >= 0:
|
| 64 |
+
self.degrees[p] += 1
|
| 65 |
+
|
| 66 |
+
# Adjacency matrix (undirected)
|
| 67 |
+
self.adjacency = np.zeros((J, J), dtype=np.float32)
|
| 68 |
+
for j in range(J):
|
| 69 |
+
p = self.parent_indices[j]
|
| 70 |
+
if p >= 0:
|
| 71 |
+
self.adjacency[j, p] = 1.0
|
| 72 |
+
self.adjacency[p, j] = 1.0
|
| 73 |
+
|
| 74 |
+
# Geodesic distances via BFS
|
| 75 |
+
self.geodesic_dist = self._compute_geodesic_distances()
|
| 76 |
+
|
| 77 |
+
# Side tags from joint names
|
| 78 |
+
self.side_tags = self._infer_side_tags()
|
| 79 |
+
|
| 80 |
+
# Symmetry pairs
|
| 81 |
+
self.symmetry_pairs = self._find_symmetry_pairs()
|
| 82 |
+
|
| 83 |
+
def _compute_geodesic_distances(self) -> np.ndarray:
|
| 84 |
+
"""BFS-based geodesic distance on skeleton tree."""
|
| 85 |
+
J = self.num_joints
|
| 86 |
+
dist = np.full((J, J), fill_value=J + 1, dtype=np.int32)
|
| 87 |
+
np.fill_diagonal(dist, 0)
|
| 88 |
+
|
| 89 |
+
for i in range(J):
|
| 90 |
+
# BFS from joint i
|
| 91 |
+
queue = [i]
|
| 92 |
+
visited = {i}
|
| 93 |
+
while queue:
|
| 94 |
+
curr = queue.pop(0)
|
| 95 |
+
for j in range(J):
|
| 96 |
+
if self.adjacency[curr, j] > 0 and j not in visited:
|
| 97 |
+
dist[i, j] = dist[i, curr] + 1
|
| 98 |
+
visited.add(j)
|
| 99 |
+
queue.append(j)
|
| 100 |
+
|
| 101 |
+
return dist.astype(np.float32)
|
| 102 |
+
|
| 103 |
+
def _infer_side_tags(self) -> list[str]:
|
| 104 |
+
"""Infer left/right/center from joint names."""
|
| 105 |
+
tags = []
|
| 106 |
+
left_keywords = ['left', 'l_', '_l', 'lft']
|
| 107 |
+
right_keywords = ['right', 'r_', '_r', 'rgt']
|
| 108 |
+
|
| 109 |
+
for name in self.joint_names:
|
| 110 |
+
name_lower = name.lower()
|
| 111 |
+
if any(kw in name_lower for kw in left_keywords):
|
| 112 |
+
tags.append('left')
|
| 113 |
+
elif any(kw in name_lower for kw in right_keywords):
|
| 114 |
+
tags.append('right')
|
| 115 |
+
else:
|
| 116 |
+
tags.append('center')
|
| 117 |
+
|
| 118 |
+
return tags
|
| 119 |
+
|
| 120 |
+
def _find_symmetry_pairs(self) -> list[tuple[int, int]]:
|
| 121 |
+
"""Find symmetric joint pairs based on naming conventions."""
|
| 122 |
+
pairs = []
|
| 123 |
+
used = set()
|
| 124 |
+
|
| 125 |
+
for i, name_i in enumerate(self.joint_names):
|
| 126 |
+
if i in used:
|
| 127 |
+
continue
|
| 128 |
+
name_lower = name_i.lower()
|
| 129 |
+
|
| 130 |
+
# Try to find mirror
|
| 131 |
+
mirror_name = None
|
| 132 |
+
if 'left' in name_lower:
|
| 133 |
+
mirror_name = name_lower.replace('left', 'right')
|
| 134 |
+
elif 'right' in name_lower:
|
| 135 |
+
mirror_name = name_lower.replace('right', 'left')
|
| 136 |
+
elif '_l_' in name_lower:
|
| 137 |
+
mirror_name = name_lower.replace('_l_', '_r_')
|
| 138 |
+
elif '_r_' in name_lower:
|
| 139 |
+
mirror_name = name_lower.replace('_r_', '_l_')
|
| 140 |
+
|
| 141 |
+
if mirror_name:
|
| 142 |
+
for j, name_j in enumerate(self.joint_names):
|
| 143 |
+
if j != i and j not in used and name_j.lower() == mirror_name:
|
| 144 |
+
pairs.append((i, j))
|
| 145 |
+
used.add(i)
|
| 146 |
+
used.add(j)
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
return pairs
|
| 150 |
+
|
| 151 |
+
def get_edge_list(self) -> list[tuple[int, int]]:
|
| 152 |
+
"""Return parent-child edge list."""
|
| 153 |
+
edges = []
|
| 154 |
+
for j in range(self.num_joints):
|
| 155 |
+
p = self.parent_indices[j]
|
| 156 |
+
if p >= 0:
|
| 157 |
+
edges.append((p, j))
|
| 158 |
+
return edges
|
| 159 |
+
|
| 160 |
+
def get_joint_features(self) -> np.ndarray:
|
| 161 |
+
"""
|
| 162 |
+
Compute per-joint feature vector for skeleton encoder input.
|
| 163 |
+
Returns: [J, D] where D = 3 (offset) + 1 (bone_len) + 1 (depth) + 1 (degree) + 3 (side one-hot)
|
| 164 |
+
"""
|
| 165 |
+
J = self.num_joints
|
| 166 |
+
|
| 167 |
+
# Side tags as one-hot: [left, right, center]
|
| 168 |
+
side_onehot = np.zeros((J, 3), dtype=np.float32)
|
| 169 |
+
for j, tag in enumerate(self.side_tags):
|
| 170 |
+
if tag == 'left':
|
| 171 |
+
side_onehot[j, 0] = 1.0
|
| 172 |
+
elif tag == 'right':
|
| 173 |
+
side_onehot[j, 1] = 1.0
|
| 174 |
+
else:
|
| 175 |
+
side_onehot[j, 2] = 1.0
|
| 176 |
+
|
| 177 |
+
# Normalize rest offsets
|
| 178 |
+
max_offset = np.max(np.abs(self.rest_offsets)) + 1e-8
|
| 179 |
+
norm_offsets = self.rest_offsets / max_offset
|
| 180 |
+
|
| 181 |
+
# Normalize bone lengths
|
| 182 |
+
max_bone = np.max(self.bone_lengths) + 1e-8
|
| 183 |
+
norm_bones = (self.bone_lengths / max_bone).reshape(-1, 1)
|
| 184 |
+
|
| 185 |
+
# Normalize depth/degree
|
| 186 |
+
max_depth = max(self.depths.max(), 1)
|
| 187 |
+
norm_depths = (self.depths / max_depth).reshape(-1, 1).astype(np.float32)
|
| 188 |
+
max_degree = max(self.degrees.max(), 1)
|
| 189 |
+
norm_degrees = (self.degrees / max_degree).reshape(-1, 1).astype(np.float32)
|
| 190 |
+
|
| 191 |
+
features = np.concatenate([
|
| 192 |
+
norm_offsets, # [J, 3]
|
| 193 |
+
norm_bones, # [J, 1]
|
| 194 |
+
norm_depths, # [J, 1]
|
| 195 |
+
norm_degrees, # [J, 1]
|
| 196 |
+
side_onehot, # [J, 3]
|
| 197 |
+
], axis=-1) # [J, 9]
|
| 198 |
+
|
| 199 |
+
return features
|
| 200 |
+
|
| 201 |
+
def to_dict(self) -> dict:
|
| 202 |
+
"""Serialize to dict for saving."""
|
| 203 |
+
return {
|
| 204 |
+
'joint_names': self.joint_names,
|
| 205 |
+
'parent_indices': self.parent_indices,
|
| 206 |
+
'rest_offsets': self.rest_offsets,
|
| 207 |
+
'bone_lengths': self.bone_lengths,
|
| 208 |
+
'depths': self.depths,
|
| 209 |
+
'degrees': self.degrees,
|
| 210 |
+
'adjacency': self.adjacency,
|
| 211 |
+
'geodesic_dist': self.geodesic_dist,
|
| 212 |
+
'side_tags': self.side_tags,
|
| 213 |
+
'symmetry_pairs': self.symmetry_pairs,
|
| 214 |
+
'name_embeddings': self.name_embeddings,
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
@classmethod
|
| 218 |
+
def from_dict(cls, d: dict) -> 'SkeletonGraph':
|
| 219 |
+
"""Deserialize from dict."""
|
| 220 |
+
sg = cls(
|
| 221 |
+
joint_names=d['joint_names'],
|
| 222 |
+
parent_indices=d['parent_indices'],
|
| 223 |
+
rest_offsets=d['rest_offsets'],
|
| 224 |
+
)
|
| 225 |
+
if d.get('name_embeddings') is not None:
|
| 226 |
+
sg.name_embeddings = d['name_embeddings']
|
| 227 |
+
return sg
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ============================================================
|
| 231 |
+
# Joint name normalization (alias table)
|
| 232 |
+
# ============================================================
|
| 233 |
+
|
| 234 |
+
JOINT_NAME_ALIASES = {
|
| 235 |
+
# Mixamo naming
|
| 236 |
+
'mixamorig:hips': 'pelvis',
|
| 237 |
+
'mixamorig:spine': 'spine',
|
| 238 |
+
'mixamorig:spine1': 'spine1',
|
| 239 |
+
'mixamorig:spine2': 'chest',
|
| 240 |
+
'mixamorig:neck': 'neck',
|
| 241 |
+
'mixamorig:head': 'head',
|
| 242 |
+
'mixamorig:leftshoulder': 'left shoulder',
|
| 243 |
+
'mixamorig:leftarm': 'left upper arm',
|
| 244 |
+
'mixamorig:leftforearm': 'left forearm',
|
| 245 |
+
'mixamorig:lefthand': 'left hand',
|
| 246 |
+
'mixamorig:rightshoulder': 'right shoulder',
|
| 247 |
+
'mixamorig:rightarm': 'right upper arm',
|
| 248 |
+
'mixamorig:rightforearm': 'right forearm',
|
| 249 |
+
'mixamorig:righthand': 'right hand',
|
| 250 |
+
'mixamorig:leftupleg': 'left upper leg',
|
| 251 |
+
'mixamorig:leftleg': 'left lower leg',
|
| 252 |
+
'mixamorig:leftfoot': 'left foot',
|
| 253 |
+
'mixamorig:lefttoebase': 'left toe',
|
| 254 |
+
'mixamorig:rightupleg': 'right upper leg',
|
| 255 |
+
'mixamorig:rightleg': 'right lower leg',
|
| 256 |
+
'mixamorig:rightfoot': 'right foot',
|
| 257 |
+
'mixamorig:righttoebase': 'right toe',
|
| 258 |
+
# SMPL naming
|
| 259 |
+
'pelvis': 'pelvis',
|
| 260 |
+
'l_hip': 'left hip',
|
| 261 |
+
'r_hip': 'right hip',
|
| 262 |
+
'spine1': 'lower spine',
|
| 263 |
+
'l_knee': 'left knee',
|
| 264 |
+
'r_knee': 'right knee',
|
| 265 |
+
'spine2': 'upper spine',
|
| 266 |
+
'l_ankle': 'left ankle',
|
| 267 |
+
'r_ankle': 'right ankle',
|
| 268 |
+
'spine3': 'chest',
|
| 269 |
+
'l_foot': 'left foot',
|
| 270 |
+
'r_foot': 'right foot',
|
| 271 |
+
'neck': 'neck',
|
| 272 |
+
'l_collar': 'left collar',
|
| 273 |
+
'r_collar': 'right collar',
|
| 274 |
+
'head': 'head',
|
| 275 |
+
'l_shoulder': 'left shoulder',
|
| 276 |
+
'r_shoulder': 'right shoulder',
|
| 277 |
+
'l_elbow': 'left elbow',
|
| 278 |
+
'r_elbow': 'right elbow',
|
| 279 |
+
'l_wrist': 'left wrist',
|
| 280 |
+
'r_wrist': 'right wrist',
|
| 281 |
+
# Common animal naming
|
| 282 |
+
'hips': 'pelvis',
|
| 283 |
+
'spine': 'spine',
|
| 284 |
+
'chest': 'chest',
|
| 285 |
+
'leftforeleg': 'left fore leg',
|
| 286 |
+
'rightforeleg': 'right fore leg',
|
| 287 |
+
'lefthindleg': 'left hind leg',
|
| 288 |
+
'righthindleg': 'right hind leg',
|
| 289 |
+
'tail': 'tail',
|
| 290 |
+
'tail1': 'tail base',
|
| 291 |
+
'tail2': 'tail mid',
|
| 292 |
+
'tail3': 'tail tip',
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def normalize_joint_name(name: str) -> str:
|
| 297 |
+
"""Normalize joint name to a canonical human-readable form."""
|
| 298 |
+
key = name.lower().strip().replace(' ', '')
|
| 299 |
+
if key in JOINT_NAME_ALIASES:
|
| 300 |
+
return JOINT_NAME_ALIASES[key]
|
| 301 |
+
|
| 302 |
+
# Fallback: split camelCase and add spaces
|
| 303 |
+
import re
|
| 304 |
+
result = re.sub(r'([a-z])([A-Z])', r'\1 \2', name)
|
| 305 |
+
result = re.sub(r'[_:]', ' ', result)
|
| 306 |
+
return result.lower().strip()
|