text
stringlengths
0
1.47k
# means some twist leaves the overlap unchanged → rotation genuinely unconstrained. Kept as a low
# gate so it fires only on extreme rotational flatness (the residual gate catches ordinary
# failures); a discretely-sampled near-symmetric remnant that STILL aligns (Chamfer-success) is
# intentionally NOT failed by this gate.
_FS_AMBIG_SENSITIVITY = 0.02
# Diagnostic only: RANSAC hypothesis rotation spread among near-best hypotheses.
_FS_AMBIG_ROT_SPREAD_DEG = 12.0 # near-best hypotheses spread above this (deg) → rotation disagreement
_FS_TOPK_HYP = 12 # number of top RANSAC hypotheses kept for the spread test
_FS_HYP_SCORE_SLACK = 0.85 # a hypothesis is "near-best" if inliers >= slack * best_inliers
# Score epsilon for stability tie-break in global_align (used in align.py)
_SCORE_EPS = 1e-3
# ── k-NN ──────────────────────────────────────────────────────────────────────
def _knn_indices(pts: torch.Tensor, k: int) -> torch.Tensor:
"""For each point return the indices of its ``k`` nearest neighbours (excluding self).
Uses chunked ``cdist`` to bound memory. Returns ``(N, k)`` int64 indices.
CPU-friendly (no cuda required).
"""
N = pts.shape[0]
k = min(k, N - 1)
out = pts.new_empty((N, k), dtype=torch.int64)
step = max(1, int(4_000_000 // max(N, 1)))
for lo in range(0, N, step):
hi = min(lo + step, N)
d = torch.cdist(pts[lo:hi], pts) # (chunk, N)
d[:, lo:hi].fill_diagonal_(float("inf")) # exclude self
_, idx = torch.topk(d, k, dim=1, largest=False)
out[lo:hi] = idx
return out
# ── normals ────────────────────────────────────────────────────────────────────
def _estimate_normals(pts: torch.Tensor, idx: torch.Tensor) -> torch.Tensor:
"""Per-point surface normal ``(N, 3)`` from the smallest-eigenvector of the local covariance.
The normal is the eigenvector of the k-NN covariance with the *smallest* eigenvalue (the
direction of least variance = surface normal). Signs are disambiguated to point away from the
cloud centroid so both source and target orient consistently (FPFH features use the normal
directions, so a consistent convention is required for the descriptors to match across clouds).
Args:
pts: ``(N, 3)`` float32 cloud.
idx: ``(N, k)`` precomputed k-NN indices.
Returns:
``(N, 3)`` unit normals on the same device.
"""
N = pts.shape[0]
nbrs = pts[idx] # (N, k, 3)
centred = nbrs - nbrs.mean(dim=1, keepdim=True) # (N, k, 3)
cov = torch.einsum("nki,nkj->nij", centred, centred) / centred.shape[1] # (N, 3, 3)
# eigh returns ascending eigenvalues; smallest -> column 0 of eigenvectors
try:
_, evecs = torch.linalg.eigh(cov) # evecs: (N, 3, 3), columns are eigenvectors
except Exception:
return torch.zeros(N, 3, device=pts.device, dtype=pts.dtype).index_fill_(
1, torch.tensor([2], device=pts.device), 1.0
)
normals = evecs[:, :, 0] # (N, 3) smallest-eigenvalue direction
# Orient away from the cloud centroid (consistent sign convention across clouds).
centroid = pts.mean(dim=0, keepdim=True) # (1, 3)
out = pts - centroid # (N, 3) outward radial direction
flip = (normals * out).sum(dim=1) < 0.0 # normal points inward → flip
normals = torch.where(flip.unsqueeze(1), -normals, normals)
normals = normals / normals.norm(dim=1, keepdim=True).clamp_min(1e-9)
return normals
# ── FPFH descriptor (Rusu et al., ICRA 2009) ───────────────────────────────────
def _spfh(pts: torch.Tensor, normals: torch.Tensor, idx: torch.Tensor, bins: int) -> torch.Tensor:
"""Simplified Point Feature Histogram ``(N, 3*bins)`` from the Darboux-frame angles.
For every (anchor p, neighbour q) pair we build the Darboux frame from the two estimated
normals and compute the three classic PFH features:
u = n_p
v = (q - p) / ||q - p|| × u (cross product, then normalised)
w = u × v
alpha = v · n_q (in [-1, 1])
phi = u · (q - p) / ||q - p|| (in [-1, 1])
theta = atan2(w · n_q, u · n_q) (in [-pi, pi])
Each feature is histogrammed into ``bins`` bins; the three histograms are concatenated and
L1-normalised. Translation/rotation invariant by construction (only relative directions enter).
Args:
pts: ``(N, 3)`` cloud.
normals: ``(N, 3)`` unit normals.
idx: ``(N, k)`` k-NN indices.
bins: histogram bins per feature.