UPDATE: new bouncing ball dataset
Browse files
README.md
CHANGED
|
@@ -113,6 +113,10 @@ python /home/lau/sim/DynaTraj/sb3_collect.py \
|
|
| 113 |
--render
|
| 114 |
```
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
Notes:
|
| 117 |
- The script searches checkpoints under `ckpt_root/<domain>/<task>/` as `ckpt-<k>.pt`. If you see an error for `ckpt-0.pt`, switch to 1-based indices.
|
| 118 |
- If your environment has no display backend, simply omit `--render`.
|
|
|
|
| 113 |
--render
|
| 114 |
```
|
| 115 |
|
| 116 |
+
For Bouncing ball:
|
| 117 |
+
python bb_collect.py --trajectories 1024 --steps_per_trajectory 8192
|
| 118 |
+
|
| 119 |
+
|
| 120 |
Notes:
|
| 121 |
- The script searches checkpoints under `ckpt_root/<domain>/<task>/` as `ckpt-<k>.pt`. If you see an error for `ckpt-0.pt`, switch to 1-based indices.
|
| 122 |
- If your environment has no display backend, simply omit `--render`.
|
__pycache__/dataset.cpython-310.pyc
CHANGED
|
Binary files a/__pycache__/dataset.cpython-310.pyc and b/__pycache__/dataset.cpython-310.pyc differ
|
|
|
bb_collect.py
CHANGED
|
@@ -3,8 +3,14 @@ import numpy as np
|
|
| 3 |
import argparse
|
| 4 |
from typing import Optional, Tuple, Dict, Any
|
| 5 |
import time
|
|
|
|
|
|
|
| 6 |
from dataclasses import dataclass
|
| 7 |
from scipy.spatial.transform import Rotation as R
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
@dataclass
|
|
@@ -288,8 +294,8 @@ class PingPongEnv:
|
|
| 288 |
obs = np.concatenate([global_obs, local_obs]) # Total: 33 dimensions
|
| 289 |
|
| 290 |
# Done condition: ball(x,y) out of [100,100] or z lower than board - 0.1m
|
| 291 |
-
done = (abs(ball_pos[0]) >
|
| 292 |
-
abs(ball_pos[1]) >
|
| 293 |
ball_pos[2] < (board_pos[2] - 0.1))
|
| 294 |
|
| 295 |
return obs, done
|
|
@@ -357,6 +363,15 @@ class PingPongDummyController:
|
|
| 357 |
self.target_yaw = 0.0
|
| 358 |
self.last_update_time = 0.0
|
| 359 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
def quat_to_euler(self, quat: np.ndarray) -> np.ndarray:
|
| 361 |
"""
|
| 362 |
Convert quaternion to Euler angles (roll, pitch, yaw).
|
|
@@ -543,46 +558,202 @@ class PingPongDummyController:
|
|
| 543 |
return action
|
| 544 |
|
| 545 |
|
| 546 |
-
def
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
|
| 554 |
-
|
| 555 |
-
config = Config()
|
| 556 |
-
env = PingPongEnv(headless=args.headless, config=config)
|
| 557 |
|
| 558 |
-
|
| 559 |
-
controller = PingPongDummyController(config=config) if args.use_controller else None
|
| 560 |
|
| 561 |
-
|
| 562 |
-
# Reset environment
|
| 563 |
obs = env.reset()
|
| 564 |
-
|
| 565 |
|
| 566 |
-
#
|
| 567 |
-
for step in range(
|
| 568 |
-
# Get
|
| 569 |
-
|
| 570 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
|
| 572 |
-
|
|
|
|
| 573 |
|
| 574 |
-
|
| 575 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 576 |
env.render()
|
| 577 |
-
|
|
|
|
|
|
|
| 578 |
time.sleep(env.model.opt.timestep)
|
| 579 |
-
|
|
|
|
|
|
|
| 580 |
break
|
| 581 |
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
|
| 587 |
|
| 588 |
if __name__ == "__main__":
|
|
|
|
| 3 |
import argparse
|
| 4 |
from typing import Optional, Tuple, Dict, Any
|
| 5 |
import time
|
| 6 |
+
import os
|
| 7 |
+
from datetime import datetime
|
| 8 |
from dataclasses import dataclass
|
| 9 |
from scipy.spatial.transform import Rotation as R
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
import pickle
|
| 12 |
+
|
| 13 |
+
from dataset import TrajectoryBuffer
|
| 14 |
|
| 15 |
|
| 16 |
@dataclass
|
|
|
|
| 294 |
obs = np.concatenate([global_obs, local_obs]) # Total: 33 dimensions
|
| 295 |
|
| 296 |
# Done condition: ball(x,y) out of [100,100] or z lower than board - 0.1m
|
| 297 |
+
done = (abs(ball_pos[0]) > 100.0 or
|
| 298 |
+
abs(ball_pos[1]) > 100.0 or
|
| 299 |
ball_pos[2] < (board_pos[2] - 0.1))
|
| 300 |
|
| 301 |
return obs, done
|
|
|
|
| 363 |
self.target_yaw = 0.0
|
| 364 |
self.last_update_time = 0.0
|
| 365 |
|
| 366 |
+
def reset_controller(self):
|
| 367 |
+
"""Reset controller state for new episode"""
|
| 368 |
+
self.last_update_time = 0.0
|
| 369 |
+
# Optionally reset targets to initial values
|
| 370 |
+
self.target_z = 0.5
|
| 371 |
+
self.target_roll = 0.0
|
| 372 |
+
self.target_pitch = 0.0
|
| 373 |
+
self.target_yaw = 0.0
|
| 374 |
+
|
| 375 |
def quat_to_euler(self, quat: np.ndarray) -> np.ndarray:
|
| 376 |
"""
|
| 377 |
Convert quaternion to Euler angles (roll, pitch, yaw).
|
|
|
|
| 558 |
return action
|
| 559 |
|
| 560 |
|
| 561 |
+
def collect_bouncing_ball_data(
|
| 562 |
+
env: PingPongEnv,
|
| 563 |
+
controller: PingPongDummyController,
|
| 564 |
+
target_trajectories: int,
|
| 565 |
+
steps_per_traj: int,
|
| 566 |
+
render: bool = False,
|
| 567 |
+
realtime: bool = False
|
| 568 |
+
) -> TrajectoryBuffer:
|
| 569 |
+
"""
|
| 570 |
+
Collect trajectory data from bouncing ball environment using ball_response controller.
|
| 571 |
+
|
| 572 |
+
Args:
|
| 573 |
+
env: PingPong environment
|
| 574 |
+
controller: Controller for board movement
|
| 575 |
+
target_trajectories: Number of trajectories to collect
|
| 576 |
+
steps_per_traj: Steps per trajectory
|
| 577 |
+
render: Whether to render during collection
|
| 578 |
+
realtime: Whether to match simulation speed to real time
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
TrajectoryBuffer with collected data
|
| 582 |
+
"""
|
| 583 |
+
buffer = TrajectoryBuffer(steps_per_traj)
|
| 584 |
|
| 585 |
+
pbar = tqdm(total=target_trajectories, desc="Collecting bouncing ball data")
|
|
|
|
|
|
|
| 586 |
|
| 587 |
+
collected_trajs = 0
|
|
|
|
| 588 |
|
| 589 |
+
while collected_trajs < target_trajectories:
|
| 590 |
+
# Reset environment and controller
|
| 591 |
obs = env.reset()
|
| 592 |
+
controller.reset_controller()
|
| 593 |
|
| 594 |
+
# Collect one trajectory
|
| 595 |
+
for step in range(steps_per_traj):
|
| 596 |
+
# Get current observation and done flag
|
| 597 |
+
current_obs, done = env.get_obs()
|
| 598 |
+
|
| 599 |
+
# Get action from ball_response controller
|
| 600 |
+
action = controller.get_ball_response_action(env)
|
| 601 |
+
|
| 602 |
+
# Calculate reward (simple distance-based for now)
|
| 603 |
+
ball_qpos_idx = env.model.jnt_qposadr[mujoco.mj_name2id(env.model, mujoco.mjtObj.mjOBJ_JOINT, "ball_free")]
|
| 604 |
+
board_qpos_idx = env.model.jnt_qposadr[mujoco.mj_name2id(env.model, mujoco.mjtObj.mjOBJ_JOINT, "board_free")]
|
| 605 |
+
ball_pos = env.data.qpos[ball_qpos_idx:ball_qpos_idx+3]
|
| 606 |
+
board_pos = env.data.qpos[board_qpos_idx:board_qpos_idx+3]
|
| 607 |
+
|
| 608 |
+
# Reward based on ball-board distance (encouraging ball to stay near board)
|
| 609 |
+
distance = np.linalg.norm(ball_pos[:2] - board_pos[:2]) # x,y distance only
|
| 610 |
+
reward = -distance # Negative distance as reward
|
| 611 |
+
|
| 612 |
+
# Step environment first to get the next state
|
| 613 |
+
_, _, env_done, _ = env.step(action)
|
| 614 |
|
| 615 |
+
# Get done status after stepping (this is what we want to predict)
|
| 616 |
+
_, done_after_step = env.get_obs()
|
| 617 |
|
| 618 |
+
# Append step to buffer (B=1 for single environment)
|
| 619 |
+
# obs->action->done pattern: observation leads to action, done is result after action
|
| 620 |
+
obs_np = current_obs[None, :] # Add batch dimension
|
| 621 |
+
ext_obs_np = obs_np # Same as obs for this environment
|
| 622 |
+
action_np = action[None, :] # Add batch dimension
|
| 623 |
+
reward_np = np.array([reward], dtype=np.float32)
|
| 624 |
+
done_np = np.array([done_after_step], dtype=np.bool_) # Done status after applying action
|
| 625 |
+
|
| 626 |
+
buffer.append_step(obs_np, ext_obs_np, action_np, reward_np, done_np)
|
| 627 |
+
|
| 628 |
+
# Render if requested
|
| 629 |
+
if render:
|
| 630 |
env.render()
|
| 631 |
+
|
| 632 |
+
# Sleep for realtime if requested
|
| 633 |
+
if realtime:
|
| 634 |
time.sleep(env.model.opt.timestep)
|
| 635 |
+
|
| 636 |
+
# Break if episode is done
|
| 637 |
+
if done_after_step or env_done:
|
| 638 |
break
|
| 639 |
|
| 640 |
+
collected_trajs += 1
|
| 641 |
+
pbar.update(1)
|
| 642 |
+
|
| 643 |
+
pbar.close()
|
| 644 |
+
return buffer
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def parse_data_collection_args():
|
| 648 |
+
"""Parse command line arguments for data collection"""
|
| 649 |
+
parser = argparse.ArgumentParser(description="Collect bouncing ball dataset")
|
| 650 |
+
parser.add_argument("--trajectories", type=int, default=1000, help="Number of trajectories to collect")
|
| 651 |
+
parser.add_argument("--steps_per_trajectory", type=int, default=20000, help="Steps per trajectory")
|
| 652 |
+
parser.add_argument("--out_dir", type=str, default="./dataset/bb/", help="Output directory")
|
| 653 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 654 |
+
parser.add_argument("--headless", action="store_true", help="Run in headless mode (no rendering)")
|
| 655 |
+
|
| 656 |
+
# Demo simulation args for backward compatibility
|
| 657 |
+
parser.add_argument("--realtime", action="store_true", help="Match simulation speed to real time")
|
| 658 |
+
parser.add_argument("--demo", action="store_true", help="Run demo mode instead of data collection")
|
| 659 |
+
|
| 660 |
+
return parser.parse_args()
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
def main():
|
| 664 |
+
args = parse_data_collection_args()
|
| 665 |
+
|
| 666 |
+
# Set random seed
|
| 667 |
+
np.random.seed(args.seed)
|
| 668 |
+
|
| 669 |
+
if args.demo:
|
| 670 |
+
# Demo simulation mode
|
| 671 |
+
# Create configuration and environment
|
| 672 |
+
config = Config()
|
| 673 |
+
env = PingPongEnv(headless=args.headless, config=config)
|
| 674 |
+
controller = PingPongDummyController(config=config)
|
| 675 |
+
|
| 676 |
+
try:
|
| 677 |
+
# Reset environment and controller
|
| 678 |
+
obs = env.reset()
|
| 679 |
+
controller.reset_controller()
|
| 680 |
+
print(f"Initial observation shape: {obs.shape}")
|
| 681 |
+
|
| 682 |
+
# Run simulation for 1000 steps
|
| 683 |
+
for step in range(1000):
|
| 684 |
+
# Get action from ball_response controller
|
| 685 |
+
action = controller.get_ball_response_action(env)
|
| 686 |
+
|
| 687 |
+
obs, reward, done, info = env.step(action)
|
| 688 |
+
|
| 689 |
+
if not args.headless:
|
| 690 |
+
# Render every frame for smooth visualization
|
| 691 |
+
env.render()
|
| 692 |
+
if args.realtime:
|
| 693 |
+
time.sleep(env.model.opt.timestep)
|
| 694 |
+
if done:
|
| 695 |
+
obs = env.reset() # Auto-reset if done
|
| 696 |
+
controller.reset_controller() # Reset controller state
|
| 697 |
+
|
| 698 |
+
print("Demo simulation completed")
|
| 699 |
+
|
| 700 |
+
finally:
|
| 701 |
+
env.close()
|
| 702 |
+
|
| 703 |
+
else:
|
| 704 |
+
# Data collection mode (default)
|
| 705 |
+
print(f"Starting data collection with {args.trajectories} trajectories...")
|
| 706 |
+
|
| 707 |
+
# Create output directory
|
| 708 |
+
os.makedirs(args.out_dir, exist_ok=True)
|
| 709 |
+
|
| 710 |
+
# Create configuration and environment
|
| 711 |
+
config = Config()
|
| 712 |
+
env = PingPongEnv(headless=args.headless, config=config)
|
| 713 |
+
controller = PingPongDummyController(config=config)
|
| 714 |
+
|
| 715 |
+
try:
|
| 716 |
+
# Collect data
|
| 717 |
+
buffer = collect_bouncing_ball_data(
|
| 718 |
+
env=env,
|
| 719 |
+
controller=controller,
|
| 720 |
+
target_trajectories=args.trajectories,
|
| 721 |
+
steps_per_traj=args.steps_per_trajectory,
|
| 722 |
+
render=not args.headless, # Render if not headless
|
| 723 |
+
realtime=args.realtime
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
# Save dataset
|
| 727 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 728 |
+
file_stem = f"bb_ball_response_{timestamp}"
|
| 729 |
+
dataset_path = os.path.join(args.out_dir, f"{file_stem}.npz")
|
| 730 |
+
buffer.save(dataset_path)
|
| 731 |
+
|
| 732 |
+
# Save metadata
|
| 733 |
+
meta = {
|
| 734 |
+
"environment": "bouncing_ball",
|
| 735 |
+
"control_mode": "ball_response",
|
| 736 |
+
"trajectories": args.trajectories,
|
| 737 |
+
"steps_per_trajectory": args.steps_per_trajectory,
|
| 738 |
+
"total_trajectories": len(buffer),
|
| 739 |
+
"total_steps": len(buffer) * args.steps_per_trajectory,
|
| 740 |
+
"seed": args.seed,
|
| 741 |
+
"config": config,
|
| 742 |
+
"timestamp": timestamp,
|
| 743 |
+
"headless": args.headless
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
metadata_path = os.path.join(args.out_dir, f"{file_stem}_metadata.pkl")
|
| 747 |
+
with open(metadata_path, "wb") as f:
|
| 748 |
+
pickle.dump(meta, f)
|
| 749 |
+
|
| 750 |
+
print(f"[INFO] Data collection completed!")
|
| 751 |
+
print(f"[INFO] Dataset saved: {dataset_path}")
|
| 752 |
+
print(f"[INFO] Metadata saved: {metadata_path}")
|
| 753 |
+
print(f"[INFO] Collected {len(buffer)} trajectories")
|
| 754 |
+
|
| 755 |
+
finally:
|
| 756 |
+
env.close()
|
| 757 |
|
| 758 |
|
| 759 |
if __name__ == "__main__":
|
dataset/bb/bb_ball_response_2025-09-19_15-43-14.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab7afe6b73f56bf76eda4e5bdf73cb7aff3654e13403df3c530858debf54ab11
|
| 3 |
+
size 2820321076
|
dataset/bb/bb_ball_response_2025-09-19_15-43-14_metadata.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:80bb8de135d7e54e43c989d37b8218b291fd9fd513b6ecd2362a3540d8b4ffb6
|
| 3 |
+
size 781
|