Either computes the statistics of a dataset or loads them from a cache file if this function has been called before with the same `hash_dependencies`. Currently, the statistics include the min/max/mean/std of the actions and proprio as well as the number of transitions and trajecto
(
dataset: dl.DLataset,
hash_dependencies: Tuple[str, ...],
save_dir: Optional[str] = None,
)
| 242 | print(f"Error removing directory {save_path}: {rm_error}") |
| 243 | |
| 244 | def get_dataset_statistics( |
| 245 | dataset: dl.DLataset, |
| 246 | hash_dependencies: Tuple[str, ...], |
| 247 | save_dir: Optional[str] = None, |
| 248 | ) -> Dict: |
| 249 | """ |
| 250 | Either computes the statistics of a dataset or loads them from a cache file if this function has been called before |
| 251 | with the same `hash_dependencies`. |
| 252 | |
| 253 | Currently, the statistics include the min/max/mean/std of the actions and proprio as well as the number of |
| 254 | transitions and trajectories in the dataset. |
| 255 | """ |
| 256 | unique_hash = hashlib.sha256( |
| 257 | "".join(hash_dependencies).encode("utf-8"), usedforsecurity=False |
| 258 | ).hexdigest() |
| 259 | |
| 260 | # Fallback local path for when data_dir is not writable or not provided |
| 261 | local_path = os.path.expanduser( |
| 262 | os.path.join("~", ".cache", "orca", f"dataset_statistics_{unique_hash}.json") |
| 263 | ) |
| 264 | if save_dir is not None: |
| 265 | path = tf.io.gfile.join(save_dir, f"dataset_statistics_{unique_hash}.json") |
| 266 | else: |
| 267 | path = local_path |
| 268 | |
| 269 | # check if cache file exists and load |
| 270 | if tf.io.gfile.exists(path): |
| 271 | print(f"Loading existing dataset statistics from {path}.") |
| 272 | with tf.io.gfile.GFile(path, "r") as f: |
| 273 | metadata = json.load(f) |
| 274 | return metadata |
| 275 | |
| 276 | if os.path.exists(local_path): |
| 277 | print(f"Loading existing dataset statistics from {local_path}.") |
| 278 | with open(local_path, "r") as f: |
| 279 | metadata = json.load(f) |
| 280 | return metadata |
| 281 | |
| 282 | dataset = dataset.traj_map( |
| 283 | lambda traj: { |
| 284 | "action": traj["action"], |
| 285 | "proprio": ( |
| 286 | traj["observation"]["proprio"] |
| 287 | if "proprio" in traj["observation"] |
| 288 | else tf.zeros_like(traj["action"]) |
| 289 | ), |
| 290 | } |
| 291 | ) |
| 292 | |
| 293 | cardinality = dataset.cardinality().numpy() |
| 294 | if cardinality == tf.data.INFINITE_CARDINALITY: |
| 295 | raise ValueError("Cannot compute dataset statistics for infinite datasets.") |
| 296 | |
| 297 | print("Computing dataset statistics. This may take a bit, but should only need to happen once.") |
| 298 | actions, proprios, num_transitions, num_trajectories = [], [], 0, 0 |
| 299 | for traj in tqdm( |
| 300 | dataset.iterator(), |
| 301 | total=cardinality if cardinality != tf.data.UNKNOWN_CARDINALITY else None, |
no outgoing calls
no test coverage detected