"""지면 모델 (nusim.recon.ground) — GPU 없이 CPU 텐서로.""" import math import torch from nusim.recon.ground import GROUND_THICKNESS, flatten, ground_loss, init_flat def test_ground_loss_flat_vs_bumpy(): g = torch.Generator().manual_seed(0) xy = torch.rand(20000, 2, generator=g) * 20 m = torch.ones(20000, dtype=torch.bool) flat = torch.cat([xy, torch.zeros(20000, 1)], 1) bumpy = torch.cat([xy, torch.randn(20000, 1, generator=g) * 0.1], 1) assert float(ground_loss(flat, m)) < 1e-9 assert abs(float(ground_loss(bumpy, m)) - 0.01) < 0.002 # 분산 = 0.1² def test_ground_loss_slope_is_small_per_patch(): # 5% 경사: 1 m 칸 안 높이 차 5 cm → 분산 ≈ 0.05²/12 — 평탄하지 않다고 크게 벌주지 않는다 xy = torch.rand(20000, 2) * 20 z = 0.05 * xy[:, :1] v = float(ground_loss(torch.cat([xy, z], 1), torch.ones(20000, dtype=torch.bool))) assert v < 0.05 ** 2 / 12 * 1.5 def test_ground_loss_ignores_non_ground_and_has_grad(): means = torch.cat([torch.rand(1000, 2) * 5, torch.randn(1000, 1)], 1).requires_grad_(True) mask = torch.zeros(1000, dtype=torch.bool) assert float(ground_loss(means, mask)) == 0.0 mask[:500] = True ground_loss(means, mask).backward() assert means.grad[500:].abs().sum() == 0 and means.grad[:500, 2].abs().sum() > 0 def test_flatten_only_touches_ground(): p = {"quats": torch.nn.Parameter(torch.randn(4, 4)), "scales": torch.nn.Parameter(torch.randn(4, 3))} before_q, before_s = p["quats"].data.clone(), p["scales"].data.clone() mask = torch.tensor([True, False, True, False]) init_flat(p, mask) assert torch.equal(p["quats"].data[0], torch.tensor([1.0, 0, 0, 0])) assert math.isclose(float(p["scales"].data[2, 2]), math.log(GROUND_THICKNESS), rel_tol=1e-6) assert float(p["scales"].data[0, 0]) == float(p["scales"].data[0, 1]) assert torch.equal(p["quats"].data[~mask], before_q[~mask]) assert torch.equal(p["scales"].data[~mask], before_s[~mask]) p["quats"].data[0] = torch.tensor([0.0, 1, 0, 0]) flatten(p, mask) assert torch.equal(p["quats"].data[0], torch.tensor([1.0, 0, 0, 0]))