| |
| """Build a validated radar-first table joined with two depth frames. |
| |
| The exact join key is recording_id + subject + activity + frame_index. Every |
| radar row must match exactly two depth rows, and every depth row must match at |
| least one radar row. Original .mat and .npy files are never opened. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| import pyarrow as pa |
| import pyarrow.parquet as pq |
|
|
|
|
| JOIN_KEYS = ("recording_id", "subject", "activity", "frame_index") |
| DEPTH_ITEM_FIELDS = ("relative_path", "sequence_name", "local_frame_index") |
| DEPTH_COLUMNS = (*JOIN_KEYS, *DEPTH_ITEM_FIELDS) |
| RADAR_COLUMNS = ( |
| "relative_path", |
| "recording_id", |
| "sequence_name", |
| "activity", |
| "subject", |
| "snaplength", |
| "format", |
| "win_size", |
| "win_stride", |
| "frame_index", |
| "range_bin_index", |
| "entrophy", |
| ) |
|
|
| OUTPUT_SCHEMA = pa.schema( |
| [ |
| pa.field("recording_id", pa.string()), |
| pa.field("subject", pa.string()), |
| pa.field("activity", pa.string()), |
| pa.field("frame_index", pa.int64()), |
| pa.field("radar_path", pa.string()), |
| pa.field("radar_sequence_name", pa.string()), |
| pa.field("radar_snaplength", pa.int64()), |
| pa.field("radar_format", pa.string()), |
| pa.field("radar_win_size", pa.int64()), |
| pa.field("radar_win_stride", pa.int64()), |
| pa.field("radar_range_bin_index", pa.int64()), |
| pa.field("radar_entrophy", pa.float64()), |
| pa.field("depth_paths", pa.list_(pa.string())), |
| pa.field("depth_sequence_names", pa.list_(pa.string())), |
| pa.field("depth_local_frame_indexes", pa.list_(pa.int64())), |
| ] |
| ) |
|
|
|
|
| JoinKey = tuple[str, str, str, int] |
|
|
|
|
| def _check_columns( |
| parquet_file: pq.ParquetFile, required: tuple[str, ...], label: str |
| ) -> None: |
| missing = sorted(set(required) - set(parquet_file.schema_arrow.names)) |
| if missing: |
| raise ValueError(f"{label} Parquet is missing columns: {', '.join(missing)}") |
|
|
|
|
| def _join_key(row: dict[str, object]) -> JoinKey: |
| return ( |
| str(row["recording_id"]), |
| str(row["subject"]), |
| str(row["activity"]), |
| int(row["frame_index"]), |
| ) |
|
|
|
|
| def _group_and_validate_depth( |
| depth_file: pq.ParquetFile, |
| ) -> dict[JoinKey, list[dict[str, object]]]: |
| """Group depth rows and require exactly two local frames for every key.""" |
| grouped: dict[JoinKey, list[dict[str, object]]] = defaultdict(list) |
| for batch in depth_file.iter_batches(columns=list(DEPTH_COLUMNS), batch_size=100_000): |
| for row in batch.to_pylist(): |
| grouped[_join_key(row)].append( |
| {field: row[field] for field in DEPTH_ITEM_FIELDS} |
| ) |
|
|
| invalid = [] |
| for key, items in grouped.items(): |
| items.sort(key=lambda item: (item["local_frame_index"], item["relative_path"])) |
| local_indexes = [item["local_frame_index"] for item in items] |
| if len(items) != 2 or len(set(local_indexes)) != 2: |
| invalid.append((key, len(items), local_indexes)) |
|
|
| if invalid: |
| key, count, local_indexes = invalid[0] |
| raise ValueError( |
| "Every frame key must contain exactly two distinct depth local frames; " |
| f"first invalid key={key}, count={count}, local_indexes={local_indexes}. " |
| f"Total invalid keys={len(invalid)}" |
| ) |
| return dict(grouped) |
|
|
|
|
| def join_radar_and_depth( |
| radar_parquet: str | Path, |
| depth_parquet: str | Path, |
| output_path: str | Path, |
| ) -> int: |
| """Write the radar-first table and return its validated row count.""" |
| radar_path = Path(radar_parquet).expanduser().resolve() |
| depth_path = Path(depth_parquet).expanduser().resolve() |
| output = Path(output_path).expanduser().resolve() |
|
|
| for path in (radar_path, depth_path): |
| if not path.is_file(): |
| raise FileNotFoundError(f"Parquet file does not exist: {path}") |
|
|
| radar_file = pq.ParquetFile(radar_path) |
| depth_file = pq.ParquetFile(depth_path) |
| _check_columns(radar_file, RADAR_COLUMNS, "Radar") |
| _check_columns(depth_file, DEPTH_COLUMNS, "Depth") |
| depth_items_by_key = _group_and_validate_depth(depth_file) |
|
|
| output.parent.mkdir(parents=True, exist_ok=True) |
| temporary_output = output.with_name(f".{output.name}.tmp") |
| temporary_output.unlink(missing_ok=True) |
| matched_depth_keys: set[JoinKey] = set() |
| written_rows = 0 |
| writer = pq.ParquetWriter(temporary_output, OUTPUT_SCHEMA, compression="zstd") |
| try: |
| for batch in radar_file.iter_batches( |
| columns=list(RADAR_COLUMNS), batch_size=100_000 |
| ): |
| output_rows = [] |
| for row in batch.to_pylist(): |
| key = _join_key(row) |
| depth_items = depth_items_by_key.get(key) |
| if depth_items is None: |
| raise ValueError(f"Radar row has no matching depth frames: key={key}") |
| matched_depth_keys.add(key) |
|
|
| output_rows.append( |
| { |
| "recording_id": row["recording_id"], |
| "subject": row["subject"], |
| "activity": row["activity"], |
| "frame_index": row["frame_index"], |
| "radar_path": row["relative_path"], |
| "radar_sequence_name": row["sequence_name"], |
| "radar_snaplength": row["snaplength"], |
| "radar_format": row["format"], |
| "radar_win_size": row["win_size"], |
| "radar_win_stride": row["win_stride"], |
| "radar_range_bin_index": row["range_bin_index"], |
| "radar_entrophy": row["entrophy"], |
| "depth_paths": [item["relative_path"] for item in depth_items], |
| "depth_sequence_names": [ |
| item["sequence_name"] for item in depth_items |
| ], |
| "depth_local_frame_indexes": [ |
| item["local_frame_index"] for item in depth_items |
| ], |
| } |
| ) |
|
|
| table = pa.Table.from_pylist(output_rows, schema=OUTPUT_SCHEMA) |
| writer.write_table(table) |
| written_rows += table.num_rows |
| except Exception: |
| writer.close() |
| temporary_output.unlink(missing_ok=True) |
| raise |
| else: |
| writer.close() |
|
|
| unmatched_depth_keys = depth_items_by_key.keys() - matched_depth_keys |
| if unmatched_depth_keys: |
| temporary_output.unlink(missing_ok=True) |
| example = next(iter(unmatched_depth_keys)) |
| raise ValueError( |
| f"Depth frames have no matching radar row: first key={example}. " |
| f"Total unmatched depth keys={len(unmatched_depth_keys)}" |
| ) |
|
|
| expected_rows = radar_file.metadata.num_rows |
| if written_rows != expected_rows: |
| temporary_output.unlink(missing_ok=True) |
| raise RuntimeError( |
| f"Row-count validation failed: output={written_rows}, radar={expected_rows}" |
| ) |
|
|
| temporary_output.replace(output) |
| return written_rows |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--radar", required=True, help="Radar index Parquet path") |
| parser.add_argument("--depth", required=True, help="Depth index Parquet path") |
| parser.add_argument("--output", required=True, help="Joined Parquet output path") |
| args = parser.parse_args() |
|
|
| row_count = join_radar_and_depth(args.radar, args.depth, args.output) |
| print(f"Wrote {row_count} rows to {Path(args.output).resolve()}") |
| print(f"Validation passed: output rows = radar index rows = {row_count}") |
| print("Validation passed: every radar row has exactly two depth frames") |
| print("Validation passed: every depth frame has a matching radar row") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|