File size: 12,996 Bytes
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
125390d
f4b39a7
 
125390d
 
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125390d
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
 
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
125390d
 
 
 
 
 
 
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
75a9975
f4b39a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import argparse
import os
import time
from dataclasses import dataclass
from datetime import datetime
from typing import List, Tuple

import mujoco
import numpy as np
from tqdm import tqdm

from dataset import TrajectoryBuffer


@dataclass
class Config:
    """Configuration for the multi-ball-in-bottle environment."""

    num_balls: int = 4
    bottle_length: float = 0.10  # x dimension (m)
    bottle_width: float = 0.10  # y dimension (m)
    bottle_height: float = 0.50  # z dimension (m)
    wall_thickness: float = 0.005
    ball_radius: float = 0.01
    ball_mass: float = 0.003
    timestep: float = 0.001

    # Initialization ranges
    min_z: float = 0.4
    max_z: float = 0.5
    max_xy_speed: float = 0.30  # m/s

    # Rendering
    render_width: int = 640
    render_height: int = 480


class BottleMultiBallEnv:
    """Four free-falling balls inside an open-top square bottle."""

    def __init__(self, headless: bool = True, config: Config | None = None, seed: int = 0):
        self.config = config or Config()
        self.headless = headless
        self.rng = np.random.RandomState(seed)
        self.model = mujoco.MjModel.from_xml_string(self._build_xml())
        self.data = mujoco.MjData(self.model)
        self.viewer = None
        self.renderer = None
        self.cam_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_CAMERA, "bottle_cam")
        if not self.headless:
            try:
                import mujoco.viewer as mj_viewer  # type: ignore

                self.viewer = mj_viewer.launch_passive(self.model, self.data)
            except Exception:
                # Fallback to offscreen renderer; requires a valid GL context to show frames
                self.renderer = mujoco.Renderer(
                    self.model, width=self.config.render_width, height=self.config.render_height
                )

        # Cache indices for qpos/qvel blocks of each ball
        self.ball_qpos_idx = []
        self.ball_qvel_idx = []
        for i in range(1, self.config.num_balls + 1):
            name = f"ball{i}_free"
            self.ball_qpos_idx.append(
                self.model.jnt_qposadr[mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_JOINT, name)]
            )
            self.ball_qvel_idx.append(
                self.model.jnt_dofadr[mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_JOINT, name)]
            )

    def _build_xml(self) -> str:
        c = self.config
        half_len = c.bottle_length / 2
        half_wid = c.bottle_width / 2
        t = c.wall_thickness
        h = c.bottle_height
        ball_rad = c.ball_radius
        return f"""
        <mujoco model="multi_ball_bottle">
            <compiler angle="radian" coordinate="local"/>
            <option timestep="{c.timestep}"/>
            <default>
                <geom 
                    solref="0.01 0.10"
                    friction="1.5 0.001 0.001"
                    condim="6"
                />
            </default>
            <worldbody>
                <light name="light" pos="0 0 {h}" dir="0 0 -1"/>
                <!-- Floor -->
                <geom name="floor" type="plane" pos="0 0 0" size="1 1 0.01" rgba="0.8 0.8 0.8 1"/>
                <!-- Walls -->
                <geom name="wall_xp" type="box" pos="{half_len + t/2} 0 {h/2}" size="{t/2} {half_wid} {h/2}" rgba="0.7 0.7 0.7 1"/>
                <geom name="wall_xn" type="box" pos="-{half_len + t/2} 0 {h/2}" size="{t/2} {half_wid} {h/2}" rgba="0.7 0.7 0.7 1"/>
                <geom name="wall_yp" type="box" pos="0 {half_wid + t/2} {h/2}" size="{half_len} {t/2} {h/2}" rgba="0.7 0.7 0.7 1"/>
                <geom name="wall_yn" type="box" pos="0 -{half_wid + t/2} {h/2}" size="{half_len} {t/2} {h/2}" rgba="0.7 0.7 0.7 1"/>
                <!-- Balls (each as a root body because free joints must be root-level) -->
                {"".join([self._ball_body_xml(i, ball_rad) for i in range(1, self.config.num_balls + 1)])}
                <camera name="bottle_cam" pos="0 0 {h}" quat="0 -1 0 0" fovy="60"/>
            </worldbody>
            <asset>
                <texture type="skybox" builtin="gradient" rgb1=".4 .5 .6" rgb2="0 0 0" width="64" height="64"/>
                <material name="ball_mat" rgba="0.9 0.4 0.2 1"/>
            </asset>
            <visual>
                <map force="0.1"/>
                <quality shadowsize="2048"/>
            </visual>
        </mujoco>
        """

    def _ball_body_xml(self, idx: int, radius: float) -> str:
        return f"""
        <body name="ball{idx}" pos="0 0 0">
            <joint name="ball{idx}_free" type="free"/>
            <geom name="ball{idx}_geom" type="sphere" size="{radius}" mass="{self.config.ball_mass}" material="ball_mat" friction="1.5 0.001 0.001"/>
        </body>
        """

    def reset(self) -> Tuple[np.ndarray, bool]:
        mujoco.mj_resetData(self.model, self.data)
        positions = self._sample_initial_positions()
        velocities = self._sample_initial_velocities()

        for i in range(self.config.num_balls):
            qpos_idx = self.ball_qpos_idx[i]
            qvel_idx = self.ball_qvel_idx[i]
            pos = positions[i]
            vel = velocities[i]
            self.data.qpos[qpos_idx : qpos_idx + 3] = pos
            # quaternion wxyz = [1, 0, 0, 0]
            self.data.qpos[qpos_idx + 3 : qpos_idx + 7] = np.array([1.0, 0.0, 0.0, 0.0])
            self.data.qvel[qvel_idx : qvel_idx + 3] = vel
            self.data.qvel[qvel_idx + 3 : qvel_idx + 6] = np.zeros(3)

        mujoco.mj_forward(self.model, self.data)
        return self.get_obs()

    def _sample_initial_positions(self) -> np.ndarray:
        c = self.config
        positions = []
        margin = c.ball_radius * 2.5
        tries = 0
        while len(positions) < c.num_balls:
            x = self.rng.uniform(-c.bottle_length / 2 + margin, c.bottle_length / 2 - margin)
            y = self.rng.uniform(-c.bottle_width / 2 + margin, c.bottle_width / 2 - margin)
            z = self.rng.uniform(c.min_z, c.max_z)
            candidate = np.array([x, y, z], dtype=np.float64)
            if all(np.linalg.norm(candidate[:2] - p[:2]) > c.ball_radius * 2 for p in positions):
                positions.append(candidate)
            tries += 1
            if tries > 1000:  # fallback to avoid infinite loop
                positions.append(candidate)
        return np.stack(positions, axis=0)

    def _sample_initial_velocities(self) -> np.ndarray:
        c = self.config
        speeds = self.rng.uniform(0.0, c.max_xy_speed, size=(c.num_balls,))
        angles = self.rng.uniform(0.0, 2 * np.pi, size=(c.num_balls,))
        vx = speeds * np.cos(angles)
        vy = speeds * np.sin(angles)
        vz = np.zeros_like(vx)
        return np.stack([vx, vy, vz], axis=1)

    def step(self):
        mujoco.mj_step(self.model, self.data)
        return self.get_obs()

    def get_obs(self) -> Tuple[np.ndarray, bool]:
        # Collect positions and velocities for four balls
        pos_list: List[np.ndarray] = []
        vel_list: List[np.ndarray] = []
        for i in range(self.config.num_balls):
            qpos_idx = self.ball_qpos_idx[i]
            qvel_idx = self.ball_qvel_idx[i]
            pos_list.append(self.data.qpos[qpos_idx : qpos_idx + 3].copy())
            vel_list.append(self.data.qvel[qvel_idx : qvel_idx + 3].copy())
        positions = np.stack(pos_list, axis=0)
        velocities = np.stack(vel_list, axis=0)

        timestamp = np.array([self.data.time], dtype=np.float32)
        obs = np.concatenate([positions.reshape(-1), velocities.reshape(-1), timestamp]).astype(np.float32)

        done = self._check_done(positions)
        return obs, done

    def _check_done(self, positions: np.ndarray) -> bool:
        c = self.config
        half_len = c.bottle_length / 2
        half_wid = c.bottle_width / 2
        if np.any(positions[:, 2] < 0.0):
            return True
        if np.any(np.abs(positions[:, 0]) > half_len) or np.any(np.abs(positions[:, 1]) > half_wid):
            return True
        return False

    def render(self):
        if self.viewer is not None:
            self.viewer.sync()
            return None
        if self.renderer is not None:
            self.renderer.update_scene(self.data, camera=self.cam_id)
            return self.renderer.render()
        return None

    def close(self):
        if self.viewer is not None:
            try:
                self.viewer.close()
            except Exception:
                pass
        if self.renderer is not None:
            self.renderer.free()


