File size: 10,146 Bytes
1bfcdaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -------------------------------------------------------------------
# scripts/data/build_lmdb.py
# -------------------------------------------------------------------
"""
Build LMDB databases for VAE/KPP training.

This script samples point clouds in a low-memory mode, performs normalization, and writes
train/val splits to LMDB for efficient training I/O.
"""
import sys
import os
import argparse
import json
import torch
import numpy as np
import trimesh
from torch.utils.data import Dataset, random_split, Subset

# Ensure the repository root is importable
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))

# Import the GAPartNet loader.
from dragmesh.data.data_loader_v2 import GAPartNetLoaderV2
from dragmesh.data.balanced_dataset_utils import build_vae_lmdb
from dragmesh.utils.kpp_normalization import bbox_center_scale, normalize_points, normalize_vector

class SmartProcessingDataset(Dataset):
    """
    Smart processing dataset:
    1) Category-based filtering (config-driven)
    2) Uses the GAPartNet loader
    3) Filtering based on motion magnitude
    4) Normalization and point sampling
    """
    def __init__(self, root, categories=None, num_frames=16, num_points=4096, joint_selection: str = "largest_motion"):
        print(f"Initializing Loader from: {root}")
        self.loader = GAPartNetLoaderV2(root)
        self.num_frames = num_frames
        self.num_points = num_points
        self.joint_selection = joint_selection
        
        # === 1) Category-based filtering ===
        if categories:
            print(f"Filtering for {len(categories)} categories...")
            self.valid_indices = []
            for i, obj_path in enumerate(self.loader.object_list):
                # Check meta.json for category labels.
                meta_path = os.path.join(obj_path, "meta.json")
                if os.path.exists(meta_path):
                    try:
                        with open(meta_path, 'r') as f:
                            meta = json.load(f)
                            if meta.get('model_cat') in categories:
                                self.valid_indices.append(i)
                    except:
                        pass
            print(f"Found {len(self.valid_indices)} objects matching categories.")
        else:
            self.valid_indices = list(range(len(self.loader.object_list)))
            
    def __len__(self):
        return len(self.valid_indices)

    def __getitem__(self, idx):
        # Map back to the loader's global object index.
        real_idx = self.valid_indices[idx]
        
        try:
            # 1) Fetch a raw sample from the loader.
            raw = self.loader.generate_training_sample(
                real_idx,
                self.num_frames,
                joint_selection=self.joint_selection,
                return_mesh=False,          # key: low-memory point-cloud mode (avoid mesh concat OOM)
                num_points=self.num_points  # sample points inside the loader
            )
            
            # 2) Motion-based filtering.
            joint_type = raw['joint_type']
            is_valid = False
            
            if joint_type in ['revolute', 'continuous']:
                # Check rotation magnitude via quaternion angle difference (first vs last frame).
                q_s, q_e = raw['qr_sequence'][0], raw['qr_sequence'][-1]
                dot = np.abs(np.dot(q_s, q_e))
                angle_diff = 2 * np.arccos(np.clip(dot, -1, 1))
                # Threshold: > ~17 degrees (~0.3 rad).
                if angle_diff > 0.3: 
                    is_valid = True
            
            elif joint_type == 'prismatic':
                # Check translation distance.
                traj = raw['drag_trajectory']
                dist = np.linalg.norm(traj[-1] - traj[0])
                if dist > 0.1: 
                    is_valid = True
            
            if not is_valid: 
                return None  # tell build_vae_lmdb to skip this sample
            
            # 3) === Normalization (points already sampled by the loader) ===
            # KPP predicts the origin in the normalized point-cloud frame.  This
            # frame must be available at inference, so center on the object bbox,
            # not the GT joint origin.
            points = raw['initial_mesh']  # [N,3] ndarray

            # Compute scale: prefer loader-provided bounds; otherwise use point-cloud bounds.
            if 'bounds_min' in raw and 'bounds_max' in raw:
                bmin = raw['bounds_min']
                bmax = raw['bounds_max']
            else:
                bmin = points.min(axis=0)
                bmax = points.max(axis=0)
            center, scale = bbox_center_scale(bmin, bmax)

            points = normalize_points(points, center, scale)

            # 4) Part mask is already point-level (0=static, 1=movable).
            p_mask = raw['part_mask'].astype(np.int32)

            # 5) Pack output dict
            out = {
                'initial_mesh': points.astype(np.float32, copy=False),
                'drag_point': normalize_points(raw['drag_point'], center, scale),
                'drag_vector': normalize_vector(raw['drag_vector'], scale),
                'qr_gt': raw['qr_sequence'].astype(np.float32),
                'qd_gt': (raw['qd_sequence'] / scale).astype(np.float32),
                'joint_type': 0 if joint_type in ['revolute', 'continuous'] else 1,
                'joint_axis': raw['joint_axis'].astype(np.float32),
                'joint_origin': normalize_points(raw['joint_origin'], center, scale),
                'part_mask': p_mask.astype(np.float32),
                'norm_center': center.astype(np.float32),
                'norm_scale': np.array(scale, dtype=np.float32),
                'origin_normalization_version': np.array(1, dtype=np.int64),
                
                # Extra fields (used by loss/augmentation)
                'rotation_direction': raw['rotation_direction'].astype(np.float32),
                'trajectory_vectors': (raw['trajectory_vectors'] / scale).astype(np.float32),
                'drag_trajectory': normalize_points(raw['drag_trajectory'], center, scale)
            }
            return out

        except Exception as e:
            # print(f"Skip sample {real_idx}: {e}")
            return None

