File size: 6,448 Bytes
06b3545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""OpenAI Gym wrapper for the CLEVRER-lite environment.

    env = CLEVRERLiteEnv()
    obs, info = env.reset(seed=0)
    obs, reward, terminated, truncated, info = env.step(env.action_space.sample())

Observation: (frame_size, frame_size, 3) uint8 RGB frame (top-down view).
Action:      Discrete(5) - {noop, push probe ball E/N/W/S}.
             With ``probe=False`` every action is a no-op, giving the purely
             passive CLEVRER dynamics.
Reward:      0.0 (the task is video reasoning, not control).
Info:        per-frame physics state + collisions so far.

The env records the full trajectory, so after an episode you can call
``extract_events()`` / ``build_questions()`` to get CLEVRER-style annotations.
"""

import numpy as np

try:
    import gym
except ImportError:                                    # pragma: no cover
    import gymnasium as gym
from gym import spaces

from . import config, renderer, simulate, events as events_mod, questions as questions_mod


class CLEVRERLiteEnv(gym.Env):
    """A CLEVRER-like world of colliding objects as a gym environment."""

    metadata = {
        "render_modes": ["rgb_array"],
        "render_fps": int(round(1.0 / config.FRAME_DT)),
    }

    def __init__(self, num_objects=(3, 6), num_frames=64, frame_size=128,
                 probe=False, min_collisions=2, min_initially_moving=2,
                 render_mode=None):
        self.num_objects = (tuple(num_objects) if isinstance(num_objects, (tuple, list))
                            else (int(num_objects), int(num_objects)))
        self.num_frames = int(num_frames)
        self.frame_size = int(frame_size)
        self.probe = bool(probe)
        self.min_collisions = int(min_collisions)
        self.min_initially_moving = int(min_initially_moving)
        self.render_mode = render_mode

        self.observation_space = spaces.Box(0, 255, (self.frame_size, self.frame_size, 3),
                                            np.uint8)
        self.action_space = spaces.Discrete(len(config.ACTION_LABELS))

        # episode state
        self._spec = None
        self._bodies = None
        self._t = 0
        self._last_obs = None
        self._trajectory = None
        self._collisions = []
        self._wall_hits = []

    # ------------------------------------------------------------------ api
    def reset(self, *, seed=None, options=None):
        super().reset(seed=seed)
        rng = self.np_random

        # sample a scene that is rich enough for causal questions
        for _ in range(60):
            spec = simulate.sample_spec(rng, rng.integers(self.num_objects[0],
                                                          self.num_objects[1] + 1),
                                        probe=self.probe)
            bodies = simulate.bodies_from_spec(spec)
            out = simulate.rollout(bodies, self.num_frames)
            ev = events_mod.extract_events(out["states"], out["collisions"],
                                           out["wall_hits"], n=len(bodies))
            stationary = [i for i in range(len(bodies))
                          if i not in ev["initially_moving"]]
            if (len(ev["collisions"]) >= self.min_collisions
                    and len(ev["initially_moving"]) >= self.min_initially_moving
                    and (not self.probe or len(stationary) >= 1)):
                break
        else:
            pass  # keep the last sample even if not ideal

        self._spec = spec
        self._bodies = simulate.bodies_from_spec(spec)
        self._t = 0
        self._collisions = []
        self._wall_hits = []
        self._trajectory = np.zeros((self.num_frames, len(self._bodies), 4))
        self._last_obs = self._render()
        return self._last_obs, self._info()

    def step(self, action):
        if self._bodies is None:
            raise RuntimeError("call reset() before step()")
        action = int(action)

        def action_fn(t, bodies):
            if self.probe and action != 0:
                dirs = {1: (1, 0), 2: (0, 1), 3: (-1, 0), 4: (0, -1)}
                dx, dy = dirs[action]
                for b in bodies:
                    if b.is_probe:
                        b.vel = b.vel + np.array([dx, dy]) * (config.PROBE_IMPULSE / b.mass)

        out = simulate.rollout(self._bodies, 1, render_fn=None, action_fn=action_fn)
        t = self._t
        self._trajectory[t] = out["states"][0]
        for c in out["collisions"]:
            self._collisions.append((t, c[1], c[2]))
        for (_, i, ax, s) in out["wall_hits"]:
            self._wall_hits.append((t, i, ax, s))

        self._t += 1
        self._last_obs = self._render()
        truncated = bool(self._t >= self.num_frames)
        info = self._info()
        info.update({
            "frame": self._t - 1,
            "collisions_so_far": len(self._collisions),
            "latest_collision": self._collisions[-1] if self._collisions else None,
            "truncated": truncated,
        })
        return self._last_obs, 0.0, False, truncated, info

    def render(self):
        return self._last_obs

    def close(self):
        self._bodies = None

    # ------------------------------------------------------------ utilities
    @property
    def scene(self):
        """Scene spec (list of dicts) of the current episode."""
        return self._spec

    @property
    def trajectory(self):
        """(T, n, 4) array of (x, y, vx, vy) recorded so far."""
        return self._trajectory

    def extract_events(self):
        return events_mod.extract_events(self._trajectory, self._collisions,
                                         self._wall_hits, n=len(self._bodies))

    def build_questions(self, ev=None, max_questions=8):
        ev = ev if ev is not None else self.extract_events()
        return questions_mod.build_questions(self._spec, ev, self.np_random,
                                             self.num_frames,
                                             max_questions=max_questions)

    # ------------------------------------------------------------ internals
    def _render(self):
        return renderer.render(self._bodies, size=self.frame_size)

    def _info(self):
        return {
            "t": self._t,
            "objects": [b.idx for b in self._bodies],
            "positions": np.array([b.pos for b in self._bodies]),
            "speeds": np.array([b.speed for b in self._bodies]),
        }