File size: 2,197 Bytes
24599ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import torch

from bbflow.models.latent import LatentEncoder


class _Cfg:
    dim = 16
    num_modes = 2
    motion_hidden_dim = 16
    motion_dist_bins = 4
    motion_dist_width = 4.0
    motion_message_passing_layers = 1
    template_residual_scale = 0.1
    template_remove_rotation = True


def test_motion_targets_include_oracle_pca_modes_and_energy():
    eq = torch.zeros(3, 3)
    mask = torch.ones(3)
    mode1 = torch.tensor([[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
    mode2 = torch.tensor([[0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, -2.0, 0.0]])
    coeffs = torch.tensor([[2.0, 0.0], [-2.0, 0.0], [0.0, 1.0], [0.0, -1.0]])
    frames = eq[None] + coeffs[:, 0, None, None] * mode1[None] + coeffs[:, 1, None, None] * mode2[None]

    targets = LatentEncoder.compute_motion_targets(frames, eq, mask, num_modes=2)

    assert targets["oracle_modes"].shape == (3, 2, 3)
    assert targets["oracle_energy"].shape == (2,)
    assert targets["oracle_mean_disp"].shape == (3, 3)
    assert torch.isfinite(targets["oracle_modes"]).all()
    assert torch.isfinite(targets["oracle_energy"]).all()
    assert targets["oracle_energy"].sum() > 0


def test_oracle_condition_uses_signed_coefficients_to_build_directional_field():
    encoder = LatentEncoder(_Cfg())
    modes = torch.zeros(1, 3, 2, 3)
    modes[0, :, 0, 0] = torch.tensor([1.0, -1.0, 0.0])
    modes[0, :, 1, 1] = torch.tensor([0.5, 0.5, -1.0])
    coeff = torch.tensor([[2.0, -3.0]])
    rotmats = torch.eye(3).reshape(1, 1, 3, 3).repeat(1, 3, 1, 1)
    mask = torch.ones(1, 3)

    condition = encoder.condition_from_mode_coefficients(modes, coeff, rotmats, mask)

    expected_disp = torch.einsum("bk,bnkd->bnd", condition["mode_coefficients"].float(), condition["u_global"].float())
    assert condition["disp_node_cond"].shape == (1, 3, 3)
    assert condition["disp_edge_cond"].shape == (1, 3, 3, 1)
    assert torch.allclose(condition["disp_node_cond"].float(), expected_disp, atol=1e-6)
    assert torch.allclose(
        condition["disp_edge_cond"].float()[..., 0],
        torch.einsum("bid,bjd->bij", expected_disp, expected_disp),
        atol=1e-6,
    )