File size: 4,887 Bytes
5413623 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | """
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())
|