text
stringlengths
0
1.47k
s = (D * torch.diagonal(S)).sum() / var_src.clamp_min(1e-12)
else:
s = torch.ones((), device=src.device, dtype=src.dtype)
t = dst_mean - s * (R @ src_mean)
return s, R, t
# ── batched torch ICP helpers (already on-device) ─────────────────────────────────────
def _stride_subsample(a: torch.Tensor, k: int) -> torch.Tensor:
"""Deterministic strided subsample to <= k rows (no RNG)."""
if a.shape[0] <= k:
return a
sel = torch.linspace(0, a.shape[0] - 1, k, device=a.device).round().to(torch.int64)
return a[sel]
def _batched_nn(X: torch.Tensor, Y: torch.Tensor):
"""Batched squared-distance nearest neighbour: for each ``X[b,i]`` its nearest ``Y[b]``.
Chunked ``torch.cdist``. Returns ``(dist_sq (B,Nx), idx (B,Nx))``; chunks over the query
axis to bound the ``(B,Nx,Ny)`` pairwise tensor.
"""
B, Nx, _ = X.shape
Ny = Y.shape[1]
out_d = X.new_empty((B, Nx))
out_i = torch.empty((B, Nx), device=X.device, dtype=torch.int64)
step = max(1, int(8_000_000 // max(B * Ny, 1)))
for lo in range(0, Nx, step):
hi = min(lo + step, Nx)
d = torch.cdist(X[:, lo:hi], Y)
md, mi = d.min(dim=2)
out_d[:, lo:hi] = md * md
out_i[:, lo:hi] = mi
return out_d, out_i
def _batched_umeyama(X: torch.Tensor, Y: torch.Tensor, w: torch.Tensor, with_scale: bool):
"""Batched weighted closed-form similarity mapping ``X[b] -> Y[b]`` (Umeyama 1991).
``w (B,N)`` are non-negative weights (the trim mask). Returns ``(s (B,), R (B,3,3),
t (B,3))`` with ``Y ≈ s * (X @ R.T) + t``.
"""
B = X.shape[0]
ws = w.sum(dim=1, keepdim=True).clamp_min(1e-9)
wn = (w / ws).unsqueeze(-1)
mu_x = (wn * X).sum(dim=1)
mu_y = (wn * Y).sum(dim=1)
Xc = X - mu_x.unsqueeze(1)
Yc = Y - mu_y.unsqueeze(1)
cov = torch.einsum("bni,bnj->bij", wn * Yc, Xc)
U, Dsv, Vh = torch.linalg.svd(cov)
detUV = torch.linalg.det(U) * torch.linalg.det(Vh)
S = torch.eye(3, device=X.device, dtype=X.dtype).expand(B, 3, 3).clone()
S[:, 2, 2] = torch.sign(detUV)
R = U @ S @ Vh
if with_scale:
var_x = (wn * Xc.pow(2)).sum(dim=(1, 2)).clamp_min(1e-12)
s = (Dsv * torch.diagonal(S, dim1=1, dim2=2)).sum(dim=1) / var_x
else:
s = torch.ones(B, device=X.device, dtype=X.dtype)
t = mu_y - s.unsqueeze(1) * torch.einsum("bij,bj->bi", R, mu_x)
return s, R, t
def _trim_mean_sqrt(dist_sq: torch.Tensor, frac: float) -> torch.Tensor:
"""Mean of the sqrt of the lowest ``frac`` fraction of squared distances, per batch row."""
k = max(1, int(round(frac * dist_sq.shape[1])))
v, _ = torch.sort(dist_sq, dim=1)
return v[:, :k].sqrt().mean(dim=1)
def _batched_trimmed_icp(
src_sub: torch.Tensor, tgt_sub: torch.Tensor, R_seeds: torch.Tensor, with_scale: bool, icp_iters: int
):
"""All seeds through one batched trimmed point-to-point ICP (centre, per-seed scale match,
trimmed Umeyama iterations, trimmed symmetric Chamfer score). Returns ``(aligned (B,K,3),
score (B,))`` (lower score = better). Seeds processed in chunks of ``_SEED_BATCH``."""
K, Kg = src_sub.shape[0], tgt_sub.shape[0]
pc = src_sub.mean(0)
gc = tgt_sub.mean(0)
p0c = src_sub - pc
rg = (tgt_sub - gc).pow(2).sum(-1).mean().sqrt()
keep_k = max(3, int(round(_ICP_TRIM_KEEP * K)))
aligned_chunks: list[torch.Tensor] = []
score_chunks: list[torch.Tensor] = []
for lo in range(0, R_seeds.shape[0], _SEED_BATCH):
Rb = R_seeds[lo : lo + _SEED_BATCH]
b = Rb.shape[0]
X = torch.bmm(p0c.unsqueeze(0).expand(b, K, 3), Rb.transpose(1, 2))
if with_scale:
rp = X.pow(2).sum(-1).mean(1).sqrt()
X = X * (rg / rp.clamp_min(1e-9)).view(b, 1, 1)
X = X + gc
Y = tgt_sub.unsqueeze(0).expand(b, Kg, 3).contiguous()
for _ in range(int(icp_iters)):
d, idx = _batched_nn(X, Y)
Ym = torch.gather(Y, 1, idx.unsqueeze(-1).expand(b, K, 3))