Download scripts/preprocess.py from tczzx6/SAGEdata: direct link, hf CLI and curl.
- Browser
- Download file 4.89 kB
-
https://huggingface.co/datasets/tczzx6/SAGEdata/resolve/main/scripts/preprocess.py
- Command line
-
hf download hf://datasets/tczzx6/SAGEdata/scripts/preprocess.py
-
curl -L -o preprocess.py https://huggingface.co/datasets/tczzx6/SAGEdata/resolve/main/scripts/preprocess.py
4.89 kB
| """ | |
| Reference preprocessing for the SAGE real-world network dataset release. | |
| The release ships *raw observational states* only. This script reproduces the | |
| preprocessing the SAGE pipeline applies before equation discovery: | |
| 1. optional temporal aggregation (mean-pooling over `resample` steps) | |
| 2. Savitzky-Golay smoothing (preserves higher-order moments) | |
| 3. temporal derivatives (analytic derivative of the SG fit) | |
| 4. train / validation / test split (blocked, time-ordered) | |
| Split ratios follow the paper: 60 / 20 / 20, always contiguous in time -- never | |
| shuffled -- because temporal order is what makes derivative estimation valid. | |
| python preprocess.py # all datasets, paper settings | |
| python preprocess.py --dataset power_grid # one dataset | |
| python preprocess.py --no-smooth --no-derivative | |
| Dependencies: numpy, scipy. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import numpy as np | |
| from scipy.signal import savgol_filter | |
| from load_dataset import AVAILABLE, load | |
| # Per-dataset SG settings used in the paper. sg_window is in samples and must be | |
| # odd; sg_order is the local polynomial degree. | |
| SAVGOL = { | |
| "urban_mobile_communication": dict(window=7, order=2, resample=6), | |
| "brain_eeg": dict(window=7, order=2, resample=1), | |
| "power_grid": dict(window=5, order=2, resample=1), | |
| "urban_rail_transit": dict(window=7, order=2, resample=1), | |
| } | |
| SPLIT = (0.6, 0.2, 0.2) | |
| def _odd(n: int) -> int: | |
| return n if n % 2 == 1 else n + 1 | |
| def aggregate(states: np.ndarray, window: int, dt: float) -> tuple[np.ndarray, float]: | |
| """Mean-pool `states` (T, N, D) over `window` consecutive samples.""" | |
| if window <= 1: | |
| return states, dt | |
| t, n, d = states.shape | |
| usable = (t // window) * window | |
| pooled = states[:usable].reshape(usable // window, window, n, d).mean(axis=1) | |
| return pooled, dt * window | |
| def smooth(states: np.ndarray, window: int, order: int) -> np.ndarray: | |
| """Savitzky-Golay filter along the time axis of (T, N, D) data.""" | |
| window = min(_odd(window), states.shape[0] - 1) | |
| return savgol_filter(states, window_length=window, polyorder=order, axis=0) | |
| def derivative(states: np.ndarray, window: int, order: int, dt: float) -> np.ndarray: | |
| """Analytic derivative of the Savitzky-Golay fit, per unit time.""" | |
| window = min(_odd(window), states.shape[0] - 1) | |
| return savgol_filter( | |
| states, window_length=window, polyorder=order, deriv=1, delta=dt, axis=0 | |
| ) | |
| def split_indices(t: int, ratios: tuple[float, float, float] = SPLIT): | |
| """Blocked, time-ordered train/val/test index arrays.""" | |
| train = int(ratios[0] * t) | |
| val = int(ratios[1] * t) | |
| return ( | |
| np.arange(0, train), | |
| np.arange(train, train + val), | |
| np.arange(train + val, t), | |
| ) | |
| def prepare(name: str, do_smooth: bool = True, do_derivative: bool = True) -> dict: | |
| """Run the full preprocessing chain for one dataset.""" | |
| ds = load(name) | |
| cfg = SAVGOL[name] | |
| raw_dt = _dt_seconds(ds.metadata.get("dt", "1")) | |
| states, dt = aggregate(ds.states, cfg["resample"], raw_dt) | |
| dxdt = None | |
| if do_smooth: | |
| states = smooth(states, cfg["window"], cfg["order"]) | |
| if do_derivative: | |
| dxdt = derivative(states, cfg["window"], cfg["order"], dt) | |
| train, val, test = split_indices(states.shape[0]) | |
| return dict( | |
| name=name, states=states, dxdt=dxdt, dt=dt, | |
| adj=ds.adj, community=ds.community, | |
| train=train, val=val, test=test, | |
| ) | |
| def _dt_seconds(text: str) -> float: | |
| """Best-effort parse of the free-text `dt` field into seconds.""" | |
| head = text.split("(")[0].split(";")[0].strip() | |
| parts = head.split() | |
| if not parts: | |
| return 1.0 | |
| try: | |
| value = float(parts[0]) | |
| except ValueError: | |
| return 1.0 | |
| unit = parts[1].lower() if len(parts) > 1 else "s" | |
| return value * {"s": 1.0, "min": 60.0, "h": 3600.0}.get(unit, 1.0) | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n")[1]) | |
| ap.add_argument("--dataset", choices=AVAILABLE, default=None) | |
| ap.add_argument("--no-smooth", action="store_true") | |
| ap.add_argument("--no-derivative", action="store_true") | |
| args = ap.parse_args() | |
| names = [args.dataset] if args.dataset else list(AVAILABLE) | |
| for name in names: | |
| out = prepare(name, not args.no_smooth, not args.no_derivative) | |
| s = out["states"] | |
| shape = " x ".join(str(v) for v in (s.shape[0], s.shape[1], s.shape[2])) | |
| line = f"{name:28s} T x N x D = {shape:>16s} dt={out['dt']:g}s" | |
| if out["dxdt"] is not None: | |
| line += f" |dx/dt| mean = {np.abs(out['dxdt']).mean():.4g}" | |
| line += (f" split {len(out['train'])}/{len(out['val'])}/{len(out['test'])}") | |
| print(line) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |