File size: 19,054 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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | """
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())
|