"""Scene sampling, deterministic rollout, and counterfactual re-simulation.""" import numpy as np from . import config, physics, events as events_mod # -------------------------------------------------------------------------- # scene specification (serializable dicts) <-> Body objects # -------------------------------------------------------------------------- def sample_spec(rng, n_objects=None, probe=False): """Sample a random CLEVRER-style scene spec (list of dicts).""" n = int(n_objects if n_objects is not None else rng.integers(3, 7)) # 3..6 colors = rng.permutation(config.COLOR_NAMES)[:n] # unique colors shapes = rng.choice(config.SHAPES, size=n) materials = rng.choice(config.MATERIALS, size=n) sizes = rng.choice(config.SIZES, size=n) # non-overlapping positions (rejection sampling) radii = np.array([rng.uniform(*config.SIZE_RADIUS[s]) for s in sizes]) positions = np.zeros((n, 2)) placed = 0 tries = 0 while placed < n: tries += 1 if tries > 4000: raise RuntimeError("could not place objects without overlap") p = rng.uniform(-config.SPAWN_HALF, config.SPAWN_HALF, size=2) ok = True for k in range(placed): if np.linalg.norm(p - positions[k]) < radii[k] + radii[placed] + 0.22: ok = False break if ok: positions[placed] = p placed += 1 # at least 2 objects moving, at least one stationary (for causal questions) n_moving = int(rng.integers(2, min(n, 4) + 1)) moving_idx = set(rng.permutation(n)[:n_moving].tolist()) spec = [] for i in range(n): v = np.zeros(2) if i in moving_idx: theta = rng.uniform(0, 2 * np.pi) speed = rng.uniform(*config.SPEED_RANGE) v = np.array([np.cos(theta), np.sin(theta)]) * speed spec.append({ "idx": i, "color": str(colors[i]), "shape": str(shapes[i]), "material": str(materials[i]), "size": str(sizes[i]), "radius": float(radii[i]), "position": positions[i].tolist(), "velocity": v.tolist(), "spin": float(rng.uniform(-1.5, 1.5)), "is_probe": False, }) if probe: theta = rng.uniform(0, 2 * np.pi) spec.append({ "idx": n, "color": config.PROBE_COLOR, "shape": "sphere", "material": "metal", "size": config.PROBE_SIZE, "radius": config.PROBE_RADIUS, "position": rng.uniform(-config.SPAWN_HALF, config.SPAWN_HALF, size=2).tolist(), "velocity": [0.0, 0.0], "spin": 0.0, "is_probe": True, }) return spec def bodies_from_spec(spec): from dataclasses import fields as dc_fields bodies = [] for s in spec: kwargs = {k: s[k] for k in ("idx", "color", "shape", "material", "size", "radius", "spin", "is_probe")} kwargs["pos"] = np.array(s["position"], dtype=float) kwargs["vel"] = np.array(s["velocity"], dtype=float) kwargs["mass"] = physics.mass_of(s["radius"], s["material"]) kwargs["angle"] = 0.0 bodies.append(physics.Body(**kwargs)) return bodies def spec_of(bodies): return [{ "idx": b.idx, "color": b.color, "shape": b.shape, "material": b.material, "size": b.size, "radius": float(b.radius), "position": b.pos.tolist(), "velocity": b.vel.tolist(), "spin": float(b.spin), "is_probe": b.is_probe, } for b in bodies] # -------------------------------------------------------------------------- # rollout # -------------------------------------------------------------------------- def rollout(bodies, num_frames, render_fn=None, action_fn=None): """Run a deterministic rollout (physics never uses RNG). Args: bodies: list[Body] (mutated in place). num_frames: number of rendered frames. render_fn: optional callable(bodies) -> frame array. action_fn: optional callable(t, bodies) applied at the start of frame t (used by the gym env for probe-ball actions). Returns: dict with states (T, n, 4), collisions [(t, i, j)], wall_hits [(t, i, ax, s)], and frames (T, H, W, 3) if render_fn was given. """ world = physics.World(bodies) n = len(bodies) states = np.zeros((num_frames, n, 4), dtype=float) collisions, wall_hits = [], [] frames = [] if render_fn is not None else None for t in range(num_frames): if action_fn is not None: action_fn(t, bodies) for _ in range(config.SUBSTEPS): contacts, hits = world.step(config.SUB_DT) for (i, j) in contacts: collisions.append((t, i, j)) for (i, ax, s) in hits: wall_hits.append((t, i, ax, s)) for k, b in enumerate(bodies): states[t, k] = (b.pos[0], b.pos[1], b.vel[0], b.vel[1]) if render_fn is not None: frames.append(render_fn(bodies)) return {"states": states, "collisions": collisions, "wall_hits": wall_hits, "frames": frames} # -------------------------------------------------------------------------- # counterfactual re-simulation (the CLEVRER trick: remove an object, re-run) # -------------------------------------------------------------------------- def resimulate_without(spec, removed_idx, num_frames): """Deep-copy the scene minus one object, re-run physics, extract events.""" import copy spec2 = copy.deepcopy([s for s in spec if s["idx"] != removed_idx]) bodies = bodies_from_spec(spec2) out = rollout(bodies, num_frames, render_fn=None) ev = events_mod.extract_events(out["states"], out["collisions"], out["wall_hits"], n=len(bodies)) return ev