Download scripts/build_release.py from tczzx6/SAGEdata: direct link, hf CLI and curl.
- Browser
- Download file 19.1 kB
-
https://huggingface.co/datasets/tczzx6/SAGEdata/resolve/main/scripts/build_release.py
- Command line
-
hf download hf://datasets/tczzx6/SAGEdata/scripts/build_release.py
-
curl -L -o build_release.py https://huggingface.co/datasets/tczzx6/SAGEdata/resolve/main/scripts/build_release.py
19.1 kB
| """ | |
| Build the SAGE open-source dataset release from the local working copies. | |
| Reads the four real-world networks used in | |
| "Discovering hierarchical governing equations for community-structured | |
| complex network dynamics" (SAGE framework) | |
| and re-emits them in one unified, paper-release layout: | |
| data/<dataset>/ | |
| x.csv [y.csv] [z.csv] states, shape (T, N), headerless | |
| adj.csv adjacency, shape (N, N), integer 0/1 | |
| community.csv node,community (N rows + header) | |
| metadata.json machine-readable description | |
| README.md human-readable description | |
| State values are copied token-for-token from the sources so that no | |
| floating-point precision is lost or introduced. | |
| Usage: | |
| python build_release.py | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import json | |
| import os | |
| import shutil | |
| import sys | |
| from collections import Counter | |
| # -------------------------------------------------------------------------- | |
| # Paths | |
| # -------------------------------------------------------------------------- | |
| DESKTOP = os.path.join(os.path.expanduser("~"), "Desktop") | |
| PIPELINE = os.path.join(DESKTOP, "agent动力学发现", "实验", "动力学方程发现流程") | |
| SRC_DATA = os.path.join(PIPELINE, "数据集") | |
| SRC_TRAFFIC = os.path.join(os.path.expanduser("~"), "Downloads", "真实交通数据集.zip") | |
| SRC_TRAFFIC_EXTRACTED = os.path.join( | |
| os.path.dirname(os.path.abspath(__file__)), "_traffic_src" | |
| ) | |
| OUT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| OUT_DATA = os.path.join(OUT, "data") | |
| # -------------------------------------------------------------------------- | |
| # Low-level helpers | |
| # -------------------------------------------------------------------------- | |
| def read_tokens(path: str, delimiter: str = ",") -> list[list[str]]: | |
| """Read a headerless CSV as raw string tokens.""" | |
| with open(path, newline="", encoding="utf-8-sig") as fh: | |
| return [row for row in csv.reader(fh, delimiter=delimiter) if row] | |
| def write_tokens(path: str, rows: list[list[str]]) -> None: | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", newline="", encoding="utf-8") as fh: | |
| csv.writer(fh, lineterminator="\n").writerows(rows) | |
| def write_states(path: str, rows: list[list[str]]) -> tuple[int, int]: | |
| """Write a (T, N) state matrix, normalising numeric tokens.""" | |
| out = [[_norm_token(tok) for tok in row] for row in rows] | |
| write_tokens(path, out) | |
| return len(out), len(out[0]) | |
| def transpose(rows: list[list[str]]) -> list[list[str]]: | |
| return [list(col) for col in zip(*rows)] | |
| def _norm_token(tok: str) -> str: | |
| """Keep the source value but drop redundant trailing zeros / -0.0.""" | |
| tok = tok.strip() | |
| if tok in ("", "nan", "NaN", "None"): | |
| return "nan" | |
| try: | |
| val = float(tok) | |
| except ValueError: | |
| return tok | |
| if val == int(val) and abs(val) < 1e15: | |
| return str(int(val)) | |
| return repr(val) | |
| def write_adjacency(path: str, rows: list[list[str]]) -> tuple[int, int]: | |
| n = len(rows) | |
| if any(len(r) != n for r in rows): | |
| raise ValueError(f"{path}: adjacency is not square ({n} rows)") | |
| out = [[str(int(float(v))) for v in row] for row in rows] | |
| write_tokens(path, out) | |
| return n, n | |
| def normalise_community(raw: list[list[str]]) -> list[int]: | |
| """Accept either (node, community) rows or a K-column one-hot block.""" | |
| if raw and len(raw[0]) == 2: | |
| first = raw[0][0].strip().lower() | |
| body = raw[1:] if first in ("node", "node_id", "id") else raw | |
| labels = [int(float(r[1])) for r in body] | |
| else: | |
| labels = [] | |
| for row in raw: | |
| vals = [float(v) for v in row] | |
| labels.append(max(range(len(vals)), key=vals.__getitem__)) | |
| # Sources already use dense 0..K-1 labels; keep them untouched so that users | |
| # can compare against the original files. Only remap if the labels are not | |
| # already dense, and then preserve order of first appearance. | |
| distinct = sorted(set(labels)) | |
| if distinct == list(range(len(distinct))): | |
| return labels | |
| seen: dict[int, int] = {} | |
| for lab in labels: | |
| if lab not in seen: | |
| seen[lab] = len(seen) | |
| print(f" note: remapped community labels {distinct} -> 0..{len(seen) - 1}") | |
| return [seen[lab] for lab in labels] | |
| def write_community(path: str, labels: list[int]) -> Counter: | |
| body = [["node", "community"]] + [[str(i), str(l)] for i, l in enumerate(labels)] | |
| write_tokens(path, body) | |
| return Counter(labels) | |
| def find_source_dir(root: str, *required: str) -> str | None: | |
| """Return the first directory under `root` that holds all `required` files.""" | |
| for dirpath, _dirnames, filenames in os.walk(root): | |
| if all(name in filenames for name in required): | |
| return dirpath | |
| return None | |
| def write_metadata(path: str, meta: dict) -> None: | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", encoding="utf-8") as fh: | |
| json.dump(meta, fh, indent=2, ensure_ascii=False) | |
| fh.write("\n") | |
| README_TEMPLATE = """# {title} | |
| `{slug}` -- one of the four real-world community-structured networks in | |
| **Discovering hierarchical governing equations for community-structured complex | |
| network dynamics** (SAGE framework). | |
| ## Files | |
| | File | Shape | Description | | |
| |------|-------|-------------| | |
| {file_rows} | |
| `T` = time steps, `N` = nodes. State files are headerless CSV; row `t` is the | |
| state of all `N` nodes at time step `t`, and column `i` is the full trajectory of | |
| node `i`. | |
| ## At a glance | |
| | Property | Value | | |
| |----------|-------| | |
| | Nodes `N` | {N} | | |
| | Time steps `T` | {T} | | |
| | State variables `D` | {D} | | |
| | Time step `dt` | {dt} | | |
| | Communities `K` | {K} | | |
| | Community sizes | {community_sizes} | | |
| | Adjacency | {adjacency} | | |
| {derivative_row} | |
| ## Provenance | |
| {source} | |
| {citation} | |
| ## Reading the data | |
| ```python | |
| import sys; sys.path.insert(0, "scripts") | |
| from load_dataset import load | |
| ds = load("{slug}") | |
| print(ds) # <Dataset '{slug}' T={T} N={N} D={D} K={K}> | |
| print(ds.x.shape, ds.adj.shape, ds.community.shape) | |
| ``` | |
| The release ships raw observational states only. To reproduce the Savitzky-Golay | |
| smoothing, derivative estimation and 60/20/20 blocked time split used in the | |
| paper, run: | |
| ```bash | |
| python scripts/preprocess.py --dataset {slug} | |
| ``` | |
| """ | |
| # -------------------------------------------------------------------------- | |
| # Dataset builders | |
| # -------------------------------------------------------------------------- | |
| def _reflow(text: str) -> str: | |
| """Collapse source-code indentation in a prose block, keeping blank lines.""" | |
| return "\n\n".join( | |
| para for para in (" ".join(line.strip() for line in chunk.splitlines()).strip() | |
| for chunk in text.strip().split("\n\n")) | |
| if para | |
| ) + "\n" | |
| def write_readme(path: str, info: dict) -> None: | |
| file_rows = "".join( | |
| f"| `{key}.csv` | `(T, N)` | {desc} |\n" | |
| for key, desc in info["variables"].items() | |
| if f"{key}.csv" in info["state_files"] | |
| ) | |
| file_rows += ( | |
| "| `adj.csv` | `(N, N)` | Adjacency matrix, 0/1 integers, zero diagonal |\n" | |
| "| `community.csv` | `(N, 2)` | `node,community` -- community label per node, as in the source data |\n" | |
| "| `metadata.json` | -- | Machine-readable description of this dataset |\n" | |
| ) | |
| fields = dict(info) | |
| fields["community_sizes"] = ", ".join(str(s) for s in info["community_sizes"]) | |
| fields["file_rows"] = file_rows | |
| fields["derivative_row"] = ( | |
| f"| Derivative note | {info['derivative']} |\n" if "derivative" in info else "" | |
| ) | |
| # Re-flow the multi-line source/citation blocks so they render as clean | |
| # paragraphs without the indentation used in the Python source. | |
| fields["source"] = _reflow(info["source"]) | |
| fields["citation"] = _reflow(info["citation"]) | |
| text = README_TEMPLATE.format(**fields) | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", encoding="utf-8") as fh: | |
| fh.write(text) | |
| def build_mobile_comms() -> dict: | |
| src = os.path.join(SRC_DATA, "real_mobile_comms") | |
| dst = os.path.join(OUT_DATA, "urban_mobile_communication") | |
| os.makedirs(dst, exist_ok=True) | |
| shapes = {} | |
| for var in ("x", "y", "z"): | |
| shapes[var] = write_states( | |
| os.path.join(dst, f"{var}.csv"), read_tokens(os.path.join(src, f"{var}.csv")) | |
| ) | |
| n, _ = write_adjacency(os.path.join(dst, "adj.csv"), | |
| read_tokens(os.path.join(src, "adj.csv"))) | |
| sizes = write_community(os.path.join(dst, "community.csv"), | |
| normalise_community(read_tokens(os.path.join(src, "community.csv")))) | |
| t = shapes["x"][0] | |
| return dict( | |
| slug="urban_mobile_communication", | |
| title="Urban mobile communication network", | |
| shape=f"{t} x {n} x 3", | |
| T=t, N=n, D=3, K=len(sizes), | |
| community_sizes=[sizes[k] for k in sorted(sizes)], | |
| variables={"x": "Internet activity", "y": "Phone-call activity", "z": "SMS activity"}, | |
| dt="10 min (native); aggregated to 60 min (6-step mean) in the paper", | |
| adjacency="Four-neighbour spatial grid on the Milan 100x100 raster", | |
| source="Telecom Italia Big Data Challenge, Milan, 1-7 November 2013. The " | |
| "three state variables are the Internet, call and SMS activity of " | |
| "each grid cell, already normalised per cell by the data provider. " | |
| "The paper aggregated the native 10-minute samples to 60-minute " | |
| "resolution (mean over 6 steps), giving 168 time steps.", | |
| citation="Barlacchi, G. et al. A multi-source dataset of urban life in the " | |
| "city of Milan and the Province of Trentino. Sci. Data 2, 150055 " | |
| "(2015). https://doi.org/10.1038/sdata.2015.55\n " | |
| "Source portal: https://dataverse.harvard.edu/dataverse/BigDataChallenge", | |
| ) | |
| def build_eeg() -> dict: | |
| src = os.path.join(SRC_DATA, "real_brain_eeg") | |
| dst = os.path.join(OUT_DATA, "brain_eeg") | |
| os.makedirs(dst, exist_ok=True) | |
| # The '2' variants are the 64-channel / 2440-step / 5-community release used | |
| # in the paper (Supplementary Section 3.2); the un-suffixed files are an | |
| # earlier 610-step / 8-community draft and are not part of the release. | |
| shapes = {} | |
| for var, srcfile in (("x", "x2.csv"), ("y", "y2.csv")): | |
| shapes[var] = write_states( | |
| os.path.join(dst, f"{var}.csv"), read_tokens(os.path.join(src, srcfile)) | |
| ) | |
| n, _ = write_adjacency(os.path.join(dst, "adj.csv"), | |
| read_tokens(os.path.join(src, "adj2.csv"))) | |
| sizes = write_community(os.path.join(dst, "community.csv"), | |
| normalise_community(read_tokens(os.path.join(src, "community2.csv")))) | |
| t = shapes["x"][0] | |
| return dict( | |
| slug="brain_eeg", | |
| title="Brain EEG network", | |
| shape=f"{t} x {n} x 2", | |
| T=t, N=n, D=2, K=len(sizes), | |
| community_sizes=[sizes[k] for k in sorted(sizes)], | |
| variables={"x": "Hilbert analytic amplitude", "y": "Hilbert quadrature component"}, | |
| dt="0.00625 s (160 Hz sampling rate)", | |
| adjacency="Channel co-activation graph, 806 directed entries", | |
| source="PhysioNet EEG Motor Movement/Imagery Dataset (EEGMMIDB), record " | |
| "S001R01, 64 channels. Signals were band-pass filtered at 1-20 Hz " | |
| "and re-referenced with common average referencing (CAR). Each " | |
| "channel was then converted to an analytic signal by the Hilbert " | |
| "transform, giving the two state variables released here: the " | |
| "amplitude component (x) and the quadrature component (y). The 64 " | |
| "channels are grouped into five dynamical communities.", | |
| citation="Schalk, G., McFarland, D. J., Hinterberger, T., Birbaumer, N. & " | |
| "Wolpaw, J. R. BCI2000: a general-purpose brain-computer " | |
| "interface (BCI) system. IEEE Trans. Biomed. Eng. 51, 1034-1043 " | |
| "(2004).\n PhysioNet: https://physionet.org/content/eegmmidb/1.0.0/", | |
| ) | |
| def build_power_grid() -> dict: | |
| src = os.path.join(SRC_DATA, "power_grid_rerun") | |
| dst = os.path.join(OUT_DATA, "power_grid") | |
| os.makedirs(dst, exist_ok=True) | |
| # Supplementary Section 3.3 describes a single state variable per bus. The | |
| # working copy additionally holds y.csv, but y is not an independent | |
| # observation: it equals the central-difference derivative of x to float32 | |
| # precision (max relative residual 4.7e-8). It is therefore not released as a | |
| # state variable; the derivative recipe is recorded in metadata instead. | |
| shapes = {} | |
| for var in ("x",): | |
| shapes[var] = write_states( | |
| os.path.join(dst, f"{var}.csv"), read_tokens(os.path.join(src, f"{var}.csv")) | |
| ) | |
| n, _ = write_adjacency(os.path.join(dst, "adj.csv"), | |
| read_tokens(os.path.join(src, "adj.csv"))) | |
| sizes = write_community(os.path.join(dst, "community.csv"), | |
| normalise_community(read_tokens(os.path.join(src, "community.csv")))) | |
| t = shapes["x"][0] | |
| return dict( | |
| slug="power_grid", | |
| title="Power grid network (IEEE 39-bus New England)", | |
| shape=f"{t} x {n} x 1", | |
| T=t, N=n, D=1, K=len(sizes), | |
| community_sizes=[sizes[k] for k in sorted(sizes)], | |
| variables={"x": "Bus phase angle (rotor-angle state)"}, | |
| derivative="np.gradient(x, axis=0) / 0.01 reproduces the working copy's " | |
| "y.csv exactly (verified to float32 precision). It is a derived " | |
| "quantity, not a second state variable, so it is not shipped.", | |
| dt="0.01 s", | |
| adjacency="Physical transmission-line topology, 0/1", | |
| source="IEEE 39-bus New England test system, 39 buses treated as nodes. " | |
| "Buses are connected when directly linked by a transmission line. " | |
| "Each bus carries a single state variable, the phase angle (x); " | |
| "this matches the single-state-variable description in " | |
| "Supplementary Section 3.3. The buses fall into three dynamical " | |
| "communities of 13 each.", | |
| citation="Athay, T., Podmore, R. & Virmani, S. A practical method for the " | |
| "direct analysis of transient stability. IEEE Trans. Power " | |
| "Appar. Syst. PAS-98, 573-584 (1979).", | |
| ) | |
| def build_rail_transit() -> dict: | |
| dst = os.path.join(OUT_DATA, "urban_rail_transit") | |
| os.makedirs(dst, exist_ok=True) | |
| # The archive was authored on macOS and stores Chinese entry names without | |
| # the UTF-8 flag, so the extracted folder name differs by platform. Locate | |
| # the source files by walking the tree rather than by assuming a name. | |
| src = find_source_dir(SRC_TRAFFIC_EXTRACTED, "in_15min.csv", "out_15min.csv") | |
| if src is None: | |
| raise FileNotFoundError( | |
| f"Traffic sources not found under {SRC_TRAFFIC_EXTRACTED}. " | |
| f"Extract {SRC_TRAFFIC} into that directory first." | |
| ) | |
| # Source layout is (N, T); the release layout is (T, N). | |
| shapes = {} | |
| for var, srcfile in (("x", "in_15min.csv"), ("y", "out_15min.csv")): | |
| rows = transpose(read_tokens(os.path.join(src, srcfile))) | |
| shapes[var] = write_states(os.path.join(dst, f"{var}.csv"), rows) | |
| n, _ = write_adjacency(os.path.join(dst, "adj.csv"), | |
| read_tokens(os.path.join(src, "adj.csv"))) | |
| sizes = write_community(os.path.join(dst, "community.csv"), | |
| normalise_community(read_tokens(os.path.join(src, "group.csv")))) | |
| t = shapes["x"][0] | |
| return dict( | |
| slug="urban_rail_transit", | |
| title="Urban rail transit network (Beijing)", | |
| shape=f"{t} x {n} x 2", | |
| T=t, N=n, D=2, K=len(sizes), | |
| community_sizes=[sizes[k] for k in sorted(sizes)], | |
| variables={"x": "Station passenger inflow (boarding)", | |
| "y": "Station passenger outflow (alighting)"}, | |
| dt="15 min", | |
| adjacency="Physical rail-network connectivity between stations, 0/1", | |
| source="Beijing urban rail transit passenger-flow dataset, collected from " | |
| "the Automatic Fare Collection (AFC) system between 05:00 and 23:00 " | |
| "on the 25 weekdays within 29 February - 3 April 2016 (five " | |
| "consecutive weeks; 25 x 18 h x 4 = 1800 steps), covering 17 lines " | |
| "and 276 stations. Weekends are not included. The two state " | |
| "variables are the passenger inflow (boarding, x) and outflow " | |
| "(alighting, y) of each station. The released file was aggregated " | |
| "to 15-minute resolution; values are raw passenger counts. The 276 " | |
| "stations are grouped into eight communities.", | |
| citation="Zhang, J. et al. Deep learning architecture for short-term " | |
| "passenger flow forecasting in urban rail transit. IEEE Trans. " | |
| "Intell. Transp. Syst. 22, 7004-7014 (2021).", | |
| ) | |
| BUILDERS = { | |
| "urban_mobile_communication": build_mobile_comms, | |
| "brain_eeg": build_eeg, | |
| "power_grid": build_power_grid, | |
| "urban_rail_transit": build_rail_transit, | |
| } | |
| # -------------------------------------------------------------------------- | |
| # Entry point | |
| # -------------------------------------------------------------------------- | |
| def main() -> int: | |
| if not os.path.isdir(SRC_TRAFFIC_EXTRACTED): | |
| if os.path.exists(SRC_TRAFFIC): | |
| import zipfile | |
| zf = zipfile.ZipFile(SRC_TRAFFIC) | |
| zf.extractall(SRC_TRAFFIC_EXTRACTED) | |
| zf.close() | |
| else: | |
| print(f"WARNING: traffic archive not found at {SRC_TRAFFIC}", file=sys.stderr) | |
| summary = {} | |
| for slug, builder in BUILDERS.items(): | |
| # Rebuild from scratch so that files dropped from a dataset (e.g. a | |
| # derived array no longer classified as a state) do not linger. | |
| shutil.rmtree(os.path.join(OUT_DATA, slug), ignore_errors=True) | |
| info = builder() | |
| info["state_files"] = [ | |
| f"{key}.csv" for key in ("x", "y", "z") | |
| if os.path.exists(os.path.join(OUT_DATA, slug, f"{key}.csv")) | |
| ] | |
| write_metadata(os.path.join(OUT_DATA, slug, "metadata.json"), info) | |
| write_readme(os.path.join(OUT_DATA, slug, "README.md"), info) | |
| summary[slug] = info | |
| print(f"[ok] {slug:28s} {info['shape']:>18s} K={info['K']}") | |
| manifest = os.path.join(OUT_DATA, "manifest.json") | |
| write_metadata(manifest, { | |
| "release": "SAGE real-world network dataset release", | |
| "datasets": list(summary.values()), | |
| }) | |
| print(f"\nWrote {len(summary)} datasets to {OUT_DATA}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |