hanghang214's picture
Add files using upload-large-folder tool
9e6e56b verified
Raw History Blame Contribute Delete
2.34 kB
import torch
ALIGNMENT_VERSION = "row_kabsch_u_d_vh_v1"
def require_alignment_version(payload, source="motion-target cache"):
actual = payload.get("alignment_version") if isinstance(payload, dict) else None
if actual != ALIGNMENT_VERSION:
raise ValueError(
f"{source} alignment_version mismatch: expected "
f"{ALIGNMENT_VERSION!r}, got {actual!r}; regenerate the cache with "
"scripts/extract_shape_fingerprints.py"
)
def kabsch_align(moving, target, mask):
"""Align batched row-vector coordinates onto targets with proper rotations."""
out_dtype = moving.dtype
if target.dim() == 2:
target = target.unsqueeze(0).expand(moving.shape[0], -1, -1)
if mask.dim() == 1:
mask = mask.unsqueeze(0).expand(moving.shape[0], -1)
aligned = []
with torch.autocast(device_type=moving.device.type, enabled=False):
moving_f = moving.float()
target_f = target.to(device=moving.device, dtype=torch.float32)
mask_f = mask.to(device=moving.device, dtype=torch.float32)
for sample_moving, sample_target, sample_mask in zip(
moving_f, target_f, mask_f
):
valid = sample_mask.bool()
moving_valid = sample_moving[valid]
target_valid = sample_target[valid]
moving_mean = moving_valid.mean(dim=0, keepdim=True)
target_mean = target_valid.mean(dim=0, keepdim=True)
if int(valid.sum().item()) < 3:
aligned.append(
sample_moving - moving_mean + target_mean
)
continue
covariance = (
moving_valid - moving_mean
).transpose(0, 1) @ (target_valid - target_mean)
u, _, vh = torch.linalg.svd(covariance)
correction = torch.eye(
3, device=moving.device, dtype=torch.float32
)
correction[-1, -1] = torch.where(
torch.det(u @ vh) < 0,
correction.new_tensor(-1.0),
correction.new_tensor(1.0),
)
rotation = u @ correction @ vh
aligned.append(
(sample_moving - moving_mean) @ rotation + target_mean
)
return torch.stack(aligned, dim=0).to(dtype=out_dtype)