File size: 9,977 Bytes
6582381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69fd52a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6582381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69fd52a
 
 
 
 
 
 
 
6582381
 
 
 
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
---
license: cc-by-4.0
pretty_name: MATSim Zurich GNN surrogate dataset
tags: [transportation, matsim, graph, gnn, traffic-simulation]
---
# gnn_dataset — MATSim training data for a GNN surrogate (Zurich cutout)

Runs many MATSim scenarios on Euler and stores per scenario a compact dataset
(population, network, hourly link loads) as parquet. Nothing in the pipeline
itself is modified; everything lives in this directory.

## How it works

1. **Base (once)** — `sbatch sbatch/build_base.sbatch`
   runs the eqasim pipeline up to `matsim.cutter.run` at **2 %** (a generated
   copy of `config.yml`, the original is untouched), cuts the canton of Zurich
   (`extent/zurich_canton.shp`, built from swissBOUNDARIES3D), and harvests
   `zurich_*.xml.gz` + config + the eqasim jar into `$SCRATCH/gnn_runs/base/`.
   It also builds `pool_persons.parquet` (attributes + home municipality).
   The 2 % pool exists so that class-3 scenarios can draw 0.5 / 1 / 2 % samples
   without ever re-running the pipeline; the **baseline is a fixed 1 % draw
   (pop_seed 0)** of that pool.
2. **Scenarios** — `python generate_scenarios.py` writes
   `scenarios/<id>/scenario.json` for the whole campaign, deterministic from
   `config.yaml: generator_seed`.
3. **Run** — `python submit_array.py ...` submits one Slurm array task per
   scenario (`run_scenario.py`): materialize (modified network / population XML
   + config overrides) → `RunSimulation` → extract parquets → delete
   `output_events.xml.gz` + `ITERS/` → copy parquets to `data/<id>/`.
4. **Manifest** — `python build_manifest.py` → `manifest.parquet`
   (status ok/failed/running, path, class, runtime, core-hours, error).

## Scenario classes

| class | id      | perturbation |
|------:|---------|--------------|
| 0 | `base_s0..4` | identical baseline, different MATSim seed (simulation variance) |
| 1 | `c1_*`  | 1–5 closures of car links with capacity ≥ 1000 veh/h, never PT-carrying links. **Variant: capacity → 0** (kept in the network: capacity 1 veh/h, freespeed 1 m/s so the router avoids it). Removing links crashes MATSim when routes reference them. |
| 2 | `c2_*`  | 5–20 random car links, capacity × {0.5, 0.75, 1.5} (factor drawn per link) |
| 3 | `c3_*`  | other population seed and/or rate ∈ {0.5, 1, 2 %}; with p=0.5 also one random municipality scaled × {0.7, 1.3} (implemented as a differential draw rate inside that zone) |

`flowCapacityFactor = rate`, `storageCapacityFactor = rate^0.75` (eqasim's rule),
both recorded in every `scenario.json`.

## Per-scenario files (`data/<id>/`)

- `scenario.json` — id, class, seed, matsim_seed, pop_seed, sample_rate,
  capacity factors, iterations, eqasim commit, all perturbation parameters,
  population selection stats
- `nodes.parquet` — node_id, x, y
- `links.parquet` — link_id, from_node, to_node, length, freespeed, capacity,
  lanes, modes, `closed`, `capacity_factor`
- `persons.parquet` — person_id, home_x/y, home_zone (BFS), age, employed,
  car_available, has_license, main activity type + x/y, is_freight
- `link_hourly.parquet` — link_id, hour, volume (scaled to 100 %),
  traveltime_avg, vc_ratio, congestion_index (from `linkstats`, averaged over
  the last 5 iterations). **Sparse:** only (link, hour) rows with volume > 0 are
  stored; a missing row means volume 0, free-flow travel time, vc_ratio 0,
  congestion_index 1. Compact dtypes (int8 hour, float32), zstd.
- `delta_vs_baseline.parquet` (class 1, 2) — Δ vc_ratio, Δ congestion_index vs
  `base_s0` over the union of both sparse key sets; rows with zero change omitted
- `scorestats.parquet` — MATSim score trajectory (convergence check)

Demand tables (from the scenario's OWN population plans, `build_demand.py`;
all counts are `weight = 1/sample_rate`-weighted, i.e. scaled to 100 %):

- `persons.parquet` additionally has `work_x/y`, `edu_x/y` (first work /
  education activity), `n_legs` (raw MATSim legs), `n_trips` (trips between
  non-interaction activities, the unit used by the OD tables), `n_car_trips`,
  `weight`
- `cells.parquet` — regular 500 m grid over the network bounding box (grid
  definition in `scenario.json: demand.grid`, `cell_id = iy * nx + ix`,
  EPSG:2056; identical for all scenarios). Per cell: `cx, cy`, `residents`,
  `residents_employed`, `residents_car_available` (carAvail always/sometimes),
  `residents_age_0_17/18_64/65plus`, `jobs`, `edu_places`, `trips_origin`,
  `trips_dest`. Empty cells are included (zeros). Home = the plan's first
  `home` activity, so agents cut by the scenario cutter (only `outside`
  activities) and freight agents are not residents. Source: the scenario's
  `output_plans.xml.gz` (plans after replanning, consistent with the measured
  loads; recorded in `scenario.json: demand.source`).
- `od_cells.parquet` — `orig_cell, dest_cell, mode, trips` (sparse, trips > 0;
  cell −1 = outside the grid). `mode` is the trip's routingMode (car, pt,
  walk, bike, car_passenger, truck, outside). `od_cells_am.parquet`: same for
  departures 06:00–09:00.
