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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
| """ Rajagopal 全身骨骼模型实现
论文 Section II-B: 20个刚体段,37个广义坐标 - 6自由度骨盆浮动关节 - 31个铰链关节(解剖学定义旋转轴) """
import torch import torch.nn as nn import numpy as np from typing import Dict, Tuple, Optional
class BiomechanicalSkeleton(nn.Module): """ 全身骨骼模型(基于 Rajagopal 2015) 拓扑结构: pelvis (root, 6-DOF) ├── spine → thorax → head ├── left_hip → left_thigh → left_shin → left_foot ├── right_hip → right_thigh → right_shin → right_foot ├── left_shoulder → left_upper_arm → left_forearm → left_hand └── right_shoulder → right_upper_arm → right_forearm → right_hand 20个刚体段,37个广义坐标 """ JOINT_DEFINITION = { 'pelvis': ('root', None, 6), 'spine': ('pelvis', 'sagittal', 3), 'thorax': ('spine', 'sagittal', 3), 'head': ('thorax', 'sagittal', 3), 'left_hip': ('pelvis', 'sagittal', 3), 'left_knee': ('left_thigh', 'sagittal', 1), 'left_ankle': ('left_shin', 'sagittal', 2), 'left_shoulder': ('thorax', 'sagittal', 3), 'left_elbow': ('left_upper_arm', 'sagittal', 1), 'left_wrist': ('left_forearm', 'sagittal', 2), 'right_hip': ('pelvis', 'sagittal', 3), 'right_knee': ('right_thigh', 'sagittal', 1), 'right_ankle': ('right_shin', 'sagittal', 2), 'right_shoulder': ('thorax', 'sagittal', 3), 'right_elbow': ('right_upper_arm', 'sagittal', 1), 'right_wrist': ('right_forearm', 'sagittal', 2), } SEGMENT_RATIOS = { 'pelvis_to_spine': 0.282, 'spine_to_thorax': 0.221, 'thorax_to_head': 0.182, 'hip_to_knee': 0.246, 'knee_to_ankle': 0.245, 'shoulder_to_elbow': 0.186, 'elbow_to_wrist': 0.146, } def __init__(self, num_markers: int = 17, num_foot_bodies: int = 4): super().__init__() self.num_q = 37 self.num_bodies = 20 self.num_markers = num_markers self.num_foot_bodies = num_foot_bodies self.register_buffer( 'default_segment_lengths', torch.tensor(list(self.SEGMENT_RATIOS.values())) ) def forward_kinematics( self, q: torch.Tensor, segment_scales: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ 可微前向运动学 Args: q: 广义坐标 (B, T, 37) segment_scales: 段长缩放因子 Returns: markers: 3D关节位置 (B, T, 17, 3) foot_contacts: 接触概率 (B, T, 4) """ B, T, _ = q.shape pelvis_pos = q[..., :3] pelvis_rot = q[..., 3:6] joint_angles = q[..., 6:] markers = self._compute_markers( pelvis_pos, pelvis_rot, joint_angles, segment_scales ) foot_contacts = self._compute_foot_contact(markers) return markers, foot_contacts def _compute_markers(self, pos, rot, angles, scales): """ 简化的前向运动学计算 实际实现中需要完整的运动学树遍历 这里给出关键步骤的伪代码框架 """ batch_size, seq_len, _ = pos.shape markers = torch.zeros(batch_size, seq_len, self.num_markers, 3) markers[:, :, 0, :] = pos spine_len = scales[:, 0:1] * self.default_segment_lengths[0] markers[:, :, 1, :] = pos + torch.cat([ torch.zeros_like(spine_len), torch.zeros_like(spine_len), spine_len ], dim=-1).unsqueeze(1) return markers def _compute_foot_contact(self, markers): """ 脚-地接触分类 4个脚体:左/右跟骨、左/右脚趾 判断依据:脚高度 < 阈值 且 脚速度 < 阈值 """ foot_indices = [7, 8, 10, 11] foot_pos = markers[:, :, foot_indices, :] foot_height = foot_pos[..., 2] foot_vel = torch.diff( foot_pos, dim=1, prepend=foot_pos[:, :1, :, :] ) foot_speed = torch.norm(foot_vel, dim=-1) height_score = torch.sigmoid(-10 * (foot_height - 0.05)) speed_score = torch.sigmoid(-10 * (foot_speed - 0.1)) contact_prob = height_score * speed_score return contact_prob
class ScalePredictor(nn.Module): """ 从雷达点云特征预测主体特异性段长缩放 论文 Section II-D: 主体特异性身体比例预测 """ def __init__(self, point_dim: int = 7, num_segments: int = 7): super().__init__() self.encoder = nn.Sequential( nn.Linear(point_dim, 128), nn.GELU(), nn.Linear(128, 256), nn.GELU(), nn.Linear(256, 128), nn.GELU() ) self.scale_head = nn.Sequential( nn.Linear(128, 64), nn.GELU(), nn.Linear(64, num_segments), nn.Sigmoid() ) def forward( self, point_cloud: torch.Tensor, mask: torch.Tensor = None ) -> torch.Tensor: """ Returns: scales: (B, num_segments) 段长缩放因子 """ x = self.encoder(point_cloud) if mask is not None: x = x * mask.unsqueeze(-1).float() x = x.sum(dim=1) / mask.sum(dim=1, keepdim=True).float() else: x = x.mean(dim=1) scales = self.scale_head(x) return scales
class MotionPredictionNetwork(nn.Module): """ 时序雷达 → 广义坐标预测网络 论文 Section II-E: BiLSTM + 潜在递归 """ def __init__( self, point_dim: int = 7, hidden_dim: int = 256, num_q: int = 37, num_contacts: int = 4, num_layers: int = 2 ): super().__init__() self.point_encoder = nn.Sequential( nn.Linear(point_dim, 128), nn.GELU(), nn.Linear(128, hidden_dim) ) self.spatial_attn = nn.MultiheadAttention( hidden_dim, num_heads=8, batch_first=True ) self.temporal_lstm = nn.LSTM( input_size=hidden_dim, hidden_size=hidden_dim, num_layers=num_layers, batch_first=True, bidirectional=True ) self.q_head = nn.Linear(hidden_dim * 2, num_q) self.contact_head = nn.Linear(hidden_dim * 2, num_contacts) def forward( self, radar_sequence: torch.Tensor, point_mask: torch.Tensor = None ) -> Tuple[torch.Tensor, torch.Tensor]: """ Returns: q: (B, T, 37) 广义坐标 contact_logits: (B, T, 4) 接触分类logits """ B, T, N, F = radar_sequence.shape x = self.point_encoder(radar_sequence) x = x.view(B * T, N, -1) if point_mask is not None: point_mask_flat = point_mask.view(B * T, N) else: point_mask_flat = None x, _ = self.spatial_attn(x, x, x, key_padding_mask=point_mask_flat) x = x.mean(dim=1) x = x.view(B, T, -1) x, _ = self.temporal_lstm(x) q = self.q_head(x) contact_logits = self.contact_head(x) return q, contact_logits
class RadarBiomechanicalHPE(nn.Module): """ 完整的雷达-生物力学人体姿态估计框架 端到端可微管道: 雷达点云 → MotionPrediction → 广义坐标 → BiomechanicalSkeleton.forward_kinematics → 3D关节位置 + 接触 → 联合损失(位置 + 接触) """ def __init__(self): super().__init__() self.motion_net = MotionPredictionNetwork() self.scale_net = ScalePredictor() self.skeleton = BiomechanicalSkeleton() def forward( self, radar_seq: torch.Tensor, point_mask: torch.Tensor = None ) -> Dict[str, torch.Tensor]: q, contact_logits = self.motion_net(radar_seq, point_mask) first_frame = radar_seq[:, 0, :, :] first_mask = point_mask[:, 0, :] if point_mask is not None else None scales = self.scale_net(first_frame, first_mask) markers, foot_contacts = self.skeleton.forward_kinematics(q, scales) return { 'q': q, 'contact_logits': contact_logits, 'scales': scales, 'markers': markers, 'foot_contacts': foot_contacts }
class CombinedLoss(nn.Module): """ 组合损失:数据追踪 + 接触分类 L = L_pos + λ_contact * L_contact + λ_scale * L_scale """ def __init__(self, lambda_contact=1.0, lambda_scale=0.5): super().__init__() self.lambda_contact = lambda_contact self.lambda_scale = lambda_scale def forward( self, pred: dict, gt_markers: torch.Tensor, gt_contacts: torch.Tensor, gt_scales: torch.Tensor ) -> Tuple[torch.Tensor, dict]: pos_loss = nn.functional.mse_loss(pred['markers'], gt_markers) contact_loss = nn.functional.binary_cross_entropy_with_logits( pred['contact_logits'], gt_contacts.float() ) scale_loss = nn.functional.mse_loss(pred['scales'], gt_scales) total = ( pos_loss + self.lambda_contact * contact_loss + self.lambda_scale * scale_loss ) return total, { 'pos_loss': pos_loss.item(), 'contact_loss': contact_loss.item(), 'scale_loss': scale_loss.item() }
if __name__ == "__main__": torch.manual_seed(42) B, T, N, F = 4, 30, 192, 7 radar_input = torch.randn(B, T, N, F) point_mask = torch.ones(B, T, N, dtype=torch.bool) gt_markers = torch.randn(B, T, 17, 3) * 1.0 gt_contacts = torch.randint(0, 2, (B, T, 4)).float() gt_scales = torch.rand(B, 7) * 0.3 + 0.85 model = RadarBiomechanicalHPE() criterion = CombinedLoss() pred = model(radar_input, point_mask) loss, metrics = criterion(pred, gt_markers, gt_contacts, gt_scales) print("=" * 60) print("Radar-Biomechanical HPE 测试结果") print("=" * 60) print(f"输入: 雷达点云 {radar_input.shape}") print(f"广义坐标: {pred['q'].shape}") print(f"关节位置: {pred['markers'].shape}") print(f"接触logits: {pred['contact_logits'].shape}") print(f"段长缩放: {pred['scales'].shape}") print(f"\n损失: {loss.item():.4f}") for k, v in metrics.items(): print(f" {k}: {v:.4f}") total_params = sum(p.numel() for p in model.parameters()) print(f"\n模型参数: {total_params:,} ({total_params/1e6:.2f}M)")
|