hang commited on
Commit
1f86ebf
·
1 Parent(s): 3fbec94

UPDATE: longer episode without termination

Browse files
Files changed (21) hide show
  1. __pycache__/dataset.cpython-310.pyc +0 -0
  2. dataset.py +27 -0
  3. dataset/load_npz.py +672 -0
  4. dataset/{sb3_cheetah_run_ckpt001_2025-08-18_23-31-33.npz → sb3_cheetah_run_ckpt001_2025-08-28_19-39-53.npz} +2 -2
  5. dataset/{sb3_cheetah_run_ckpt001_2025-08-18_23-31-33_metadata.pkl → sb3_cheetah_run_ckpt001_2025-08-28_19-39-53_metadata.pkl} +0 -0
  6. dataset/sb3_cheetah_run_ckpt020_2025-08-28_17-35-15.npz +0 -3
  7. dataset/{sb3_cheetah_run_ckpt001_2025-08-28_16-46-27.npz → sb3_cheetah_run_ckpt020_2025-08-28_19-42-44.npz} +2 -2
  8. dataset/{sb3_cheetah_run_ckpt020_2025-08-18_23-36-48_metadata.pkl → sb3_cheetah_run_ckpt020_2025-08-28_19-42-44_metadata.pkl} +0 -0
  9. dataset/sb3_cheetah_run_ckpt030_2025-08-18_23-40-31.npz +0 -3
  10. dataset/sb3_cheetah_run_ckpt030_2025-08-28_17-38-32.npz +0 -3
  11. dataset/{sb3_cheetah_run_ckpt020_2025-08-18_23-36-48.npz → sb3_cheetah_run_ckpt030_2025-08-28_19-49-33.npz} +2 -2
  12. dataset/{sb3_cheetah_run_ckpt030_2025-08-18_23-40-31_metadata.pkl → sb3_cheetah_run_ckpt030_2025-08-28_19-49-33_metadata.pkl} +0 -0
  13. dataset/sb3_cheetah_run_ckpt050_2025-08-18_23-43-50.npz +0 -3
  14. dataset/sb3_cheetah_run_ckpt050_2025-08-28_17-41-11.npz +0 -3
  15. dataset/sb3_cheetah_run_ckpt050_2025-08-28_17-41-11_metadata.pkl +0 -3
  16. dataset/sb3_cheetah_run_ckpt050_2025-08-28_20-11-25.npz +3 -0
  17. dataset/{sb3_cheetah_run_ckpt050_2025-08-18_23-43-50_metadata.pkl → sb3_cheetah_run_ckpt050_2025-08-28_20-11-25_metadata.pkl} +0 -0
  18. dataset/sb3_cheetah_run_ckpt020_2025-08-28_17-35-15_metadata.pkl → sb3_cheetah_run_ckpt001_2025-08-28_19-35-01_trajectory_0.png +2 -2
  19. dataset/sb3_cheetah_run_ckpt030_2025-08-28_17-38-32_metadata.pkl → sb3_cheetah_run_ckpt001_2025-08-28_19-39-53_trajectory_0.png +2 -2
  20. dataset/sb3_cheetah_run_ckpt001_2025-08-28_16-46-27_metadata.pkl → sb3_cheetah_run_ckpt020_2025-08-28_19-42-44_trajectory_0.png +2 -2
  21. sb3_collect.py +1 -1
__pycache__/dataset.cpython-310.pyc CHANGED
Binary files a/__pycache__/dataset.cpython-310.pyc and b/__pycache__/dataset.cpython-310.pyc differ
 
dataset.py CHANGED
@@ -35,7 +35,34 @@ class TrajectoryBuffer:
35
  self.traj_pool[k].append(traj_segment)
36
  lst.clear()
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def finalize(self):
 
 
39
  return {k: np.stack(v, axis=0) for k, v in self.traj_pool.items()}
40
 
41
  def save(self, path):
 
35
  self.traj_pool[k].append(traj_segment)
36
  lst.clear()
37
 
38
+ def force_complete_trajectory(self):
39
+ """Force completion of current trajectory by padding with the last step"""
40
+ if len(self.buffers["obs"]) > 0:
41
+ # Get the last step data
42
+ last_obs = self.buffers["obs"][-1].copy()
43
+ last_ext_obs = self.buffers["ext_obs"][-1].copy()
44
+ last_action = self.buffers["action"][-1].copy()
45
+ last_reward = np.zeros_like(self.buffers["reward"][-1]) # Zero reward for padding
46
+ last_done = np.ones_like(self.buffers["done"][-1], dtype=np.bool_) # Mark as done
47
+
48
+ # Pad until we complete the trajectory
49
+ while self.step_idx % self.traj_steps != 0:
50
+ self.buffers["obs"].append(last_obs.copy())
51
+ self.buffers["ext_obs"].append(last_ext_obs.copy())
52
+ self.buffers["action"].append(last_action.copy())
53
+ self.buffers["reward"].append(last_reward.copy())
54
+ self.buffers["done"].append(last_done.copy())
55
+ self.step_idx += 1
56
+
57
+ # Now complete the trajectory
58
+ for k, lst in self.buffers.items():
59
+ traj_segment = np.stack(lst, axis=1)
60
+ self.traj_pool[k].append(traj_segment)
61
+ lst.clear()
62
+
63
  def finalize(self):
