| """ |
| Analyze DROID dataset to check: |
| 1. Episode length distribution |
| 2. Percentage with refined extrinsics |
| 3. Generate list of valid episode indices for processing |
| """ |
|
|
| import sys |
| from pathlib import Path |
| sys.path.append(str(Path(__file__).parent.parent)) |
|
|
| import numpy as np |
| import tensorflow as tf |
| tf.config.set_visible_devices([], 'GPU') |
| import tensorflow_datasets as tfds |
| import datetime |
| import re |
| import json |
| from tqdm import tqdm |
|
|
| from utils.load_camera_calibration import CameraCalibrationLoader |
|
|
|
|
| def find_closest_calibration(episode, uuid_list): |
| """Find closest calibration by timestamp.""" |
| try: |
| recording_path = episode['episode_metadata']['recording_folderpath'].numpy().decode('utf-8') |
| match = re.search(r'/([A-Z]+)/success/(\d{4}-\d{2}-\d{2})/\w+_\w+_+\d+_(\d{2}):(\d{2}):(\d{2})_\d{4}/', recording_path) |
| if not match: |
| return None |
| lab, date, hour, minute, second = match.groups() |
| episode_time = datetime.datetime.strptime(f"{date} {hour}:{minute}:{second}", "%Y-%m-%d %H:%M:%S") |
| matching_calibs = [uuid for uuid in uuid_list if uuid.startswith(f"{lab}+") and f"+{date}-" in uuid] |
| if len(matching_calibs) == 0: |
| return None |
| best_uuid = None |
| min_time_diff = float('inf') |
| for calib_uuid in matching_calibs: |
| parts = calib_uuid.split('+') |
| if len(parts) >= 3: |
| time_str = parts[2].replace('_cameras', '') |
| match_time = re.search(r'(\d{2})h-(\d{2})m-(\d{2})s', time_str) |
| if match_time: |
| calib_hour = int(match_time.group(1)) |
| calib_min = int(match_time.group(2)) |
| calib_sec = int(match_time.group(3)) |
| calib_time = datetime.datetime.strptime( |
| f"{date} {calib_hour}:{calib_min}:{calib_sec}", |
| "%Y-%m-%d %H:%M:%S" |
| ) |
| time_diff = abs((episode_time - calib_time).total_seconds()) |
| if time_diff < min_time_diff: |
| min_time_diff = time_diff |
| best_uuid = calib_uuid |
| return best_uuid |
| except: |
| return None |
|
|
|
|
| def main(): |
| print("=" * 80) |
| print("Analyzing DROID Dataset") |
| print("=" * 80) |
|
|
| |
| calib_dir = '/root/workspace/code/wmrl/Dual-Dynamics-Models/DROID-main/vision/u/wenlongh/datasets/droid_v4/cameras' |
| calib_loader = CameraCalibrationLoader(calib_dir) |
| calib_path = Path(calib_dir) |
| uuid_list = [f.stem.replace('_cameras', '') for f in sorted(calib_path.glob("*_cameras.json"))] |
| print(f"Total calibrations: {len(uuid_list)}") |
|
|
| |
| droid_path = '/mnt/kevin/data/droid/droid/1.0.0' |
| builder = tfds.builder_from_directory(droid_path) |
| dataset = builder.as_dataset(split='train') |
|
|
| |
| num_samples = 100 |
| print(f"\nAnalyzing {num_samples} episodes...") |
|
|
| episode_lengths = [] |
| has_refined = [] |
| has_calibration = [] |
| valid_episodes = [] |
|
|
| for episode_idx, episode in tqdm(enumerate(dataset), total=num_samples): |
| if episode_idx >= num_samples: |
| break |
|
|
| |
| length = sum(1 for _ in episode['steps']) |
| episode_lengths.append(length) |
|
|
| |
| uuid = find_closest_calibration(episode, uuid_list) |
| has_calib = uuid is not None |
| has_calibration.append(has_calib) |
|
|
| |
| has_ref = False |
| if uuid: |
| has_ref = calib_loader.has_refined_extrinsics(uuid) |
| has_refined.append(has_ref) |
|
|
| |
| is_valid = has_ref and length <= 400 and length >= 10 |
| if is_valid: |
| valid_episodes.append(episode_idx) |
|
|
| |
| episode_lengths = np.array(episode_lengths) |
|
|
| print("\n" + "=" * 80) |
| print("Episode Length Statistics") |
| print("=" * 80) |
| print(f" Mean length: {episode_lengths.mean():.1f}") |
| print(f" Median length: {np.median(episode_lengths):.1f}") |
| print(f" Min length: {episode_lengths.min()}") |
| print(f" Max length: {episode_lengths.max()}") |
| print(f" Std dev: {episode_lengths.std():.1f}") |
|
|
| print("\n Length distribution:") |
| bins = [0, 50, 100, 150, 200, 250, 300, 350, 400, 500, 1000, 10000] |
| for i in range(len(bins)-1): |
| count = np.sum((episode_lengths >= bins[i]) & (episode_lengths < bins[i+1])) |
| pct = 100 * count / len(episode_lengths) |
| print(f" {bins[i]:4d}-{bins[i+1]:4d}: {count:3d} episodes ({pct:5.1f}%)") |
|
|
| print("\n" + "=" * 80) |
| print("Calibration Statistics") |
| print("=" * 80) |
| num_with_calib = sum(has_calibration) |
| num_with_refined = sum(has_refined) |
| print(f" Episodes with calibration: {num_with_calib}/{num_samples} ({100*num_with_calib/num_samples:.1f}%)") |
| print(f" Episodes with refined extrinsics: {num_with_refined}/{num_samples} ({100*num_with_refined/num_samples:.1f}%)") |
|
|
| print("\n" + "=" * 80) |
| print("Valid Episodes (refined + length <= 400)") |
| print("=" * 80) |
| print(f" Valid episodes: {len(valid_episodes)}/{num_samples} ({100*len(valid_episodes)/num_samples:.1f}%)") |
|
|
| |
| print("\n" + "=" * 80) |
| print("Filter Criteria Analysis") |
| print("=" * 80) |
|
|
| for max_len in [200, 300, 400, 500]: |
| valid_count = sum(1 for i, (ref, length) in enumerate(zip(has_refined, episode_lengths)) |
| if ref and length <= max_len and length >= 10) |
| print(f" Max length {max_len:3d}: {valid_count}/{num_samples} valid ({100*valid_count/num_samples:.1f}%)") |
|
|
| |
| output_file = Path('/tmp/droid_valid_episodes.json') |
| output_data = { |
| 'valid_episodes': valid_episodes, |
| 'num_samples': num_samples, |
| 'max_length': 400, |
| 'min_length': 10, |
| 'requires_refined_extrinsics': True, |
| 'statistics': { |
| 'mean_length': float(episode_lengths.mean()), |
| 'median_length': float(np.median(episode_lengths)), |
| 'pct_with_refined': float(100 * num_with_refined / num_samples) |
| } |
| } |
|
|
| with open(output_file, 'w') as f: |
| json.dump(output_data, f, indent=2) |
|
|
| print(f"\n✓ Valid episode indices saved to: {output_file}") |
|
|
| print("\n" + "=" * 80) |
| print("Recommendation") |
| print("=" * 80) |
| if len(valid_episodes) / num_samples >= 0.5: |
| print(f"✓ Good: {100*len(valid_episodes)/num_samples:.1f}% of episodes are valid") |
| print(f" Filtering with max_length=400 is VIABLE") |
| else: |
| print(f"⚠ Warning: Only {100*len(valid_episodes)/num_samples:.1f}% of episodes are valid") |
| print(f" Consider relaxing constraints or accepting more episodes") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|