def collect_multi_ball_data(
    env: BottleMultiBallEnv,
    target_trajectories: int,
    steps_per_traj: int,
    render: bool = False,
    realtime: bool = False,
) -> TrajectoryBuffer:
    record_stride = 5  # record once every 5 env steps
    buffer = TrajectoryBuffer(steps_per_traj)
    pbar = tqdm(total=target_trajectories, desc="Collecting multi-ball data")

    for _ in range(target_trajectories):
        obs, done = env.reset()
        recorded = 0
        for step_idx in range(steps_per_traj * record_stride):
            if step_idx % record_stride == 0:
                obs_np = obs[None, :]
                ext_obs_np = obs_np
                action_np = np.zeros((1, 1), dtype=np.float32)  # placeholder action
                reward_np = np.zeros((1,), dtype=np.float32)
                done_np = np.array([done], dtype=np.bool_)
                buffer.append_step(obs_np, ext_obs_np, action_np, reward_np, done_np)
                recorded += 1
                if recorded >= steps_per_traj:
                    break

            obs, done = env.step()

            if render:
                env.render()
            if realtime:
                time.sleep(env.model.opt.timestep)
            if done:
                break

        pbar.update(1)

    pbar.close()
    return buffer


def parse_args():
    parser = argparse.ArgumentParser(description="Collect multi-ball contact-rich dataset inside a bottle.")
    parser.add_argument("--trajectories", type=int, default=1024, help="Number of trajectories to collect")
    parser.add_argument("--steps_per_trajectory", type=int, default=8192, help="Steps per trajectory")
    parser.add_argument("--out_dir", type=str, default="./dataset/multi_bb/", help="Output directory")
    parser.add_argument("--seed", type=int, default=42, help="Random seed")
    parser.add_argument("--headless", action="store_true", help="Disable on-screen rendering")
    parser.add_argument("--realtime", action="store_true", help="Sleep to match real time")
    parser.add_argument("--demo", action="store_true", help="Run a short demo instead of full collection")
    parser.add_argument("--num_balls", type=int, default=2, help="Number of balls in the bottle")
    return parser.parse_args()


