Files
ailed-experiments-rp/tests/test_particles.py
T

92 lines
3.1 KiB
Python

import torch
from particles import ParticleConfig, ParticleWorld, wrapped_diff
def test_wrapped_diff_range_and_antisymmetry():
c = torch.rand(10, 2)
d = wrapped_diff(c)
assert d.shape == (10, 10, 2)
assert d.min() >= -0.5 and d.max() < 0.5
assert torch.allclose(torch.diagonal(d, dim1=0, dim2=1), torch.zeros(2, 10))
# a pair separated by 0.7 along x must read as -0.3, not 0.7
two = torch.tensor([[0.1, 0.0], [0.8, 0.0]])
assert torch.allclose(wrapped_diff(two)[0, 1], torch.tensor([-0.3, 0.0]), atol=1e-6)
def rollout(cfg, steps):
w = ParticleWorld(cfg)
return [w.step() for _ in range(steps)]
def test_same_seed_same_trajectory():
a = rollout(ParticleConfig(seed=3), 50)
b = rollout(ParticleConfig(seed=3), 50)
for x, y in zip(a, b):
assert torch.equal(x.coords, y.coords) and torch.equal(x.target, y.target)
def test_oracles_do_not_change_the_world():
base = rollout(ParticleConfig(seed=1), 200)
for oracle in ("change", "regime"):
alt = rollout(ParticleConfig(seed=1, oracle=oracle), 200)
for x, y in zip(base, alt):
assert torch.equal(x.coords, y.coords)
assert torch.equal(x.target, y.target)
assert x.regime == y.regime and x.switched == y.switched
def test_attr_width_per_oracle():
assert ParticleWorld(ParticleConfig()).attr_dim == 3
assert ParticleWorld(ParticleConfig(oracle="change")).attr_dim == 4
assert ParticleWorld(ParticleConfig(oracle="regime")).attr_dim == 3 + 4
def test_change_flag_only_on_switch_steps():
obs = rollout(ParticleConfig(seed=2, oracle="change"), 300)
for o in obs:
flag = o.attrs[:, 3]
assert bool(flag.max()) == o.switched
assert flag.min() == flag.max()
def test_regime_onehot_matches_regime():
obs = rollout(ParticleConfig(seed=2, oracle="regime"), 300)
for o in obs:
assert torch.equal(o.attrs[0, 3:].argmax(), torch.tensor(o.regime))
def test_switches_happen_within_bounds_and_change_regime():
obs = rollout(ParticleConfig(seed=5, t_min=20, t_max=30), 400)
switch_steps = [i for i, o in enumerate(obs) if o.switched]
assert len(switch_steps) >= 10
gaps = [b - a for a, b in zip(switch_steps, switch_steps[1:])]
assert all(20 <= g <= 30 for g in gaps)
for i in switch_steps:
assert obs[i].regime != obs[i - 1].regime
def test_target_is_next_delta():
w = ParticleWorld(ParticleConfig(seed=7))
o1 = w.step(); o2 = w.step()
expected = (o2.coords - o1.coords + 0.5) % 1.0 - 0.5
assert torch.allclose(expected, o1.target, atol=1e-6)
def test_target_matches_wrapped_coordinate_update():
w = ParticleWorld(ParticleConfig(seed=11))
prev = w.step()
for _ in range(300):
cur = w.step()
d = cur.coords - prev.coords
wrapped = d - torch.floor(d + 0.5)
assert torch.allclose(prev.target, wrapped, atol=1e-6)
prev = cur
def test_zero_regime_and_no_noise_is_static():
cfg = ParticleConfig(seed=0, noise=0.0)
w = ParticleWorld(cfg)
w.regimes[w.regime] = torch.zeros(3, 3)
o = w.step()
assert torch.allclose(o.target, torch.zeros_like(o.target))