- `cells_delta_vs_baseline.parquet` (class 3) — cell values minus `base_s0`.
- `../cell_link_edges.parquet` (ONCE at the dataset root, identical for all
  scenarios): `cell_id, link_id, dist_m` for every pair with |cell centre −
  link midpoint| ≤ radius (see `cell_link_edges.json`).

## Operations

```bash
python generate_scenarios.py                 # after the base is ready
python submit_array.py base_s0               # baseline first
python -c "from gnnds.convergence import summarize; print(summarize('/cluster/scratch/rsahleanu/gnn_runs/base_s0/output/scorestats.csv'))"
python submit_array.py c1_000                # one test scenario -> runtime / core-h
python submit_array.py --class 1             # then the arrays
python submit_array.py --all --skip-done     # (re)run everything not yet ok
python build_manifest.py
```

Resources per task are in `config.yaml: resources` (override with
`--cores/--mem-mb/--time/--java-xmx/--max-parallel`).

## Campaign 2026-09-13 — results and caveats

155/155 scenarios ok (job array 14032547 + 14031605/06), 474 core-h total,
median 45 min per scenario on 4 cores (26–79 min), MaxRSS 7.5 GB.
`manifest.parquet` has runtime/core-hours/job id per scenario.

**Convergence** (`scorestats.parquet`, mean over all 155 runs of `avg_executed`):
−45.8 (it 0) → −25.4 (it 30) → −25.3 (it 60). Relative change over 5
iterations: 1.1 % at it 30, 0.4 % at it 40, ≤ 0.2 % from it 45 on. Innovation
is never switched off (`fractionOfIterationsToDisableInnovation = Infinity`),
so scores keep fluctuating by ~±0.2 % around the plateau. 60 iterations are
safe; ~45–50 would have sufficed.

**Noise floor at 1 %.** One sampled vehicle = 100 veh/h after scaling, i.e.
0.1 vc on a 1000 veh/h link. Seed-only differences (`base_s1..4` vs `base_s0`)
give mean |Δvc| = 0.09 per (link, hour) and 36 % of link-hours differ by
> 0.1; single closures (class 1) give 0.105 / 43 %. The perturbation signal is
therefore local and small relative to per-link-hour seed noise — use the five
baseline seeds to estimate that noise, aggregate over hours/links, or train on
`delta_vs_baseline` with an appropriate loss. 14 of the 173 closed links carry
no traffic in the baseline (closure has no effect); `scenario.json` +
`links.parquet: closed` identify them.

**Outliers.** `traveltime_avg` / `congestion_index` can be extreme (up to
~10⁴×) on short links that gridlock in the QSim at this sample size (storage
capacity factor 0.032 → most links hold a single vehicle). Clip or winsorize
before training. PT-only links (`pt_*`, 2240 links, freespeed ∞) have
`congestion_index = NaN`; filter `links.parquet: modes` for car links.

**Scratch.** `$SCRATCH/gnn_runs/<id>/` keeps the materialized inputs and the
non-event MATSim outputs (~200 MB each, 31 GB total); events and `ITERS/` were
deleted. Everything needed for training is in `data/` (4.3 GB).

## Loading in PyTorch

`torch_dataset.py` turns every scenario into one graph sample (needs numpy,
pandas, pyarrow, torch; optional torch_geometric and scipy). Copy `data/`,
`manifest.parquet` and `torch_dataset.py` to the training machine, then:

```python
from torch_dataset import GNNScenarioDataset
from torch.utils.data import DataLoader          # or torch_geometric.loader.DataLoader

ds = GNNScenarioDataset("/path/to/gnn_dataset", targets="vc_ratio")   # 155 scenarios
ds.build_cache()                                  # once: parquet -> cache_torch/*.npz (a few s per scenario)
tr, va, te = ds.split(val_frac=0.15, test_frac=0.15, seed=0)          # stratified by class
sample = ds[tr[0]]
# sample.x [92019, 4]   node: x, y (normalised), n_home, n_activity (persons, scaled to 100 %)
# sample.edge_index [2, 181961]   car links, from -> to
# sample.edge_attr [181961, 7]    log_length, freespeed, log_capacity, lanes, closed, capacity_factor, capacity_eff
# sample.y [181961, 24]           target per link and hour; sample.y_base = same for base_s0
# sample.scenario                 dict from scenario.json
loader = DataLoader([ds[i] for i in tr], batch_size=1, shuffle=True)   # plain torch: returns dicts
```

With `with_cells=True` (default) every sample also carries the demand side:
`cell_x [13786, 12]` (normalised centre + log1p of the 10 cell counts),
`cell_pos`, `cell_link_index [2, M]` / `cell_link_dist [M]` (cell ↔ car-link
pairs; `cell_link_max_dist=2000` keeps 9.1 M pairs instead of 57 M for 5 km),
`od_index [2, K]` / `od_trips [K, 3]` (all / car / AM-peak trips between cells
inside the grid). The cell ↔ link pairs are read once from
`cell_link_edges.parquet` and cached as npz.

`targets` may be a list (`["vc_ratio", "congestion_index", "traveltime_avg"]` →
`y` is `[E, 72]`); `congestion_index` is clipped at `clip_congestion` (50) and
NaN → 1. With `car_only=False` all 188 590 links are used. The network is the
same in every sample, so a model can cache `edge_index`.