Files
ailed-experiments-rp/particles.py
T

120 lines
4.6 KiB
Python

"""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): raw per-step displacement; equals the wrapped
# coords[t+1] - coords[t] as long as the step() assert holds
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()
# target is the raw delta, so it only matches the wrapped coordinate update while a
# particle moves less than half the torus per step. Default config peaks near 0.06;
# a config that trips this (larger n, dt, or sigma) is physically meaningless, not
# something to silently wrap away.
assert delta.abs().max() < 0.5, "per-step displacement exceeds half the torus"
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