def main():
    args = parse_args()
    np.random.seed(args.seed)

    config = Config(num_balls=args.num_balls)
    env = BottleMultiBallEnv(headless=args.headless, config=config, seed=args.seed)

    try:
        if args.demo:
            obs, _ = env.reset()
            print(f"Initial obs shape: {obs.shape}")
            for _ in range(500):
                obs, done = env.step()
                if not args.headless:
                    env.render()
                if args.realtime:
                    time.sleep(env.model.opt.timestep)
                if done:
                    obs, _ = env.reset()
        else:
            os.makedirs(args.out_dir, exist_ok=True)
            buffer = collect_multi_ball_data(
                env=env,
                target_trajectories=args.trajectories,
                steps_per_traj=args.steps_per_trajectory,
                render=not args.headless,
                realtime=args.realtime,
            )
            timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
            file_stem = f"multi_bb_{timestamp}"
            dataset_path = os.path.join(args.out_dir, f"{file_stem}.npz")
            buffer.save(dataset_path)

            meta = {
                "environment": "multi_ball_bottle",
                "trajectories": args.trajectories,
                "steps_per_trajectory": args.steps_per_trajectory,
                "total_trajectories": len(buffer),
                "total_steps": len(buffer) * args.steps_per_trajectory,
                "seed": args.seed,
                "config": config.__dict__,
                "timestamp": timestamp,
                "headless": args.headless,
            }
            import pickle

            metadata_path = os.path.join(args.out_dir, f"{file_stem}_metadata.pkl")
            with open(metadata_path, "wb") as f:
                pickle.dump(meta, f)

            print(f"[INFO] Dataset saved: {dataset_path}")
            print(f"[INFO] Metadata saved: {metadata_path}")
            print(f"[INFO] Collected {len(buffer)} trajectories")
    finally:
        env.close()


if __name__ == "__main__":
    main()