text
stringlengths
0
1.47k
thr = torch.kthvalue(d, keep_k, dim=1, keepdim=True).values
wmask = (d <= thr).to(X.dtype)
s_i, R_i, t_i = _batched_umeyama(X, Ym, wmask, with_scale)
X = s_i[:, None, None] * torch.bmm(X, R_i.transpose(1, 2)) + t_i[:, None, :]
d_xy, _ = _batched_nn(X, Y)
d_yx, _ = _batched_nn(Y, X)
score = 0.5 * (_trim_mean_sqrt(d_xy, _ICP_TRIM_KEEP) + _trim_mean_sqrt(d_yx, _ICP_TRIM_KEEP))
aligned_chunks.append(X)
score_chunks.append(score)
return torch.cat(aligned_chunks, dim=0), torch.cat(score_chunks, dim=0)
# ── public entry ──────────────────────────────────────────────────────────────────────
@torch.no_grad()
def global_align(
target: Gaussians,
source: Gaussians,
*,
transform: str = "sim3",
n_rotations: int = DEFAULT_N_ROTATIONS,
icp_iters: int = DEFAULT_ICP_ITERS,
n_points: int = DEFAULT_N_POINTS,
seed: int = 0,
) -> torch.Tensor:
"""Coarse global init: a 4x4 transform that lands ``source`` in ``target``'s basin.
Sweeps ``n_rotations`` super-Fibonacci SO(3) candidates (plus PCA sign-flips), scores each
by a batched trimmed symmetric Chamfer after a batched trimmed ICP, and returns the
closed-form similarity for the best seed, a *basin-correct init* for the fine LM, not a
precise pose. Runs fully on ``source``'s device (CPU or CUDA); no host round-trip.
Args:
target: the reference splat (``source`` aligns onto it). Only ``.means`` is read.
source: the splat to align.
transform: ``"sim3"`` (default) estimates a scale; ``"se3"`` fixes scale to 1.
n_rotations: super-Fibonacci SO(3) seed count (more -> finer covering, slower).
icp_iters: trimmed-ICP iterations per seed.
n_points: target subsample size for the fit.
seed: accepted for API stability; deterministic (no RNG).
Returns:
A ``(4, 4)`` ``torch.Tensor`` on ``source``'s device/dtype: ``T @ [x,y,z,1]``; top-left
block ``s*R`` (Sim(3)) or ``R`` (SE(3)), last column the translation.
"""
del seed # deterministic; no RNG to seed (documented for API stability)
if transform not in ("sim3", "se3"):
raise ValueError(f"transform must be 'sim3' or 'se3', got {transform!r}")
with_scale = transform == "sim3"
dev = source.means.device
dtype = source.means.dtype
src_full = source.means
tgt_full = target.means.to(device=dev, dtype=dtype)
if src_full.shape[0] < 3 or tgt_full.shape[0] < 3:
return torch.eye(4, device=dev, dtype=dtype)
# Fit in float32 on-device (SVD/cdist stability); deterministic strided subsample.
src_sub = _stride_subsample(src_full, _SUB_SOURCE).to(torch.float32)
tgt_sub = _stride_subsample(tgt_full, int(n_points)).to(torch.float32)
# Seeds (all on-device): PCA sign-flip candidates first (deterministic tie favours them),
# then the super-Fibonacci grid.
R_pca = _pca_seed_rotations(src_sub, tgt_sub) # (<=5,3,3)
R_grid = super_fibonacci_so3(int(n_rotations), device=dev, dtype=torch.float32) # (n,3,3)
R_seeds = torch.cat([R_pca, R_grid], dim=0)
aligned_sub, scores = _batched_trimmed_icp(src_sub, tgt_sub, R_seeds, with_scale, int(icp_iters))
# Stability tie-break (symmetric fix): among seeds within _SCORE_EPS
# of the best score, prefer the one whose centroid is closest to the target centroid —
# a proxy for scale/translation stability that avoids per-seed SVD calls and works in
# tensor ops. For symmetric clouds all seeds score nearly equally; the first-index
# tie-break can pick a degenerate seed (wrong translation). Centroid proximity picks
# the seed that lands source closest to target without needing to refit Umeyama per seed.
_SCORE_EPS = 5e-3
best_score = scores.min()
near_best = scores <= best_score + _SCORE_EPS * (best_score.abs().clamp_min(1.0))
near_idx = near_best.nonzero(as_tuple=False).squeeze(1) # indices of near-best seeds
if near_idx.shape[0] > 1:
# Pick the near-best seed whose centroid is closest to the target centroid.
# aligned_sub[b] is the source sub-sample after ICP convergence under seed b.
near_centroids = aligned_sub[near_idx].mean(dim=1) # (K, 3)
tgt_centroid = tgt_sub.mean(0) # (3,)
centroid_dists = (near_centroids - tgt_centroid).norm(dim=1) # (K,)
best_sub = near_idx[centroid_dists.argmin()]
else:
best_sub = torch.argmin(scores)
winner = aligned_sub[best_sub] # stays on-device
# Recover the exact closed-form similarity src_sub -> winner in float64 on-device.
s_tot, R_tot, t_tot = _umeyama(src_sub.double(), winner.double(), with_scale)
T = torch.eye(4, dtype=dtype, device=dev)
T[:3, :3] = (s_tot * R_tot).to(dtype=dtype)
T[:3, 3] = t_tot.to(dtype=dtype)
return T
# ===== file: splatreg/align_features.py =====