File size: 4,428 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
"""
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")


@dataclass(frozen=True)
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 -------------------------------------------------------
    @property
    def x(self) -> np.ndarray:
        """First state variable, shape (T, N)."""
        return self.states[:, :, 0]

    @property
    def y(self) -> np.ndarray:
        """Second state variable, shape (T, N); raises if the dataset is 1-D."""
        return self.states[:, :, 1]

    @property
    def z(self) -> np.ndarray:
        """Third state variable, shape (T, N); raises if the dataset is 2-D."""
        return self.states[:, :, 2]

    @property
    def n_nodes(self) -> int:
        return self.states.shape[1]

    @property
    def n_steps(self) -> int:
        return self.states.shape[0]

    @property
    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}")