Download scripts/load_dataset.py from tczzx6/SAGEdata: direct link, hf CLI and curl.
- Browser
- Download file 4.43 kB
-
https://huggingface.co/datasets/tczzx6/SAGEdata/resolve/main/scripts/load_dataset.py
- Command line
-
hf download hf://datasets/tczzx6/SAGEdata/scripts/load_dataset.py
-
curl -L -o load_dataset.py https://huggingface.co/datasets/tczzx6/SAGEdata/resolve/main/scripts/load_dataset.py
4.43 kB
| """ | |
| Unified loader for the SAGE real-world network dataset release. | |
| Every dataset in `data/` follows the same on-disk layout: | |
| <dataset>/x.csv [y.csv] [z.csv] states, shape (T, N), no header | |
| <dataset>/adj.csv adjacency, shape (N, N), 0/1 integers | |
| <dataset>/community.csv `node,community`, N rows + header | |
| <dataset>/metadata.json machine-readable description | |
| This module turns that layout into in-memory arrays. | |
| >>> from load_dataset import load | |
| >>> ds = load("power_grid") | |
| >>> ds.states.shape, ds.adj.shape, ds.community.shape | |
| ((5000, 39, 2), (39, 39), (39,)) | |
| Dependencies: numpy only. | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| import os | |
| from dataclasses import dataclass, field | |
| import numpy as np | |
| DATA_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data") | |
| AVAILABLE = ("urban_mobile_communication", "brain_eeg", "power_grid", "urban_rail_transit") | |
| class Dataset: | |
| """One network: states, structure, community labels, and provenance.""" | |
| name: str | |
| states: np.ndarray # (T, N, D) float64 | |
| adj: np.ndarray # (N, N) int64, 0/1, zero diagonal | |
| community: np.ndarray # (N,) int64, labels in 0..K-1 | |
| metadata: dict = field(default_factory=dict) | |
| # -- convenience ------------------------------------------------------- | |
| def x(self) -> np.ndarray: | |
| """First state variable, shape (T, N).""" | |
| return self.states[:, :, 0] | |
| def y(self) -> np.ndarray: | |
| """Second state variable, shape (T, N); raises if the dataset is 1-D.""" | |
| return self.states[:, :, 1] | |
| def z(self) -> np.ndarray: | |
| """Third state variable, shape (T, N); raises if the dataset is 2-D.""" | |
| return self.states[:, :, 2] | |
| def n_nodes(self) -> int: | |
| return self.states.shape[1] | |
| def n_steps(self) -> int: | |
| return self.states.shape[0] | |
| def n_communities(self) -> int: | |
| return int(self.community.max()) + 1 | |
| def community_indices(self, k: int) -> np.ndarray: | |
| """Node indices belonging to community `k`.""" | |
| return np.flatnonzero(self.community == k) | |
| def __repr__(self) -> str: | |
| return (f"<Dataset {self.name!r} T={self.n_steps} N={self.n_nodes} " | |
| f"D={self.states.shape[2]} K={self.n_communities}>") | |
| def load(name: str, root: str = DATA_ROOT) -> Dataset: | |
| """Load one dataset by slug. See `AVAILABLE` for valid names.""" | |
| if name not in AVAILABLE: | |
| raise ValueError(f"unknown dataset {name!r}; expected one of {AVAILABLE}") | |
| base = os.path.join(root, name) | |
| with open(os.path.join(base, "metadata.json"), encoding="utf-8") as fh: | |
| metadata = json.load(fh) | |
| planes = [] | |
| for key in ("x", "y", "z"): | |
| path = os.path.join(base, f"{key}.csv") | |
| if os.path.exists(path): | |
| planes.append(np.loadtxt(path, delimiter=",", dtype=np.float64)) | |
| if not planes: | |
| raise FileNotFoundError(f"{base}: no state files found") | |
| states = np.stack(planes, axis=-1) # (T, N, D) | |
| adj = np.loadtxt(os.path.join(base, "adj.csv"), delimiter=",", dtype=np.int64) | |
| community = _read_community(os.path.join(base, "community.csv")) | |
| if adj.shape[0] != adj.shape[1]: | |
| raise ValueError(f"{name}: adjacency is not square ({adj.shape})") | |
| if adj.shape[0] != states.shape[1]: | |
| raise ValueError( | |
| f"{name}: adjacency {adj.shape} does not match N={states.shape[1]}" | |
| ) | |
| if community.shape[0] != states.shape[1]: | |
| raise ValueError( | |
| f"{name}: {community.shape[0]} community labels for N={states.shape[1]}" | |
| ) | |
| return Dataset(name=name, states=states, adj=adj, community=community, metadata=metadata) | |
| def _read_community(path: str) -> np.ndarray: | |
| with open(path, newline="", encoding="utf-8") as fh: | |
| rows = list(csv.reader(fh)) | |
| if rows and rows[0][0].strip().lower() in ("node", "node_id", "id"): | |
| rows = rows[1:] | |
| return np.asarray([int(r[1]) for r in rows], dtype=np.int64) | |
| def load_all(root: str = DATA_ROOT) -> dict[str, Dataset]: | |
| return {name: load(name, root) for name in AVAILABLE} | |
| if __name__ == "__main__": | |
| for slug, ds in load_all().items(): | |
| print(f"{slug:28s} {ds!r}") | |