"""PyTorch dataset over gnn_dataset/data//*.parquet. One sample = one MATSim scenario as a directed graph (nodes = network nodes, edges = links). The network is identical in every scenario (same node and link order), only edge attributes (closed / capacity_factor), population features and the targets change. from torch_dataset import GNNScenarioDataset ds = GNNScenarioDataset("/path/to/gnn_dataset") # data/ + manifest.parquet sample = ds[0] # torch_geometric.data.Data if PyG is installed, else dict sample.x [N, 4] node features: x, y (normalised), n_home, n_activity (persons, scaled to 100 %) sample.edge_index [2, E] from-node -> to-node (car links only by default) sample.edge_attr [E, 7] log_length, freespeed, log_capacity, lanes, closed, capacity_factor, capacity_eff sample.y [E, 24] target per link and hour (default: vc_ratio) sample.y_base [E, 24] same quantity in base_s0 (for delta losses); absent for baselines sample.scenario dict scenario.json (class, seeds, perturbation lists, sample_rate ...) sample.link_ids np.array of MATSim link ids (E,) with with_cells=True (default) additionally, from the demand tables: sample.cell_x [C, 12] cx, cy (normalised like x/y) + the 10 weighted cell counts (log1p) sample.cell_pos [C, 2] raw cell centres (EPSG:2056) sample.cell_link_index [2, M] (cell idx, edge idx) pairs within cell_link_max_dist (default: all, 5 km -> M = 57 M) sample.cell_link_dist [M] distance in m sample.od_index [2, K] (orig cell, dest cell) pairs with trips (cells inside the grid only) sample.od_trips [K, 3] all trips, car trips, AM-peak trips (weighted to 100 %) Requirements: numpy, pandas, pyarrow, torch. Optional: torch_geometric, scipy (nearest-node assignment of persons; without scipy the two population node features are zero). Targets available: "vc_ratio", "volume", "traveltime_avg", "congestion_index" (list allowed -> y is [E, 24 * len(targets)], stacked along dim 1). Missing (link, hour) rows in link_hourly.parquet mean volume 0 / vc 0 / congestion 1 / free-flow travel time (see README). """ import json import os import numpy as np import pandas as pd DEFAULTS = {"volume": 0.0, "vc_ratio": 0.0, "congestion_index": 1.0} EDGE_ATTR_NAMES = ["log_length", "freespeed", "log_capacity", "lanes", "closed", "capacity_factor", "capacity_eff"] NODE_ATTR_NAMES = ["x", "y", "n_home", "n_activity"] def _load_pyg(): try: from torch_geometric.data import Data # noqa: F401 return Data except Exception: return None class GNNScenarioDataset: """Indexable dataset; works as a torch.utils.data.Dataset (len/getitem).""" def __init__(self, root, ids=None, classes=None, targets="vc_ratio", car_only=True, baseline_id=None, with_baseline=True, clip_congestion=50.0, cache=True, as_pyg=True, with_cells=True, cell_link_max_dist=None): self.root = root self.data_dir = os.path.join(root, "data") self.targets = [targets] if isinstance(targets, str) else list(targets) self.car_only = car_only self.baseline_id = baseline_id self.with_baseline = with_baseline self.clip_congestion = clip_congestion self.cache = cache self.cache_dir = os.path.join(root, "cache_torch") self._pyg = _load_pyg() if as_pyg else None self.with_cells = with_cells and os.path.exists(os.path.join(root, "cell_link_edges.parquet")) self.cell_link_max_dist = cell_link_max_dist # e.g. 2000 -> only pairs within 2 km man_path = os.path.join(root, "manifest.parquet") if os.path.exists(man_path): man = pd.read_parquet(man_path) man = man[man.status == "ok"] else: # fall back to directory listing ids_ = sorted(d for d in os.listdir(self.data_dir) if os.path.exists(os.path.join(self.data_dir, d, "link_hourly.parquet"))) man = pd.DataFrame({"scenario_id": ids_, "class": [json.load(open(os.path.join(self.data_dir, d, "scenario.json")))["class"] for d in ids_]}) if classes is not None: man = man[man["class"].isin(list(classes))] if ids is not None: man = man[man.scenario_id.isin(list(ids))] self.ids = list(man.scenario_id) self.classes = dict(zip(man.scenario_id, man["class"])) if not self.ids: raise ValueError("no scenarios selected") if baseline_id is None: # v1: base_s0, v2: base10_s0 (first class-0 scenario) cands = sorted(d for d in os.listdir(self.data_dir) if d.startswith("base")) self.baseline_id = "base_s0" if "base_s0" in cands else cands[0] self._build_static() self._base_y = None self._cell_static = None # ------------------------------------------------------------------ static def _build_static(self): """Node table, edge index, node coordinate normalisation (from base).""" sdir = os.path.join(self.data_dir, self.baseline_id) nodes = pd.read_parquet(os.path.join(sdir, "nodes.parquet")) links = pd.read_parquet(os.path.join(sdir, "links.parquet")) if self.car_only: links = links[links.modes.str.contains(r"(?:^|,)car(?:,|$)")] self.link_ids = links.link_id.values.astype(str) self._link_mask_index = links.index.values # row positions in the full links table self._link_index = pd.Index(self.link_ids) nid = {n: i for i, n in enumerate(nodes.node_id.values)} self.edge_index = np.stack([links.from_node.map(nid).values, links.to_node.map(nid).values]).astype(np.int64) self.node_ids = nodes.node_id.values.astype(str) xy = nodes[["x", "y"]].values.astype(np.float64) self._xy_mean, self._xy_std = xy.mean(0), xy.std(0) self.node_xy = ((xy - self._xy_mean) / self._xy_std).astype(np.float32) self._raw_xy = xy self.link_pos = {l: i for i, l in enumerate(self.link_ids)} self._lengths = links.length.values.astype(np.float32) self._freespeed = links.freespeed.values.astype(np.float32) try: from scipy.spatial import cKDTree self._tree = cKDTree(xy) except Exception: self._tree = None # --------------------------------------------------------------- per scen def _edge_attr(self, links): m = self._link_mask_index col = lambda c: links[c].values[m] fs = np.minimum(col("freespeed"), 60.0) # inf on a few pt/ferry links cap = col("capacity") cf = col("capacity_factor") closed = col("closed").astype(np.float32) return np.stack([ np.log1p(col("length")), fs, np.log1p(cap), col("lanes"), closed, cf, np.where(closed > 0, 0.0, cap * cf), # effective capacity (0 if closed) ], axis=1).astype(np.float32) def _node_pop(self, persons, sample_rate): out = np.zeros((len(self.node_ids), 2), dtype=np.float32) if self._tree is None: return out w = 1.0 / sample_rate home = persons[["home_x", "home_y"]].dropna().values act = persons[["main_activity_x", "main_activity_y"]].dropna().values if len(home): _, i = self._tree.query(home) np.add.at(out[:, 0], i, w) if len(act): _, i = self._tree.query(act) np.add.at(out[:, 1], i, w) return out def _dense_targets(self, link_hourly): """sparse link_hourly -> [E, 24 * n_targets] dense array.""" pos = self._link_index.get_indexer(link_hourly.link_id.values) keep = pos >= 0 # drop pt-only links etc. pos = pos[keep] hour = link_hourly.hour.values[keep].astype(np.int64) blocks = [] for t in self.targets: if t == "traveltime_avg": default = (self._lengths / np.minimum(self._freespeed, 1e6))[:, None].repeat(24, 1) y = default.astype(np.float32) else: y = np.full((len(self.link_ids), 24), DEFAULTS[t], dtype=np.float32) vals = link_hourly[t].values[keep].astype(np.float32) if t == "congestion_index" and self.clip_congestion: vals = np.nan_to_num(np.minimum(vals, self.clip_congestion), nan=1.0) y[pos, hour] = vals blocks.append(y) return np.concatenate(blocks, axis=1) def _cache_path(self, sid): key = "_".join(self.targets) + ("_car" if self.car_only else "_all") return os.path.join(self.cache_dir, "%s__%s.npz" % (sid, key)) def _load_arrays(self, sid): cp = self._cache_path(sid) if self.cache and os.path.exists(cp): z = np.load(cp) if not self.with_cells or "cell_x" in z: return z["x"], z["edge_attr"], z["y"] sdir = os.path.join(self.data_dir, sid) spec = json.load(open(os.path.join(sdir, "scenario.json"))) links = pd.read_parquet(os.path.join(sdir, "links.parquet")) persons = pd.read_parquet(os.path.join(sdir, "persons.parquet")) lh = pd.read_parquet(os.path.join(sdir, "link_hourly.parquet")) x = np.concatenate([self.node_xy, self._node_pop(persons, spec["sample_rate"])], axis=1) ea = self._edge_attr(links) y = self._dense_targets(lh) extra = {} if self.with_cells: cell_x, cell_pos, od_index, od_trips = self._cell_arrays(sid) extra = dict(cell_x=cell_x, cell_pos=cell_pos, od_index=od_index, od_trips=od_trips) if self.cache: os.makedirs(self.cache_dir, exist_ok=True) np.savez_compressed(cp, x=x, edge_attr=ea, y=y, **extra) return x, ea, y def base_targets(self): if self._base_y is None: self._base_y = self._load_arrays(self.baseline_id)[2] return self._base_y # ---------------------------------------------------------------- cells CELL_COLS = ["residents", "residents_employed", "residents_car_available", "residents_age_0_17", "residents_age_18_64", "residents_age_65plus", "jobs", "edu_places", "trips_origin", "trips_dest"] def cell_static(self): """(cell idx, edge idx) pairs + distance within cell_link_max_dist (identical for all scenarios). First call reads the 59 M-row parquet via pyarrow and stores compact int32 arrays in cache_torch/; later calls take ~1 s.""" if self._cell_static is not None: return self._cell_static tag = "car" if self.car_only else "all" md = self.cell_link_max_dist cp = os.path.join(self.cache_dir, "cell_link_static_%s_%s.npz" % (tag, "all" if md is None else int(md))) if self.cache and os.path.exists(cp): z = np.load(cp) self._cell_static = (z["index"], z["dist"]) return self._cell_static import pyarrow.parquet as pq tb = pq.read_table(os.path.join(self.root, "cell_link_edges.parquet")) cells, pos, dist = [], [], [] for i in range(tb.num_columns and len(tb.column("link_id").chunks)): lc = tb.column("link_id").chunk(i) if hasattr(lc, "dictionary"): cat_pos = self._link_index.get_indexer(np.asarray(lc.dictionary).astype(str)) p_ = cat_pos[np.asarray(lc.indices)] else: p_ = self._link_index.get_indexer(np.asarray(lc).astype(str)) c_ = np.asarray(tb.column("cell_id").chunk(i)).astype(np.int32) d_ = np.asarray(tb.column("dist_m").chunk(i)).astype(np.float32) keep = p_ >= 0 if md is not None: keep &= d_ <= md cells.append(c_[keep]); pos.append(p_[keep].astype(np.int32)); dist.append(d_[keep]) index = np.stack([np.concatenate(cells), np.concatenate(pos)]) dist = np.concatenate(dist) if self.cache: os.makedirs(self.cache_dir, exist_ok=True) np.savez(cp, index=index, dist=dist) self._cell_static = (index, dist) return self._cell_static def _cell_arrays(self, sid): sdir = os.path.join(self.data_dir, sid) c = pd.read_parquet(os.path.join(sdir, "cells.parquet")) xy = c[["cx", "cy"]].values cell_x = np.concatenate([((xy - self._xy_mean) / self._xy_std), np.log1p(c[self.CELL_COLS].values)], axis=1).astype(np.float32) od = pd.read_parquet(os.path.join(sdir, "od_cells.parquet")) am = pd.read_parquet(os.path.join(sdir, "od_cells_am.parquet")) od = od[(od.orig_cell >= 0) & (od.dest_cell >= 0)] am = am[(am.orig_cell >= 0) & (am.dest_cell >= 0)] g = od.groupby(["orig_cell", "dest_cell"]) tot = g.trips.sum() car = od[od["mode"].astype(str) == "car"].groupby(["orig_cell", "dest_cell"]).trips.sum() amt = am.groupby(["orig_cell", "dest_cell"]).trips.sum() tab = pd.DataFrame({"all": tot, "car": car, "am": amt}).fillna(0.0) od_index = np.array(list(tab.index), dtype=np.int64).T.reshape(2, -1) return cell_x, xy.astype(np.float32), od_index, tab.values.astype(np.float32) # ------------------------------------------------------------------ API def __len__(self): return len(self.ids) def scenario(self, sid): return json.load(open(os.path.join(self.data_dir, sid, "scenario.json"))) def __getitem__(self, i): import torch sid = self.ids[i] x, ea, y = self._load_arrays(sid) spec = self.scenario(sid) d = { "x": torch.from_numpy(x), "edge_index": torch.from_numpy(self.edge_index), "edge_attr": torch.from_numpy(ea), "y": torch.from_numpy(y), "scenario_id": sid, "scenario_class": int(spec["class"]), } if self.with_baseline and sid != self.baseline_id: d["y_base"] = torch.from_numpy(self.base_targets()) if self.with_cells: z = np.load(self._cache_path(sid)) if self.cache else None if z is not None and "cell_x" in z: cell_x, cell_pos, od_index, od_trips = z["cell_x"], z["cell_pos"], z["od_index"], z["od_trips"] else: cell_x, cell_pos, od_index, od_trips = self._cell_arrays(sid) cli, cld = self.cell_static() d.update(cell_x=torch.from_numpy(cell_x), cell_pos=torch.from_numpy(cell_pos), cell_link_index=torch.from_numpy(cli.astype(np.int64)), cell_link_dist=torch.from_numpy(cld), od_index=torch.from_numpy(od_index), od_trips=torch.from_numpy(od_trips)) if self._pyg is not None: data = self._pyg(x=d["x"], edge_index=d["edge_index"], edge_attr=d["edge_attr"], y=d["y"]) if "y_base" in d: data.y_base = d["y_base"] for k in ("cell_x", "cell_pos", "cell_link_index", "cell_link_dist", "od_index", "od_trips"): if k in d: setattr(data, k, d[k]) data.scenario_id = sid data.scenario_class = d["scenario_class"] data.scenario = spec data.link_ids = self.link_ids return data d["scenario"] = spec d["link_ids"] = self.link_ids return d def split(self, val_frac=0.15, test_frac=0.15, seed=0): """Scenario-level split, stratified by class; returns three index lists.""" rng = np.random.default_rng(seed) tr, va, te = [], [], [] by_class = {} for i, sid in enumerate(self.ids): by_class.setdefault(self.classes[sid], []).append(i) for k, idx in by_class.items(): idx = list(rng.permutation(idx)) n_te = int(round(len(idx) * test_frac)) n_va = int(round(len(idx) * val_frac)) te += idx[:n_te] va += idx[n_te:n_te + n_va] tr += idx[n_te + n_va:] return sorted(tr), sorted(va), sorted(te) def build_cache(self, verbose=True): """Precompute every scenario's arrays once (numpy only, no torch needed).""" for k, sid in enumerate(self.ids): self._load_arrays(sid) if verbose and (k % 10 == 0 or k == len(self.ids) - 1): print("cached %d/%d" % (k + 1, len(self.ids))) if __name__ == "__main__": import sys root = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__)) ds = GNNScenarioDataset(root, as_pyg=False) print("scenarios:", len(ds), "| nodes:", len(ds.node_ids), "| edges:", ds.edge_index.shape[1]) x, ea, y = ds._load_arrays(ds.ids[0]) print("x", x.shape, "edge_attr", ea.shape, "y", y.shape) if "--cache" in sys.argv: ds.build_cache()