feat: relational particles world with regime switches and opt-in oracles (spec §7)

This commit is contained in:
chrnx committed 2026-09-02 07:36:25 -05:00
1 parent 17567efcec
commit de27334fc3
2 files changed
+193

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
"""Relational particles with unannounced regime switches. Spec §7.
The world is deterministic given `seed`. Oracles only append columns to `attrs`;
they never touch the trajectory (asserted in tests).
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
import torch
from torch import Tensor
ORACLES = ("none", "change", "regime")
def wrapped_diff(coords: Tensor) -> Tensor:
"""r_ij = c_j - c_i on the unit torus, in [-0.5, 0.5)."""
d = coords[None, :, :] - coords[:, None, :]
return d - torch.floor(d + 0.5)
@dataclass(frozen=True)
class ParticleConfig:
n: int = 16
n_types: int = 3
dt: float = 0.05
sigma: float = 0.2
noise: float = 0.002
n_regimes: int = 4
t_min: int = 40
t_max: int = 80
seed: int = 0
oracle: str = "none"
@dataclass
class Observation:
attrs: Tensor # (N, d)
coords: Tensor # (N, 2)
ids: list[int]
target: Tensor # (N, 2): coords[t+1] - coords[t], wrapped
switched: bool # True on the first step of a new regime
regime: int
class ParticleWorld:
def __init__(self, cfg: ParticleConfig):
assert cfg.oracle in ORACLES, cfg.oracle
self.cfg = cfg
self.rng = np.random.default_rng(cfg.seed)
self.torch_gen = torch.Generator().manual_seed(cfg.seed)
self.regimes = self._distinct_regimes()
self.types = torch.tensor(self.rng.integers(0, cfg.n_types, size=cfg.n))
self.coords = torch.tensor(self.rng.random((cfg.n, 2)), dtype=torch.float32)
self.regime = int(self.rng.integers(0, cfg.n_regimes))
self.until = self._next_switch(0)
self.t = 0
self.ids = list(range(cfg.n))
# -- setup ---------------------------------------------------------------
def _distinct_regimes(self) -> list[Tensor]:
seen, out = set(), []
while len(out) < self.cfg.n_regimes:
k = self.rng.choice([-1, 0, 1], size=(self.cfg.n_types, self.cfg.n_types))
key = k.tobytes()
if key in seen or not k.any():
continue
seen.add(key)
out.append(torch.tensor(k, dtype=torch.float32))
return out
def _next_switch(self, now: int) -> int:
return now + int(self.rng.integers(self.cfg.t_min, self.cfg.t_max + 1))
# -- dynamics ------------------------------------------------------------
def _delta(self) -> Tensor:
r = wrapped_diff(self.coords) # (N,N,2)
k = self.regimes[self.regime][self.types[:, None], self.types[None, :]] # (N,N)
kern = torch.exp(-(r ** 2).sum(-1) / self.cfg.sigma ** 2) # (N,N)
kern.fill_diagonal_(0.0)
force = (k * kern)[:, :, None] * r # (N,N,2)
noise = self.cfg.noise * torch.randn(self.cfg.n, 2, generator=self.torch_gen)
return self.cfg.dt * force.sum(1) + noise
@property
def attr_dim(self) -> int:
return self.cfg.n_types + {"none": 0, "change": 1, "regime": self.cfg.n_regimes}[self.cfg.oracle]
def _attrs(self, switched: bool) -> Tensor:
cols = [torch.nn.functional.one_hot(self.types, self.cfg.n_types).float()]
if self.cfg.oracle == "change":
cols.append(torch.full((self.cfg.n, 1), float(switched)))
elif self.cfg.oracle == "regime":
onehot = torch.zeros(self.cfg.n, self.cfg.n_regimes); onehot[:, self.regime] = 1.0
cols.append(onehot)
return torch.cat(cols, dim=1)
def step(self) -> Observation:
switched = False
if self.t == self.until:
choices = [i for i in range(self.cfg.n_regimes) if i != self.regime]
self.regime = int(self.rng.choice(choices))
self.until = self._next_switch(self.t)
switched = True
delta = self._delta()
obs = Observation(attrs=self._attrs(switched), coords=self.coords.clone(),
ids=list(self.ids), target=delta, switched=switched, regime=self.regime)
self.coords = (self.coords + delta) % 1.0
self.t += 1
return obs
+80
View File
@@ -0,0 +1,80 @@
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_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))