#!/usr/bin/env python3 """Create lightweight Parquet tables for the Hugging Face Dataset Viewer. The full multidimensional arrays remain in NPZ files. Each Parquet row corresponds to one NPZ sample and contains only identifiers, shapes, and compact summary statistics. """ from __future__ import annotations import argparse from pathlib import Path from typing import Any import numpy as np import pandas as pd DATASETS = { "global_mask": { "train": "GlobalMask/train/GlobalMask_train.npz", "test": "GlobalMask/test/GlobalMask_test.npz", }, "above": { "train": "InSituMatched/above/train/InSituMatched_above_train.npz", "test": "InSituMatched/above/test/InSituMatched_above_test.npz", }, "ameriflux": { "train": "InSituMatched/ameriflux/train/InSituMatched_ameriflux_train.npz", "test": "InSituMatched/ameriflux/test/InSituMatched_ameriflux_test.npz", }, "fluxnet": { "train": "InSituMatched/fluxnet/train/InSituMatched_fluxnet_train.npz", "test": "InSituMatched/fluxnet/test/InSituMatched_fluxnet_test.npz", }, "icos-ww": { "train": "InSituMatched/icos_ww/train/InSituMatched_icos-ww_train.npz", "test": "InSituMatched/icos_ww/test/InSituMatched_icos-ww_test.npz", }, "multiple": { "train": "InSituMatched/multiple/train/InSituMatched_multiple_train.npz", "test": "InSituMatched/multiple/test/InSituMatched_multiple_test.npz", }, } def shape_text(array: np.ndarray | None) -> str: if array is None: return "" return " × ".join(str(v) for v in array.shape[1:]) def finite_mean(values: np.ndarray) -> float | None: finite = np.isfinite(values) if not finite.any(): return None return float(values[finite].mean()) def finite_fraction(values: np.ndarray) -> float: return float(np.isfinite(values).mean()) def build_rows(npz_path: Path, config_name: str, split: str, relative_path: str) -> list[dict[str, Any]]: with np.load(npz_path, allow_pickle=False) as data: arrays = {key: data[key] for key in data.files} if "ed_simulation_x" not in arrays: raise KeyError(f"{npz_path}: missing required key 'ed_simulation_x'") sample_count = arrays["ed_simulation_x"].shape[0] for key, value in arrays.items(): if value.ndim > 0 and value.shape[0] != sample_count: raise ValueError( f"{npz_path}: key {key!r} is not sample-first: " f"first dimension {value.shape[0]} != {sample_count}" ) x = arrays.get("ed_simulation_x") y = arrays.get("ed_simulation_y") observed = arrays.get("observed_y") age = arrays.get("lidar_age_weight_fraction") esa_bl = arrays.get("esa_cci_bl_fraction") esa_nl = arrays.get("esa_cci_nl_fraction") esa_gs = arrays.get("esa_cci_gs_fraction") pft_bl = arrays.get("ed_simulation_pft_bl") pft_nl = arrays.get("ed_simulation_pft_nl") pft_gs = arrays.get("ed_simulation_pft_gs") rows: list[dict[str, Any]] = [] for i in range(sample_count): row: dict[str, Any] = { "sample_index": i, "split": split, "subset": config_name, "data_file": relative_path, "ed_simulation_x_shape": shape_text(x), "ed_simulation_y_shape": shape_text(y), "observed_y_shape": shape_text(observed), } if age is not None: row["lidar_age_weight_sum"] = float(np.sum(age[i])) if esa_bl is not None: row["esa_cci_bl_mean"] = finite_mean(esa_bl[i]) if esa_nl is not None: row["esa_cci_nl_mean"] = finite_mean(esa_nl[i]) if esa_gs is not None: row["esa_cci_gs_mean"] = finite_mean(esa_gs[i]) if observed is not None: row["observed_y_valid_fraction"] = finite_fraction(observed[i]) if pft_bl is not None: row["ed_simulation_pft_bl_mean"] = finite_mean(pft_bl[i]) if pft_nl is not None: row["ed_simulation_pft_nl_mean"] = finite_mean(pft_nl[i]) if pft_gs is not None: row["ed_simulation_pft_gs_mean"] = finite_mean(pft_gs[i]) rows.append(row) return rows def output_path(root: Path, config_name: str, split: str) -> Path: if config_name == "global_mask": return root / "viewer" / "global_mask" / f"{split}.parquet" return root / "viewer" / "insitu_matched" / config_name / f"{split}.parquet" def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--root", type=Path, default=Path("."), help="DERE repository root (default: current directory)", ) args = parser.parse_args() root = args.root.resolve() for config_name, splits in DATASETS.items(): for split, relative_path in splits.items(): npz_path = root / relative_path if not npz_path.exists(): raise FileNotFoundError(f"Missing data file: {npz_path}") rows = build_rows(npz_path, config_name, split, relative_path) destination = output_path(root, config_name, split) destination.parent.mkdir(parents=True, exist_ok=True) frame = pd.DataFrame(rows) frame.to_parquet(destination, index=False) print(f"Wrote {destination.relative_to(root)} ({len(frame)} rows)") if __name__ == "__main__": main()