def main(args):
    print("\n" + "="*70)
    print("BUILDING LMDB DATABASES (IN-CATEGORY VALIDATION ONLY)")
    print("With motion-based filtering and low-memory point sampling")
    print("="*70)

    # 1) Load configuration.
    print(f"Loading config: {args.config}")
    with open(args.config, 'r') as f:
        config = json.load(f)

    # Load train_categories only.
    train_categories = config['train_categories'] 
    val_in_config = config.get('val_in_category', {})
    val_split_ratio = val_in_config.get('split_ratio', 0.1)
    seed = val_in_config.get('random_seed', 42)

    print(f"Total categories: {len(train_categories)}")
    print(f"Val split ratio: {val_split_ratio}")

    # 2) Initialize smart dataset (includes filtering in __getitem__).
    # Note: we do not use FixedDragMeshDatasetV2 here; we use SmartProcessingDataset to avoid
    # unnecessary work performed during dataset initialization.
    print("\nInitializing Smart Dataset...")
    full_dataset = SmartProcessingDataset(
        root=args.dataset_root,
        categories=train_categories,
        num_frames=args.num_frames,
        num_points=args.num_points,
        joint_selection=args.joint_selection
    )
    
    # 3) Note: len(full_dataset) counts objects matching categories; the number of valid samples is
    # determined during LMDB build because __getitem__ may return None.
    print(f"Found {len(full_dataset)} matching objects (filtering happens during build).")

    # 4) Split into train/val objects.
    val_size = int(len(full_dataset) * val_split_ratio)
    train_size = len(full_dataset) - val_size

    print(f"\nSplitting into {train_size} (Train) and {val_size} (Val) objects.")
    
    train_subset, val_subset = random_split(
        full_dataset,
        [train_size, val_size],
        generator=torch.Generator().manual_seed(seed)
    )

    # 5) Build training LMDB.
    output_path_train = args.output_prefix + "_train.lmdb"
    print(f"\nBuilding TRAINING LMDB...")
    build_vae_lmdb(
        dataset=train_subset, 
        output_path=output_path_train,
        categories=train_categories, 
        num_frames=args.num_frames,
        num_points=args.num_points
    )

    # 6) Build validation LMDB.
    output_path_val = args.output_prefix + "_val.lmdb"
    print(f"\nBuilding VALIDATION LMDB...")
    build_vae_lmdb(
        dataset=val_subset, 
        output_path=output_path_val,
        categories=train_categories, 
        num_frames=args.num_frames,
        num_points=args.num_points
    )

    print("\n" + "="*70)
    print("LMDB BUILD COMPLETE!")
    print(f"Train Output: {output_path_train}")
    print(f"Val Output:   {output_path_val}")
    print("="*70 + "\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Build VAE LMDB")
    parser.add_argument('--dataset_root', type=str, required=True,
                        help='Root directory of dataset')
    parser.add_argument('--output_prefix', type=str, required=True,
                        help='Prefix for output LMDBs')
    parser.add_argument('--config', type=str,
                        default='configs/category_split_v2.json',
                        help='Category split configuration')
    parser.add_argument('--num_frames', type=int, default=16,
                        help='Number of trajectory frames')
    parser.add_argument('--num_points', type=int, default=4096,
                        help='Number of points to sample')
    parser.add_argument(
        '--joint_selection',
        type=str,
        default='largest_motion',
        choices=['largest_motion', 'random', 'first'],
        help='How to choose the joint for each object when generating samples'
    )
    args = parser.parse_args()
    main(args)