64
+ # Complete any remaining partial trajectory
65
+ self.force_complete_trajectory()
66
  return {k: np.stack(v, axis=0) for k, v in self.traj_pool.items()}
67
 
68
  def save(self, path):
dataset/load_npz.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Load .npz files and display variable names and dimensions
4
+ """
5
+
6
+ import numpy as np
7
+ import os
8
+ import glob
9
+ import argparse
10
+ import sys
11
+ from pathlib import Path
12
+ import matplotlib.pyplot as plt
13
+
14
+
15
+ def load_npz_info(npz_file_path):
16
+ """
17
+ Load .npz file and display information about all variables
18
+
19
+ Args:
20
+ npz_file_path (str): Path to .npz file
21
+ """
22
+ print(f"\n{'='*60}")
23
+ print(f"File: {os.path.basename(npz_file_path)}")
24
+ print(f"{'='*60}")
25
+
26
+ try:
27
+ # Load .npz file
28
+ data = np.load(npz_file_path)
29
+
30
+ # Display all variable names in the file
31
+ print(f"Total variables: {len(data.files)}")
32
+ print(f"Variable names: {data.files}")
33
+ print("\nDetailed information:")
34
+ print("-" * 60)
35
+
36
+ # Iterate through each variable and display detailed information
37
+ for i, var_name in enumerate(data.files, 1):
38
+ var_data = data[var_name]
39
+ print(f"{i:2d}. Variable name: {var_name}")
40
+ print(f" Data type: {var_data.dtype}")
41
+ print(f" Shape (dimensions): {var_data.shape}")
42
+ print(f" Total elements: {var_data.size}")
43
+
44
+ # If numeric type, display some statistics
45
+ if np.issubdtype(var_data.dtype, np.number):
46
+ if var_data.size > 0:
47
+ print(f" Value range: [{np.min(var_data):.4f}, {np.max(var_data):.4f}]")
48
+ print(f" Mean: {np.mean(var_data):.4f}")
49
+ print(f" Std dev: {np.std(var_data):.4f}")
50
+
51
+ # Display first few elements (if array is not too large)
52
+ if var_data.size <= 10:
53
+ print(f" Data content: {var_data}")
54
+ elif len(var_data.shape) == 1:
55
+ print(f" First 5 elements: {var_data[:5]}")
56
+ elif len(var_data.shape) == 2:
57
+ print(f" First 3x3 elements:")
58
+ print(f" {var_data[:3, :3]}")
59
+
60
+ print()
61
+
62
+ # Close file
63
+ data.close()
64
+
65
+ except Exception as e:
66
+ print(f"Error: Unable to load file {npz_file_path}")
67
+ print(f"Error message: {str(e)}")
68
+
69
+
70
+ def load_all_npz_in_directory(directory_path=None):
71
+ """
72
+ Load information from all .npz files in directory
73
+
74
+ Args:
75
+ directory_path (str): Directory path, defaults to current directory
76
+ """
77
+ if directory_path is None:
78
+ directory_path = os.getcwd()
79
+
80
+ # Find all .npz files
81
+ npz_files = glob.glob(os.path.join(directory_path, "*.npz"))
82
+
83
+ if not npz_files:
84
+ print(f"No .npz files found in directory {directory_path}")
85
+ return
86
+
87
+ print(f"Found {len(npz_files)} .npz files in directory {directory_path}")
88
+
89
+ # Sort filenames
90
+ npz_files.sort()
91
+
92
+ # Process files one by one
93
+ for npz_file in npz_files:
94
+ load_npz_info(npz_file)
95
+
96
+
97
+ def load_specific_npz(file_path):
98
+ """
99
+ Load specific .npz file
100
+
101
+ Args:
102
+ file_path (str): File path
103
+
104
+ Returns:
105
+ dict: Dictionary containing all variables
106
+ """
107
+ try:
108
+ data = np.load(file_path)
109
+ result = {}
110
+
111
+ print(f"Loading file: {os.path.basename(file_path)}")
112
+ print(f"Contains variables: {data.files}")
113
+
114
+ # Store all variables in dictionary
115
+ for var_name in data.files:
116
+ result[var_name] = data[var_name]
117
+ print(f" {var_name}: {data[var_name].shape} {data[var_name].dtype}")
118
+
119
+ return result
120
+
121
+ except Exception as e:
122
+ print(f"Error: Unable to load file {file_path}")
123
+ print(f"Error message: {str(e)}")
124
+ return None
125
+
126
+
127
+ def load_npz_simple(npz_file_path):
128
+ """
129
+ Load .npz file and display only basic information (variable names and shapes)
130
+
131
+ Args:
132
+ npz_file_path (str): Path to .npz file
133
+ """
134
+ try:
135
+ data = np.load(npz_file_path)
136
+
137
+ print(f"\nFile: {os.path.basename(npz_file_path)}")
138
+ print(f"Variables ({len(data.files)}):")
139
+
140
+ for var_name in data.files:
141
+ var_data = data[var_name]
142
+ print(f" {var_name}: {var_data.shape} ({var_data.dtype})")
143
+
144
+ data.close()
145
+
146
+ except Exception as e:
147
+ print(f"Error loading {npz_file_path}: {str(e)}")
148
+
149
+
150
+ def extract_trajectories_from_npz(npz_file_path, output_file_path=None):
151
+ """
152
+ Extract individual trajectories from NPZ data based on 'done' signal.
153
+ Split trajectories at done=True points and pad with NaN to equal length.
154
+
155
+ Args:
156
+ npz_file_path (str): Path to input .npz file
157
+ output_file_path (str): Path to save processed data (optional)
158
+
159
+ Returns:
160
+ dict: Dictionary containing processed trajectory data
161
+ """
162
+ try:
163
+ # Load original data
164
+ data = np.load(npz_file_path)
165
+ print(f"Loading data from: {os.path.basename(npz_file_path)}")
166
+
167
+ # Check if 'done' variable exists
168
+ if 'done' not in data.files:
169
+ print("Error: 'done' variable not found in the data")
170
+ return None
171
+
172
+ done = data['done'] # Shape: (1024, 1, 512)
173
+ batch_size, env_num, seq_len = done.shape
174
+
175
+ print(f"Original data shape: batch_size={batch_size}, env_num={env_num}, seq_len={seq_len}")
176
+
177
+ # Display done signal statistics for each batch
178
+ print(f"\nDone signal statistics per batch:")
179
+ print("-" * 40)
180
+
181
+ print(np.squeeze(done).sum(1)[1:200])
182
+ print(np.squeeze(done).sum())
183
+
184
+ return
185
+ done_per_batch = np.sum(done, axis=(1, 2)) # Sum over env and sequence dimensions
186
+ for batch_idx in range(min(1000, batch_size)): # Show first 20 batches
187
+ print(f"Batch {batch_idx:3d}: {done_per_batch[batch_idx]:3d} done signals")
188
+
189
+ if batch_size > 20:
190
+ print(f"... (showing first 20 out of {batch_size} batches)")
191
+
192
+ print(f"\nOverall done statistics:")
193
+ print(f" Total done signals: {np.sum(done)}")
194
+ print(f" Average per batch: {np.mean(done_per_batch):.2f}")
195
+ print(f" Min per batch: {np.min(done_per_batch)}")
196
+ print(f" Max per batch: {np.max(done_per_batch)}")
197
+
198
+ # Find all trajectory endpoints (where done=True)
199
+ trajectories = []
200
+
201
+ for batch_idx in range(batch_size):
202
+ for env_idx in range(env_num):
203
+ # Get done flags for this batch and environment
204
+ done_flags = done[batch_idx, env_idx, :]
205
+
206
+ # Find trajectory boundaries
207
+ trajectory_starts = [0]
208
+ trajectory_ends = []
209
+
210
+ for step in range(seq_len):
211
+ if done_flags[step]:
212
+ trajectory_ends.append(step + 1) # Include the done step
213
+ if step + 1 < seq_len: # If not the last step
214
+ trajectory_starts.append(step + 1)
215
+
216
+ # If the last trajectory doesn't end with done=True
217
+ if len(trajectory_ends) < len(trajectory_starts):
218
+ trajectory_ends.append(seq_len)
219
+
220
+ # Extract each trajectory
221
+ for start, end in zip(trajectory_starts, trajectory_ends):
222
+ if end > start: # Valid trajectory
223
+ traj_length = end - start
224
+ trajectories.append({
225
+ 'batch_idx': batch_idx,
226
+ 'env_idx': env_idx,
227
+ 'start': start,
228
+ 'end': end,
229
+ 'length': traj_length
230
+ })
231
+
232
+ print(f"Found {len(trajectories)} individual trajectories")
233
+
234
+ # Find the maximum trajectory length for padding
235
+ max_length = max(traj['length'] for traj in trajectories)
236
+ print(f"Maximum trajectory length: {max_length}")
237
+
238
+ # Create new data structure
239
+ num_trajectories = len(trajectories)
240
+ processed_data = {}
241
+
242
+ # Process each variable (except 'done' which we'll recreate)
243
+ for var_name in data.files:
244
+ if var_name == 'done':
245
+ continue
246
+
247
+ var_data = data[var_name]
248
+ print(f"Processing variable: {var_name}, shape: {var_data.shape}")
249
+
250
+ # Determine the new shape
251
+ if len(var_data.shape) == 3: # (batch, env, seq)
252
+ new_shape = (num_trajectories, max_length)
253
+ elif len(var_data.shape) == 4: # (batch, env, seq, feature)
254
+ feature_dim = var_data.shape[3]
255
+ new_shape = (num_trajectories, max_length, feature_dim)
256
+ else:
257
+ print(f"Warning: Unexpected shape for variable {var_name}: {var_data.shape}")
258
+ continue
259
+
260
+ # Create new array filled with NaN
261
+ if var_data.dtype in [np.float32, np.float64]:
262
+ new_var_data = np.full(new_shape, np.nan, dtype=var_data.dtype)
263
+ else:
264
+ # For non-float types, use zeros or appropriate fill value
265
+ new_var_data = np.zeros(new_shape, dtype=var_data.dtype)
266
+
267
+ # Fill in the trajectory data
268
+ for traj_idx, traj in enumerate(trajectories):
269
+ batch_idx = traj['batch_idx']
270
+ env_idx = traj['env_idx']
271
+ start = traj['start']
272
+ end = traj['end']
273
+ length = traj['length']
274
+
275
+ if len(var_data.shape) == 3:
276
+ new_var_data[traj_idx, :length] = var_data[batch_idx, env_idx, start:end]
277
+ elif len(var_data.shape) == 4:
278
+ new_var_data[traj_idx, :length, :] = var_data[batch_idx, env_idx, start:end, :]
279
+
280
+ processed_data[var_name] = new_var_data
281
+
282
+ # Create new done array
283
+ done_new = np.zeros((num_trajectories, max_length), dtype=bool)
284
+ for traj_idx, traj in enumerate(trajectories):
285
+ length = traj['length']
286
+ done_new[traj_idx, length-1] = True # Mark the end of each trajectory
287
+
288
+ processed_data['done'] = done_new
289
+
290
+ # Add trajectory metadata
291
+ traj_lengths = np.array([traj['length'] for traj in trajectories], dtype=np.int32)
292
+ processed_data['trajectory_lengths'] = traj_lengths
293
+
294
+ # Display new dataset information
295
+ print(f"\n{'='*60}")
296
+ print("PROCESSED DATASET INFORMATION")
297
+ print(f"{'='*60}")
298
+ print(f"Number of trajectories: {num_trajectories}")
299
+ print(f"Maximum trajectory length: {max_length}")
300
+ print(f"Average trajectory length: {np.mean(traj_lengths):.2f}")
301
+ print(f"Trajectory length distribution:")
302
+ print(f" Min: {np.min(traj_lengths)}")
303
+ print(f" Max: {np.max(traj_lengths)}")
304
+ print(f" Median: {np.median(traj_lengths):.2f}")
305
+
306
+ print(f"\nNew variable information:")
307
+ print("-" * 60)
308
+
309
+ for i, (var_name, var_data) in enumerate(processed_data.items(), 1):
310
+ print(f"{i:2d}. Variable name: {var_name}")
311
+ print(f" Data type: {var_data.dtype}")
312
+ print(f" Shape (dimensions): {var_data.shape}")
313
+ print(f" Total elements: {var_data.size}")
314
+
315
+ if np.issubdtype(var_data.dtype, np.number) and var_name != 'trajectory_lengths':
316
+ # Calculate stats excluding NaN values
317
+ valid_data = var_data[~np.isnan(var_data)] if var_data.dtype in [np.float32, np.float64] else var_data
318
+ if valid_data.size > 0:
319
+ print(f" Valid elements: {valid_data.size}")
320
+ print(f" Value range: [{np.min(valid_data):.4f}, {np.max(valid_data):.4f}]")
321
+ print(f" Mean: {np.mean(valid_data):.4f}")
322
+ print(f" Std dev: {np.std(valid_data):.4f}")
323
+
324
+ print()
325
+
326
+ # Save processed data if output path is provided
327
+ if output_file_path:
328
+ np.savez_compressed(output_file_path, **processed_data)
329
+ print(f"Processed data saved to: {output_file_path}")
330
+
331
+ data.close()
332
+ return processed_data
333
+
334
+ except Exception as e:
335
+ print(f"Error processing file {npz_file_path}: {str(e)}")
336
+ return None
337
+
338
+
339
+ def plot_trajectory(npz_file_path, trajectory_id, output_image_path=None):
340
+ """
341
+ Plot observations and actions for a specific trajectory.
342
+
343
+ Args:
344
+ npz_file_path (str): Path to .npz file containing trajectory data
345
+ trajectory_id (int): ID of the trajectory to plot
346
+ output_image_path (str): Path to save the plot image (optional)
347
+ """
348
+ try:
349
+ # Load trajectory data
350
+ data = np.load(npz_file_path)
351
+
352
+ # Check if required variables exist
353
+ if 'obs' not in data.files or 'action' not in data.files:
354
+ print("Error: 'obs' or 'action' variable not found in the data")
355
+ return
356
+
357
+ obs = data['obs'] # Shape: (batch, env, seq, 18) or (num_trajectories, max_length, 18)
358
+ action = data['action'] # Shape: (batch, env, seq, 6) or (num_trajectories, max_length, 6)
359
+
360
+ # Check if this is processed trajectory data or original batch data
361
+ if 'trajectory_lengths' in data.files:
362
+ # Processed trajectory data
363
+ traj_lengths = data['trajectory_lengths']
364
+ num_trajectories = obs.shape[0]
365
+
366
+ # Validate trajectory ID
367
+ if trajectory_id < 0 or trajectory_id >= num_trajectories:
368
+ print(f"Error: Trajectory ID {trajectory_id} is out of range [0, {num_trajectories-1}]")
369
+ return
370
+
371
+ traj_length = traj_lengths[trajectory_id]
372
+ traj_obs = obs[trajectory_id, :traj_length, :]
373
+ traj_action = action[trajectory_id, :traj_length, :]
374
+
375
+ # Get done flags for this trajectory
376
+ if 'done' in data.files:
377
+ traj_done = data['done'][trajectory_id, :traj_length]
378
+ done_indices = np.where(traj_done)[0]
379
+ print(f"Done=True at time steps: {done_indices}")
380
+
381
+ else:
382
+ # Original batch data - need to specify batch and env indices
383
+ if len(obs.shape) != 4:
384
+ print(f"Error: Expected 4D data (batch, env, seq, features), got shape {obs.shape}")
385
+ return
386
+
387
+ batch_size, env_num, seq_len, obs_dim = obs.shape
388
+ total_sequences = batch_size * env_num
389
+
390
+ # Convert trajectory_id to batch and env indices
391
+ if trajectory_id < 0 or trajectory_id >= total_sequences:
392
+ print(f"Error: Trajectory ID {trajectory_id} is out of range [0, {total_sequences-1}]")
393
+ return
394
+
395
+ batch_idx = trajectory_id // env_num
396
+ env_idx = trajectory_id % env_num
397
+
398
+ print(f"Using batch {batch_idx}, environment {env_idx} from original data")
399
+
400
+ traj_obs = obs[batch_idx, env_idx, :, :] # Shape: (seq_len, 18)
401
+ traj_action = action[batch_idx, env_idx, :, :] # Shape: (seq_len, 6)
402
+ traj_length = seq_len
403
+
404
+ # Get done flags for this trajectory
405
+ if 'done' in data.files:
406
+ traj_done = data['done'][batch_idx, env_idx, :]
407
+ done_indices = np.where(traj_done)[0]
408
+ print(f"Done=True at time steps: {done_indices}")
409
+
410
+ print(f"Plotting trajectory {trajectory_id} with length {traj_length}")
411
+
412
+ # Create time axis
413
+ time_steps = np.arange(traj_length)
414
+
415
+ # Create 6x4 subplot
416
+ fig, axes = plt.subplots(6, 4, figsize=(16, 18))
417
+ fig.suptitle(f'Trajectory {trajectory_id} - Observations and Actions', fontsize=16)
418
+
419
+ # Plot observations (18 dimensions) in first 3 columns
420
+ for i in range(18):
421
+ row = i // 3
422
+ col = i % 3
423
+ axes[row, col].plot(time_steps[:], traj_obs[:, i], 'b-o', linewidth=1)
424
+ axes[row, col].set_title(f'Obs {i}')
425
+ axes[row, col].grid(True, alpha=0.3)
426
+ axes[row, col].set_xlabel('Time Step')
427
+
428
+ # Plot actions (6 dimensions) in the last column
429
+ for i in range(6):
430
+ axes[i, 3].plot(time_steps, traj_action[:, i], 'r-', linewidth=1)
431
+ axes[i, 3].set_title(f'Action {i}')
432
+ axes[i, 3].grid(True, alpha=0.3)
433
+ axes[i, 3].set_xlabel('Time Step')
434
+
435
+ # Adjust layout
436
+ plt.tight_layout()
437
+
438
+ # Save or show plot
439
+ if output_image_path:
440
+ plt.savefig(output_image_path, dpi=300, bbox_inches='tight')
441
+ print(f"Plot saved to: {output_image_path}")
442
+ else:
443
+ # Generate default filename
444
+ base_name = os.path.splitext(os.path.basename(npz_file_path))[0]
445
+ default_path = f"{base_name}_trajectory_{trajectory_id}.png"
446
+ plt.savefig(default_path, dpi=300, bbox_inches='tight')
447
+ print(f"Plot saved to: {default_path}")
448
+
449
+ plt.close()
450
+ data.close()
451
+
452
+ except Exception as e:
453
+ print(f"Error plotting trajectory: {str(e)}")
454
+
455
+
456
+ def plot_done_statistics(npz_file_path, output_image_path=None):
457
+ """
458
+ Plot histogram of done time steps across all trajectories.
459
+
460
+ Args:
461
+ npz_file_path (str): Path to .npz file containing trajectory data
462
+ output_image_path (str): Path to save the plot image (optional)
463
+ """
464
+ try:
465
+ # Load trajectory data
466
+ data = np.load(npz_file_path)
467
+
468
+ # Check if required variables exist
469
+ if 'done' not in data.files:
470
+ print("Error: 'done' variable not found in the data")
471
+ return
472
+
473
+ done = data['done']
474
+
475
+ # Check if this is processed trajectory data or original batch data
476
+ if 'trajectory_lengths' in data.files:
477
+ # Processed trajectory data
478
+ traj_lengths = data['trajectory_lengths']
479
+ num_trajectories = done.shape[0]
480
+
481
+ all_done_times = []
482
+ for traj_id in range(num_trajectories):
483
+ traj_length = traj_lengths[traj_id]
484
+ traj_done = done[traj_id, :traj_length]
485
+ done_indices = np.where(traj_done)[0]
486
+ all_done_times.extend(done_indices)
487
+
488
+ print(f"Found {len(all_done_times)} done signals across {num_trajectories} trajectories")
489
+
490
+ else:
491
+ # Original batch data
492
+ batch_size, env_num, seq_len = done.shape
493
+
494
+ all_done_times = []
495
+ for batch_idx in range(batch_size):
496
+ for env_idx in range(env_num):
497
+ traj_done = done[batch_idx, env_idx, :]
498
+ done_indices = np.where(traj_done)[0]
499
+ all_done_times.extend(done_indices)
500
+
501
+ total_sequences = batch_size * env_num
502
+ print(f"Found {len(all_done_times)} done signals across {total_sequences} sequences")
503
+
504
+ if not all_done_times:
505
+ print("No done signals found in the data")
506
+ return
507
+
508
+ all_done_times = np.array(all_done_times)
509
+
510
+ # Create histogram plot
511
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
512
+
513
+ # Histogram of done times
514
+ ax1.hist(all_done_times, bins=50, alpha=0.7, color='blue', edgecolor='black')
515
+ ax1.set_xlabel('Time Step')
516
+ ax1.set_ylabel('Frequency')
517
+ ax1.set_title('Distribution of Done Signal Time Steps')
518
+ ax1.grid(True, alpha=0.3)
519
+
520
+ # Statistics
521
+ mean_done_time = np.mean(all_done_times)
522
+ median_done_time = np.median(all_done_times)
523
+ std_done_time = np.std(all_done_times)
524
+
525
+ ax1.axvline(mean_done_time, color='red', linestyle='--', linewidth=2, label=f'Mean: {mean_done_time:.1f}')
526
+ ax1.axvline(median_done_time, color='green', linestyle='--', linewidth=2, label=f'Median: {median_done_time:.1f}')
527
+ ax1.legend()
528
+
529
+ # Box plot
530
+ ax2.boxplot(all_done_times, vert=False)
531
+ ax2.set_xlabel('Time Step')
532
+ ax2.set_title('Box Plot of Done Signal Time Steps')
533
+ ax2.grid(True, alpha=0.3)
534
+
535
+ # Add statistics text
536
+ stats_text = f"""Statistics:
537
+ Total done signals: {len(all_done_times)}
538
+ Mean: {mean_done_time:.2f}
539
+ Median: {median_done_time:.2f}
540
+ Std Dev: {std_done_time:.2f}
541
+ Min: {np.min(all_done_times)}
542
+ Max: {np.max(all_done_times)}
543
+ 25th percentile: {np.percentile(all_done_times, 25):.1f}
544
+ 75th percentile: {np.percentile(all_done_times, 75):.1f}"""
545
+
546
+ ax2.text(0.02, 0.98, stats_text, transform=ax2.transAxes,
547
+ verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
548
+
549
+ plt.tight_layout()
550
+
551
+ # Save plot
552
+ if output_image_path:
553
+ plt.savefig(output_image_path, dpi=300, bbox_inches='tight')
554
+ print(f"Done statistics plot saved to: {output_image_path}")
555
+ else:
556
+ # Generate default filename
557
+ base_name = os.path.splitext(os.path.basename(npz_file_path))[0]
558
+ default_path = f"{base_name}_done_statistics.png"
559
+ plt.savefig(default_path, dpi=300, bbox_inches='tight')
560
+ print(f"Done statistics plot saved to: {default_path}")
561
+
562
+ plt.close()
563
+ data.close()
564
+
565
+ # Print summary
566
+ print(f"\nDone Statistics Summary:")
567
+ print(f"Total done signals: {len(all_done_times)}")
568
+ print(f"Mean time step: {mean_done_time:.2f}")
569
+ print(f"Median time step: {median_done_time:.2f}")
570
+ print(f"Standard deviation: {std_done_time:.2f}")
571
+ print(f"Range: [{np.min(all_done_times)}, {np.max(all_done_times)}]")
572
+
573
+ except Exception as e:
574
+ print(f"Error plotting done statistics: {str(e)}")
575
+
576
+
577
+ if __name__ == "__main__":
578
+ # Set up command line argument parsing
579
+ parser = argparse.ArgumentParser(description="Load and analyze .npz files")
580
+ parser.add_argument("path", nargs="?", default=".",
581
+ help="Path to .npz file or directory containing .npz files (default: current directory)")
582
+ parser.add_argument("-v", "--verbose", action="store_true",
583
+ help="Show detailed information including statistics")
584
+ parser.add_argument("-l", "--list-only", action="store_true",
585
+ help="Only list variable names and shapes, no detailed info")
586
+ parser.add_argument("-f", "--first-only", action="store_true",
587
+ help="Only process the first .npz file found")
588
+ parser.add_argument("-t", "--extract-trajectories", action="store_true",
589
+ help="Extract individual trajectories based on done signal")
590
+ parser.add_argument("-o", "--output", type=str,
591
+ help="Output file path for processed trajectories")
592
+ parser.add_argument("-p", "--plot", type=int, metavar="TRAJ_ID",
593
+ help="Plot trajectory with specified ID")
594
+ parser.add_argument("--plot-output", type=str,
595
+ help="Output path for trajectory plot image")
596
+
597
+ args = parser.parse_args()
598
+
599
+ # Handle case where user accidentally includes "path=" prefix
600
+ if args.path.startswith("path="):
601
+ args.path = args.path[5:] # Remove "path=" prefix
602
+
603
+ print("NPZ File Loader")
604
+ print("=" * 60)
605
+
606
+ # Check if path exists
607
+ if not os.path.exists(args.path):
608
+ print(f"Error: Path '{args.path}' does not exist")
609
+ sys.exit(1)
610
+
611
+ # If path is a file
612
+ if os.path.isfile(args.path):
613
+ if args.path.endswith('.npz'):
614
+ print(f"Loading single file: {args.path}")
615
+
616
+ if args.extract_trajectories:
617
+ # Extract trajectories
618
+ output_path = args.output
619
+ if not output_path:
620
+ # Generate default output filename
621
+ base_name = os.path.splitext(args.path)[0]
622
+ output_path = f"{base_name}_trajectories.npz"
623
+
624
+ processed_data = extract_trajectories_from_npz(args.path, output_path)
625
+
626
+ # Also display the processed data information
627
+ if processed_data and output_path and os.path.exists(output_path):
628
+ print(f"\n{'='*60}")
629
+ print("VERIFYING SAVED PROCESSED DATA")
630
+ print(f"{'='*60}")
631
+ if args.list_only:
632
+ load_npz_simple(output_path)
633
+ else:
634
+ load_npz_info(output_path)
635
+ elif args.plot is not None:
636
+ # Plot trajectory
637
+ plot_trajectory(args.path, args.plot, args.plot_output)
638
+ # Always plot done statistics too
639
+ plot_done_statistics(args.path, None)
640
+ else:
641
+ # Default: plot trajectory 0
642
+ plot_trajectory(args.path, 0, None)
643
+ # Also plot done statistics
644
+ plot_done_statistics(args.path, None)
645
+ else:
646
+ print(f"Error: '{args.path}' is not a .npz file")
647
+ sys.exit(1)
648
+
649
+ # If path is a directory
650
+ elif os.path.isdir(args.path):
651
+ npz_files = glob.glob(os.path.join(args.path, "*.npz"))
652
+
653
+ if not npz_files:
654
+ print(f"No .npz files found in directory {args.path}")
655
+ sys.exit(1)
656
+
657
+ npz_files.sort()
658
+ print(f"Found {len(npz_files)} .npz files in directory {args.path}")
659
+
660
+ if args.first_only:
661
+ npz_files = npz_files[:1]
662
+ print("Processing only the first file...")
663
+
664
+ for npz_file in npz_files:
665
+ if args.list_only:
666
+ load_npz_simple(npz_file)
667
+ else:
668
+ load_npz_info(npz_file)
669
+
670
+ else:
671
+ print(f"Error: '{args.path}' is neither a file nor a directory")
672
+ sys.exit(1)
dataset/{sb3_cheetah_run_ckpt001_2025-08-18_23-31-33.npz → sb3_cheetah_run_ckpt001_2025-08-28_19-39-53.npz} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:eefc8c4c5e6f1e233a9bb79e1527afc6fc55b76625f190084982382d920dbf9e
3
- size 83471485
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25e74c6eba114897008ce859b2f77c7612275e09250f600b4a458d1adb4b6468
3
+ size 83206684
dataset/{sb3_cheetah_run_ckpt001_2025-08-18_23-31-33_metadata.pkl → sb3_cheetah_run_ckpt001_2025-08-28_19-39-53_metadata.pkl} RENAMED
File without changes
dataset/sb3_cheetah_run_ckpt020_2025-08-28_17-35-15.npz DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6f21abb567a8ec2016031d6cff665f2ca7c267a3683f20a1bd05242bddef62e7
3
- size 83973060
 
 
 
 
dataset/{sb3_cheetah_run_ckpt001_2025-08-28_16-46-27.npz → sb3_cheetah_run_ckpt020_2025-08-28_19-42-44.npz} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c261689477b68d38695fd8d25b0ee9e88df56ad3cc08c187a00bb0eed2f4e5f0
3
- size 83472274
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2196469b61f6f81c7806122eed54eceb7dbe6437fbab8ddd5e7ff03b6e582ed
3
+ size 42271647
dataset/{sb3_cheetah_run_ckpt020_2025-08-18_23-36-48_metadata.pkl → sb3_cheetah_run_ckpt020_2025-08-28_19-42-44_metadata.pkl} RENAMED
File without changes
dataset/sb3_cheetah_run_ckpt030_2025-08-18_23-40-31.npz DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:d6bdf8b41e2caa6e6b19959a88ad13dab7d0bb6106ebaa78d2ebb2dde9e20c24
3
- size 84803350
 
 
 
 
dataset/sb3_cheetah_run_ckpt030_2025-08-28_17-38-32.npz DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:24f28dce1b3422303367426abfa92fb697ac90f4ce7e96425fb98fbac6082b76
3
- size 84805176
 
 
 
 
dataset/{sb3_cheetah_run_ckpt020_2025-08-18_23-36-48.npz → sb3_cheetah_run_ckpt030_2025-08-28_19-49-33.npz} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:06cc39f264964dba65a6be759d1c008bbdbcf3b73358a83d64a3f7f386e92ba9
3
- size 83959326
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c9399cb462e5baeffb6b78b407155ece4ed039672d417f5191ad6f0d990d6d4
3
+ size 83939631
dataset/{sb3_cheetah_run_ckpt030_2025-08-18_23-40-31_metadata.pkl → sb3_cheetah_run_ckpt030_2025-08-28_19-49-33_metadata.pkl} RENAMED
File without changes
dataset/sb3_cheetah_run_ckpt050_2025-08-18_23-43-50.npz DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b4da8fd4aeed18d39a917f051be29ef854284b4862e8e5db7cb11957fcf92bf8
3
- size 84717638
 
 
 
 
dataset/sb3_cheetah_run_ckpt050_2025-08-28_17-41-11.npz DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f53d009a9825d3132a53b9a8b2507c6cba749226d0ae4de86a1ec84ee1350f5f
3
- size 84718968
 
 
 
 
dataset/sb3_cheetah_run_ckpt050_2025-08-28_17-41-11_metadata.pkl DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0e2c5bb44fbc717c4adfea19e93ba290a02b64b76315f637a619422ca7a5151a
3
- size 191
 
 
 
 
dataset/sb3_cheetah_run_ckpt050_2025-08-28_20-11-25.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3a60c3519b157de2f157c057169d3c44e7e4f0f3d12c7f3ef9e98f51aba8f80
3
+ size 83828056
dataset/{sb3_cheetah_run_ckpt050_2025-08-18_23-43-50_metadata.pkl → sb3_cheetah_run_ckpt050_2025-08-28_20-11-25_metadata.pkl} RENAMED
File without changes
dataset/sb3_cheetah_run_ckpt020_2025-08-28_17-35-15_metadata.pkl → sb3_cheetah_run_ckpt001_2025-08-28_19-35-01_trajectory_0.png RENAMED
File without changes
dataset/sb3_cheetah_run_ckpt030_2025-08-28_17-38-32_metadata.pkl → sb3_cheetah_run_ckpt001_2025-08-28_19-39-53_trajectory_0.png RENAMED
File without changes
dataset/sb3_cheetah_run_ckpt001_2025-08-28_16-46-27_metadata.pkl → sb3_cheetah_run_ckpt020_2025-08-28_19-42-44_trajectory_0.png RENAMED
File without changes
sb3_collect.py CHANGED
@@ -230,7 +230,7 @@ def main():
230
  args = parse_args()
231
 
232
  # Prepare env
233
- env = suite.load(domain_name=args.domain, task_name=args.task, task_kwargs={"random": args.seed})
234
  action_spec = env.action_spec()
235
 
236
  # Determine obs flatten order once
 
230
  args = parse_args()
231
 
232
  # Prepare env
233
+ env = suite.load(domain_name=args.domain, task_name=args.task, task_kwargs={"random": args.seed, 'time_limit': 100000})
234
  action_spec = env.action_spec()
235
 
236
  # Determine obs flatten order once