Download stead/plot_train_label_distribution.py from DancingNow/swag-processed-data: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/DancingNow/swag-processed-data/resolve/main/stead/plot_train_label_distribution.py
- Command line
-
hf download hf://datasets/DancingNow/swag-processed-data/stead/plot_train_label_distribution.py
-
curl -L -o plot_train_label_distribution.py https://huggingface.co/datasets/DancingNow/swag-processed-data/resolve/main/stead/plot_train_label_distribution.py
11.8 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import h5py | |
| import matplotlib as mpl | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from matplotlib.ticker import MaxNLocator, ScalarFormatter | |
| SCRIPT_DIR = Path(__file__).resolve().parent | |
| DEFAULT_TRAIN_H5 = SCRIPT_DIR / "train" / "stead_100hz_60s_train.h5" | |
| DEFAULT_TRAIN_META = SCRIPT_DIR / "train" / "stead_100hz_60s_train_meta.csv" | |
| DEFAULT_GENERATION_META = SCRIPT_DIR / "train" / "stead_100hz_60s_train_meta_uniform10k.csv" | |
| DEFAULT_STATION_CODES = SCRIPT_DIR / "station_codes_stead.csv" | |
| DEFAULT_OUTPUT_PREFIX = SCRIPT_DIR / "stead_train_label_distribution_final_style" | |
| DEFAULT_GENERATION_CSV = SCRIPT_DIR / "stead_generation_conditions_from_train.csv" | |
| TRAIN_FILL = "#d8d6cf" | |
| TRAIN_EDGE = "#5f5f5f" | |
| GEN_EDGE = "#2f9cc8" | |
| GRID_COLOR = "#e7e7e7" | |
| def configure_matplotlib() -> None: | |
| mpl.rcParams.update( | |
| { | |
| "font.family": "sans-serif", | |
| "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], | |
| "svg.fonttype": "none", | |
| "pdf.fonttype": 42, | |
| "font.size": 7, | |
| "axes.spines.right": False, | |
| "axes.spines.top": False, | |
| "axes.linewidth": 0.7, | |
| "axes.labelsize": 8, | |
| "axes.titlesize": 9, | |
| "xtick.labelsize": 7, | |
| "ytick.labelsize": 7, | |
| "legend.frameon": False, | |
| "xtick.major.width": 0.6, | |
| "ytick.major.width": 0.6, | |
| "xtick.major.size": 2.5, | |
| "ytick.major.size": 2.5, | |
| } | |
| ) | |
| def load_labels(train_h5: Path) -> np.ndarray: | |
| if not train_h5.exists(): | |
| raise FileNotFoundError(f"Training HDF5 not found: {train_h5}") | |
| with h5py.File(train_h5, "r") as handle: | |
| if "labels" not in handle: | |
| raise KeyError(f"HDF5 file does not contain a 'labels' dataset: {train_h5}") | |
| labels = handle["labels"][:] | |
| if labels.ndim != 2 or labels.shape[1] < 4: | |
| raise ValueError(f"Expected labels with shape (n, >=4), got {labels.shape}") | |
| return labels.astype(np.float32, copy=False) | |
| def load_labels_from_meta(train_meta: Path) -> np.ndarray: | |
| if not train_meta.exists(): | |
| raise FileNotFoundError(f"Training metadata CSV not found: {train_meta}") | |
| columns = ["station_code", "p_index", "s_index", "s_decay"] | |
| frame = pd.read_csv(train_meta, usecols=columns) | |
| if frame.empty: | |
| raise ValueError(f"Training metadata CSV is empty: {train_meta}") | |
| for column in columns: | |
| values = pd.to_numeric(frame[column], errors="raise") | |
| if not np.isfinite(values).all(): | |
| raise ValueError(f"Non-finite values found in metadata column: {column}") | |
| frame[column] = values | |
| return frame[columns].to_numpy(dtype=np.float32) | |
| def draw_histogram( | |
| ax, | |
| train_values: np.ndarray, | |
| generation_values: np.ndarray, | |
| bins, | |
| title: str, | |
| xlabel: str, | |
| density: bool = True, | |
| ) -> None: | |
| ax.hist( | |
| train_values, | |
| bins=bins, | |
| density=density, | |
| histtype="stepfilled", | |
| color=TRAIN_FILL, | |
| edgecolor=TRAIN_EDGE, | |
| linewidth=0.9, | |
| alpha=0.72, | |
| label="Training", | |
| ) | |
| ax.hist( | |
| generation_values, | |
| bins=bins, | |
| density=density, | |
| histtype="step", | |
| color=GEN_EDGE, | |
| linewidth=1.0, | |
| linestyle="--", | |
| label="Generation", | |
| ) | |
| ax.grid(axis="y", color=GRID_COLOR, linewidth=0.45) | |
| ax.set_axisbelow(True) | |
| ax.set_title(title, loc="left", pad=3) | |
| ax.set_xlabel(xlabel) | |
| ax.set_ylabel("Density" if density else "Count") | |
| ax.xaxis.set_major_locator(MaxNLocator(nbins=4)) | |
| ax.yaxis.set_major_locator(MaxNLocator(nbins=4)) | |
| y_formatter = ScalarFormatter(useMathText=True) | |
| y_formatter.set_powerlimits((-2, 2)) | |
| ax.yaxis.set_major_formatter(y_formatter) | |
| ax.yaxis.get_offset_text().set_fontsize(6) | |
| def add_panel_label(ax, label: str) -> None: | |
| ax.text( | |
| -0.18, | |
| 1.06, | |
| label, | |
| transform=ax.transAxes, | |
| fontsize=10, | |
| fontweight="bold", | |
| va="bottom", | |
| ha="left", | |
| ) | |
| def build_figure(train_labels: np.ndarray, generation_labels: np.ndarray): | |
| configure_matplotlib() | |
| fig, axes = plt.subplots(2, 3, figsize=(7.2, 3.7), constrained_layout=True) | |
| axes = axes.ravel() | |
| train_sp = train_labels[:, 2] - train_labels[:, 1] | |
| generation_sp = generation_labels[:, 2] - generation_labels[:, 1] | |
| train_decay_after_s = train_labels[:, 3] - train_sp | |
| generation_decay_after_s = generation_labels[:, 3] - generation_sp | |
| draw_histogram( | |
| axes[0], | |
| train_labels[:, 1], | |
| generation_labels[:, 1], | |
| bins=np.arange(350, 951, 50), | |
| title="P arrival", | |
| xlabel="Samples", | |
| ) | |
| draw_histogram( | |
| axes[1], | |
| train_labels[:, 2], | |
| generation_labels[:, 2], | |
| bins=np.arange(150, 4851, 100), | |
| title="S arrival", | |
| xlabel="Samples", | |
| ) | |
| draw_histogram( | |
| axes[2], | |
| train_sp, | |
| generation_sp, | |
| bins=np.arange(0, 4201, 100), | |
| title="S-P", | |
| xlabel="Samples", | |
| ) | |
| draw_histogram( | |
| axes[3], | |
| train_labels[:, 3], | |
| generation_labels[:, 3], | |
| bins=np.arange(0, 5701, 125), | |
| title="Decay time", | |
| xlabel="Samples", | |
| ) | |
| draw_histogram( | |
| axes[4], | |
| train_decay_after_s, | |
| generation_decay_after_s, | |
| bins=np.arange(-250, 5001, 125), | |
| title="Decay after S", | |
| xlabel="Samples", | |
| ) | |
| draw_histogram( | |
| axes[5], | |
| train_labels[:, 0], | |
| generation_labels[:, 0], | |
| bins=np.arange(-0.5, max(train_labels[:, 0].max(), generation_labels[:, 0].max()) + 1.5, 25), | |
| title="Station label", | |
| xlabel="Station label", | |
| density=True, | |
| ) | |
| for panel_label, ax in zip(("a", "b", "c", "d", "e", "f"), axes): | |
| add_panel_label(ax, panel_label) | |
| handles, labels_text = axes[0].get_legend_handles_labels() | |
| fig.legend( | |
| handles, | |
| labels_text, | |
| loc="upper right", | |
| bbox_to_anchor=(0.995, 1.06), | |
| ncol=2, | |
| handlelength=1.8, | |
| columnspacing=1.0, | |
| ) | |
| fig.suptitle("STEAD label distributions", x=0.045, y=1.06, ha="left", fontsize=10, fontweight="bold") | |
| return fig | |
| def write_generation_csv(labels: np.ndarray, generation_csv: Path, row_count: int, seed: int) -> Path: | |
| if row_count > 0 and row_count < len(labels): | |
| rng = np.random.default_rng(seed) | |
| selected = rng.choice(len(labels), size=row_count, replace=False) | |
| labels = labels[selected] | |
| frame = pd.DataFrame( | |
| { | |
| "station_label": labels[:, 0].astype(np.int64), | |
| "p_arrival": labels[:, 1], | |
| "s_arrival": labels[:, 2], | |
| "decay_time": labels[:, 3], | |
| } | |
| ) | |
| frame.to_csv(generation_csv, index=False) | |
| return generation_csv | |
| def summarize(train_labels: np.ndarray, generation_labels: np.ndarray) -> dict: | |
| summary = { | |
| "label_columns": ["station_label", "p_arrival", "s_arrival", "decay_time"], | |
| "train_sample_count": int(train_labels.shape[0]), | |
| "generation_sample_count": int(generation_labels.shape[0]), | |
| "train_unique_station_count": int(np.unique(train_labels[:, 0].astype(np.int64)).shape[0]), | |
| "generation_unique_station_count": int(np.unique(generation_labels[:, 0].astype(np.int64)).shape[0]), | |
| "train_raw_labels": {}, | |
| "generation_raw_labels": {}, | |
| } | |
| for prefix, label_array in (("train", train_labels), ("generation", generation_labels)): | |
| sp_values = label_array[:, 2] - label_array[:, 1] | |
| decay_after_s_values = label_array[:, 3] - sp_values | |
| for name, values in { | |
| "station_label": label_array[:, 0], | |
| "p_arrival": label_array[:, 1], | |
| "s_arrival": label_array[:, 2], | |
| "decay_time": label_array[:, 3], | |
| "s_minus_p": sp_values, | |
| "decay_after_s": decay_after_s_values, | |
| }.items(): | |
| summary[f"{prefix}_raw_labels"][name] = describe(values) | |
| return summary | |
| def describe(values: np.ndarray) -> dict: | |
| return { | |
| "count": int(values.size), | |
| "min": float(np.min(values)), | |
| "q05": float(np.quantile(values, 0.05)), | |
| "q25": float(np.quantile(values, 0.25)), | |
| "median": float(np.quantile(values, 0.50)), | |
| "q75": float(np.quantile(values, 0.75)), | |
| "q95": float(np.quantile(values, 0.95)), | |
| "max": float(np.max(values)), | |
| "mean": float(np.mean(values)), | |
| "std": float(np.std(values)), | |
| } | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description="Plot STEAD training label distributions and prepare a generation CSV.") | |
| parser.add_argument("--train-meta", type=Path, default=DEFAULT_TRAIN_META) | |
| parser.add_argument("--generation-meta", type=Path, default=DEFAULT_GENERATION_META) | |
| parser.add_argument("--train-h5", type=Path, default=DEFAULT_TRAIN_H5) | |
| parser.add_argument("--use-h5-labels", action="store_true") | |
| parser.add_argument("--station-codes", type=Path, default=DEFAULT_STATION_CODES) | |
| parser.add_argument("--output-prefix", type=Path, default=DEFAULT_OUTPUT_PREFIX) | |
| parser.add_argument("--generation-csv", type=Path, default=DEFAULT_GENERATION_CSV) | |
| parser.add_argument("--generation-rows", type=int, default=0) | |
| parser.add_argument("--seed", type=int, default=0) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| train_labels = load_labels(args.train_h5) if args.use_h5_labels else load_labels_from_meta(args.train_meta) | |
| generation_labels = load_labels_from_meta(args.generation_meta) | |
| train_station_labels = np.unique(train_labels[:, 0].astype(np.int64)) | |
| if args.station_codes.exists(): | |
| station_frame = pd.read_csv(args.station_codes) | |
| known_station_count = station_frame["station_code"].nunique() | |
| else: | |
| known_station_count = None | |
| fig = build_figure(train_labels, generation_labels) | |
| args.output_prefix.parent.mkdir(parents=True, exist_ok=True) | |
| fig.savefig(f"{args.output_prefix}.png", dpi=300, bbox_inches="tight") | |
| fig.savefig(f"{args.output_prefix}.pdf", bbox_inches="tight") | |
| fig.savefig(f"{args.output_prefix}.svg", bbox_inches="tight") | |
| plt.close(fig) | |
| generation_csv = write_generation_csv(generation_labels, args.generation_csv, args.generation_rows, args.seed) | |
| summary = summarize(train_labels, generation_labels) | |
| summary.update( | |
| { | |
| "train_h5": str(args.train_h5), | |
| "train_meta": str(args.train_meta), | |
| "generation_meta": str(args.generation_meta), | |
| "label_source": "h5_labels" if args.use_h5_labels else "metadata_csv", | |
| "known_station_count": None if known_station_count is None else int(known_station_count), | |
| "observed_station_count": int(train_station_labels.shape[0]), | |
| "png": f"{args.output_prefix}.png", | |
| "pdf": f"{args.output_prefix}.pdf", | |
| "svg": f"{args.output_prefix}.svg", | |
| "generation_csv": str(generation_csv), | |
| "generation_rows": int(args.generation_rows), | |
| } | |
| ) | |
| summary_path = args.output_prefix.with_suffix(".summary.json") | |
| with open(summary_path, "w", encoding="utf-8") as fp: | |
| json.dump(summary, fp, ensure_ascii=False, indent=2) | |
| print(f"PNG: {args.output_prefix}.png") | |
| print(f"PDF: {args.output_prefix}.pdf") | |
| print(f"SVG: {args.output_prefix}.svg") | |
| print(f"Summary: {summary_path}") | |
| print(f"Generation CSV: {generation_csv}") | |
| if __name__ == "__main__": | |
| main() | |