Add files using upload-large-folder tool
Browse files- README.md +621 -3
- data/config.json +59 -0
- data/episodes/part-00072.parquet +3 -0
- data/episodes/part-00073.parquet +3 -0
- data/episodes/part-00074.parquet +3 -0
- data/episodes/part-00075.parquet +3 -0
- data/episodes/part-00076.parquet +3 -0
- data/episodes/part-00077.parquet +3 -0
- data/episodes/part-00078.parquet +3 -0
- data/episodes/part-00079.parquet +3 -0
- data/episodes/part-00080.parquet +3 -0
- data/episodes/part-00081.parquet +3 -0
- data/episodes/part-00082.parquet +3 -0
- data/episodes/part-00083.parquet +3 -0
- data/episodes/part-00084.parquet +3 -0
- data/episodes/part-00085.parquet +3 -0
- data/episodes/part-00086.parquet +3 -0
- data/episodes/part-00087.parquet +3 -0
- data/episodes/part-00088.parquet +3 -0
- data/episodes/part-00089.parquet +3 -0
- data/episodes/part-00090.parquet +3 -0
- data/episodes/part-00091.parquet +3 -0
- data/episodes/part-00092.parquet +3 -0
- data/episodes/part-00093.parquet +3 -0
- data/episodes/part-00094.parquet +3 -0
- data/episodes/part-00095.parquet +3 -0
- data/episodes/part-00096.parquet +3 -0
- data/episodes/part-00097.parquet +3 -0
- data/episodes/part-00098.parquet +3 -0
- data/episodes/part-00099.parquet +3 -0
- data/episodes/part-00100.parquet +3 -0
- data/episodes/part-00101.parquet +3 -0
- data/manifest.json +156 -0
- examples/benchmark_routers.py +105 -0
- examples/forecast_congestion.py +138 -0
- examples/inspect_episode.py +105 -0
- examples/visualize.py +372 -0
- requirements.txt +7 -0
- scripts/push_to_huggingface.py +45 -0
- scripts/run_local_sweep.py +100 -0
- scripts/validate_dataset.py +375 -0
- src/__init__.py +1 -0
- src/config.py +102 -0
- src/dataset.py +195 -0
- src/design.py +104 -0
- src/graph_generator.py +203 -0
- src/physics_engine.py +224 -0
- src/simulation_loop.py +451 -0
- src/telemetry_logger.py +164 -0
- terminal_logs.txt +208 -0
README.md
CHANGED
|
@@ -1,3 +1,621 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
pretty_name: Semantic Potential Routing Telemetry
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
task_categories:
|
| 7 |
+
- time-series-forecasting
|
| 8 |
+
- tabular-regression
|
| 9 |
+
- graph-ml
|
| 10 |
+
tags:
|
| 11 |
+
- networking
|
| 12 |
+
- routing
|
| 13 |
+
- graph-theory
|
| 14 |
+
- operations-research
|
| 15 |
+
- physics-based-simulation
|
| 16 |
+
- telemetry
|
| 17 |
+
- microbursts
|
| 18 |
+
- data-center-networks
|
| 19 |
+
- benchmark
|
| 20 |
+
- synthetic
|
| 21 |
+
size_categories:
|
| 22 |
+
- 100M<n<1B
|
| 23 |
+
configs:
|
| 24 |
+
- config_name: router_summary
|
| 25 |
+
data_files: data/router_summary/*.parquet
|
| 26 |
+
- config_name: flow_summary
|
| 27 |
+
data_files: data/flow_summary/*.parquet
|
| 28 |
+
- config_name: episodes
|
| 29 |
+
data_files: data/episodes/*.parquet
|
| 30 |
+
- config_name: events
|
| 31 |
+
data_files: data/events/*.parquet
|
| 32 |
+
- config_name: network_telemetry
|
| 33 |
+
data_files: data/network_telemetry/*.parquet
|
| 34 |
+
- config_name: flow_telemetry
|
| 35 |
+
data_files: data/flow_telemetry/*.parquet
|
| 36 |
+
- config_name: link_telemetry
|
| 37 |
+
data_files: data/link_telemetry/*.parquet
|
| 38 |
+
- config_name: potential_field
|
| 39 |
+
data_files: data/potential_field/*.parquet
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
# Semantic Potential Routing Telemetry
|
| 43 |
+
|
| 44 |
+
**Version 2.0** — a systematic, packet-level benchmark of **training-free potential-field routing** against
|
| 45 |
+
classical routing under stochastic congestion, dynamic topologies and microburst traffic.
|
| 46 |
+
|
| 47 |
+
Every episode is a network simulation in which routing is a physical field: each flow's destination is the
|
| 48 |
+
grounded, attractive well of a discrete Poisson equation on the graph Laplacian, congested buffers inject
|
| 49 |
+
repulsive current, and packets follow the resulting routing gradient without any learned weights. The same
|
| 50 |
+
episode — identical topology, failure timeline and packet arrivals — is replayed under **six routers**: three
|
| 51 |
+
potential-field variants (steepest descent, proportional multipath splitting, and a static ablation without
|
| 52 |
+
congestion feedback) and three classical baselines (static shortest path, equal-cost multipath, and
|
| 53 |
+
queue-aware adaptive shortest path). Episodes are laid out on a **full factorial design** over topology
|
| 54 |
+
family, network size, traffic profile, offered load and topology dynamics, so every effect can be studied
|
| 55 |
+
in isolation, and the recorded telemetry is step-resolved: buffer occupancy and drops of every node, load of
|
| 56 |
+
every directed link, per-flow delivery and delay, and the potential field itself.
|
| 57 |
+
|
| 58 |
+
Everything is generated on CPU with linear algebra and a vectorised queueing simulator: no GPU, no
|
| 59 |
+
training, no external data. The generator ships in this repository, and any episode can be re-created bit
|
| 60 |
+
for bit from `data/config.json` and its episode id.
|
| 61 |
+
|
| 62 |
+
## Experimental design
|
| 63 |
+
|
| 64 |
+
Episodes belong to the cells of a five-factor factorial design (`src/design.py`). With the default 10
|
| 65 |
+
replicates per cell the dataset holds **5 × 4 × 3 × 3 × 3 = 540 cells and 5,400 episodes**, each replayed
|
| 66 |
+
under all six routers.
|
| 67 |
+
|
| 68 |
+
| Factor | Levels | Meaning |
|
| 69 |
+
|---|---|---|
|
| 70 |
+
| `topology` | `barabasi_albert`, `watts_strogatz`, `erdos_renyi`, `waxman`, `fat_tree` | scale-free (router-level Internet), small-world, random, geometric ISP-like (distance latencies, coordinates), k-ary data-centre fabric (hosts are the endpoints, 2:1 oversubscribed edge) |
|
| 71 |
+
| `size` | 32, 64, 128, 256 | nominal node count; fat-trees use k = 4, 6, 8, 10 (36, 99, 208, 375 nodes) |
|
| 72 |
+
| `traffic_profile` | `poisson`, `microburst`, `sustained` | stationary Poisson; short intense bursts (peak/idle 16, mean 15-step bursts, 13 % duty); long moderate surges (peak/idle 4, 50 % duty) |
|
| 73 |
+
| `load_level` | `light`, `moderate`, `heavy` | offered load ρ = 0.01, 0.03, 0.10 of the network's directed link capacity (defined below) |
|
| 74 |
+
| `dynamics_level` | `static`, `moderate`, `severe` | no events; link failures and node degradations at 0.002/step each lasting 50–200 steps; 0.01/step lasting 100–400 steps |
|
| 75 |
+
|
| 76 |
+
Episode `e` maps deterministically to cell `e mod 540` and replicate `e div 540`, so any prefix of the
|
| 77 |
+
episode range — including a partially generated or resumed dataset — covers all cells evenly. Replicates
|
| 78 |
+
are assigned to splits by `replicate mod 5`: 0–2 train, 3 validation, 4 test (60/20/20), recorded in
|
| 79 |
+
`episodes.split`. Random families are generated at a common mean degree of 6, so network size is the only
|
| 80 |
+
structural quantity that changes with the size factor.
|
| 81 |
+
|
| 82 |
+
## Tables
|
| 83 |
+
|
| 84 |
+
The dataset is a relational schema of eight Parquet tables, one folder each under `data/`, sharded by
|
| 85 |
+
episode (`part-00000.parquet`, …) and served as separate configurations on the Hub, so you download only
|
| 86 |
+
what you need. Node ids are `0 … n_nodes−1`, flows `0 … n_flows−1`, and one step is one millisecond of
|
| 87 |
+
simulated time. Every telemetry row carries `episode_id`, `router` and `step`.
|
| 88 |
+
|
| 89 |
+
**`episodes`** — one row per episode: design cell (`cell_id`, `replicate`, `split`, `topology`, `size`,
|
| 90 |
+
`traffic_profile`, `load_level`, `dynamics_level`), dimensions (`n_nodes`, `n_edges`, `n_flows`,
|
| 91 |
+
`tracked_flows`, `steps`, `field_stride`), `offered_load` (ρ) and `total_capacity` (Σ directed link
|
| 92 |
+
capacity), the static graph (`edge_u`, `edge_v` with `u < v` in a fixed order; per-link `capacity` in
|
| 93 |
+
packets/step and `latency` in steps; `node_role` 0 router / 1 core / 2 aggregation / 3 edge / 4 host;
|
| 94 |
+
`node_x`, `node_y` for Waxman graphs, empty otherwise) and the flows (`flow_source`, `flow_sink`,
|
| 95 |
+
`flow_mean_rate`, `flow_idle_rate`, `flow_burst_rate`, plus the MMPP transition probabilities
|
| 96 |
+
`p_idle_to_burst`, `p_burst_to_idle`, zero for the Poisson profile).
|
| 97 |
+
|
| 98 |
+
**`events`** — one row per topology event, active for `start <= step < end`: `kind` (`link_failure`: the
|
| 99 |
+
link's capacity is 0; `node_degradation`: all links of `node` are scaled by `factor`), `edge_u`/`edge_v` or
|
| 100 |
+
`node` (−1 where not applicable).
|
| 101 |
+
|
| 102 |
+
**`router_summary`** — one row per (episode, router): `offered`, `delivered`, `dropped`, `in_flight`,
|
| 103 |
+
`loss_ratio`, `mean_delay`, `p99_delay`, `mean_queue`, `max_queue`, `link_utilisation` (packets forwarded /
|
| 104 |
+
directed link capacity over all link-steps), `link_saturation` (fraction of directed link-steps at full
|
| 105 |
+
capacity), `route_changes` (next-hop table entries that changed, summed over steps and flows).
|
| 106 |
+
|
| 107 |
+
**`flow_summary`** — one row per (episode, router, flow): `source`, `sink`, `mean_rate`, `min_hops`,
|
| 108 |
+
`min_latency` (shortest path on the base graph), `offered`, `delivered`, `dropped`, `in_flight`,
|
| 109 |
+
`loss_ratio`, `mean_delay`, `delay_std`, `p50_delay`, `p95_delay`, `p99_delay`, `max_delay`,
|
| 110 |
+
`mean_queueing_delay`, `mean_path_latency` (delay = queueing + propagation), `mean_hops`, `route_changes`.
|
| 111 |
+
|
| 112 |
+
**`network_telemetry`** — one row per (episode, router, step): network totals `offered`, `admitted`,
|
| 113 |
+
`delivered`, `dropped`, `queued`, `in_transit`, `mean_delay` (of packets delivered this step, NaN if none),
|
| 114 |
+
`route_changes`, and two lists of length `n_nodes`: `queue_depth` (buffer occupancy after the step's
|
| 115 |
+
arrivals were admitted and before forwarding, i.e. what the router sees) and `node_dropped`.
|
| 116 |
+
|
| 117 |
+
**`flow_telemetry`** — one row per (episode, router, step, tracked flow) for the first `tracked_flows` (8)
|
| 118 |
+
flows of every episode: `mmpp_state` (0 idle, 1 burst), `offered`, `admitted`, `delivered`, `dropped`,
|
| 119 |
+
`queued`, `in_transit`, `mean_delay`, `route_changes`.
|
| 120 |
+
|
| 121 |
+
**`link_telemetry`** — one row per (episode, router, step): `load_uv` and `load_vu`, lists of length
|
| 122 |
+
`n_edges` with the packets forwarded over each link in the `u → v` and `v → u` directions.
|
| 123 |
+
|
| 124 |
+
**`potential_field`** — one row per logged step of the `potential` router: `potential`, a list of
|
| 125 |
+
`tracked_flows × n_nodes` float32 values, flow-major, with φ = 0 at each flow's sink. Steps are logged every
|
| 126 |
+
`field_stride` steps (2 for 32-node graphs, 12 for the largest fat-trees) so that each episode's field
|
| 127 |
+
stays within 1 MB; any step and any flow can be recomputed exactly from the other tables (see below).
|
| 128 |
+
|
| 129 |
+
With the defaults, `flow_telemetry` holds about 260 M rows (5,400 episodes × 6 routers × 1,000 steps × 8
|
| 130 |
+
tracked flows) and `network_telemetry` and `link_telemetry` 32.4 M each; the whole dataset is roughly 20 GB,
|
| 131 |
+
three quarters of it the two per-step list tables. The summary tables are a few hundred MB and answer most
|
| 132 |
+
benchmark questions on their own. **None of the step-level tables fits in memory** — read them with column
|
| 133 |
+
projection and `episode_id` / `router` filters, or stream them shard by shard as
|
| 134 |
+
`scripts/validate_dataset.py` does.
|
| 135 |
+
|
| 136 |
+
All list columns (`queue_depth`, `node_dropped`, `load_uv`, `load_vu`, `capacity`, `latency`, …) are
|
| 137 |
+
**int16** to keep the files small. Widen them before arithmetic — `np.stack(net.queue_depth) * 160`
|
| 138 |
+
silently overflows, `np.stack(net.queue_depth).astype(float) * 160` does not.
|
| 139 |
+
|
| 140 |
+
## Simulation model
|
| 141 |
+
|
| 142 |
+
**Topologies.** Barabási–Albert (m = 3), connected Watts–Strogatz (k = 6, p = 0.1) and Erdős–Rényi
|
| 143 |
+
(p = 6/(n−1)) graphs; Waxman graphs with uniformly random coordinates in the unit square and link
|
| 144 |
+
preference exp(−d / 0.15√2), drawn with an exact edge count for mean degree 6 and latency proportional to
|
| 145 |
+
distance; and k-ary fat-trees (k²/4 core, k² pod switches, k³/4 hosts) with 40 packets/step fabric links
|
| 146 |
+
and 80 packets/step host links. Random-graph links have integer capacities uniform in 8–80 packets/step
|
| 147 |
+
(≈ 100–1 000 Mb/s for 1 500-byte packets at 1 ms steps) and latencies uniform in 1–10 steps. A disconnected
|
| 148 |
+
Erdős–Rényi or Waxman sample is stitched into one component by joining each stray component to the main
|
| 149 |
+
one (closest pair of nodes for geometric graphs), which adds on average fewer than 0.2 links per graph
|
| 150 |
+
below 128 nodes and about one link per graph at 256 nodes, so the node count is always the nominal one.
|
| 151 |
+
|
| 152 |
+
**Dynamics.** Independently each step a link fails or a node degrades with the level's probability; failed
|
| 153 |
+
links are chosen only among the non-bridge links of the live graph, so the network never partitions and the
|
| 154 |
+
question of interest — how quickly traffic routes around the damage — is always well posed. A degraded node
|
| 155 |
+
multiplies the capacity of all its links by a factor in 0.1–0.5. Effective capacities are
|
| 156 |
+
`max(1, ⌊capacity × factor_u × factor_v⌋)`, or 0 while failed, and follow from `episodes` + `events`.
|
| 157 |
+
|
| 158 |
+
**Traffic.** Each episode has two flows per endpoint node between distinct ordered (source, sink) pairs.
|
| 159 |
+
Per-flow mean rates are log-normal (σ = 0.75, elephants and mice) and rescaled so that the offered load
|
| 160 |
+
`ρ = Σ_f m_f · hops_f / Σ_links capacity` — the share of the network's directed capacity the flows would
|
| 161 |
+
occupy on their shortest paths — equals the cell's level exactly. Each flow is a two-state Markov-modulated
|
| 162 |
+
Poisson process whose idle and burst rates are derived from its mean rate and the profile's peak ratio and
|
| 163 |
+
duty cycle, so profiles differ in burstiness at equal long-run load.
|
| 164 |
+
|
| 165 |
+
**Queueing.** Every node owns one drop-tail FIFO buffer of 256 packets shared by all flows. Each step, in
|
| 166 |
+
order: new packets are created at their sources; packets reaching a node this step are delivered if the
|
| 167 |
+
node is their sink, otherwise admitted oldest-first while space remains, the rest dropped; buffers are
|
| 168 |
+
logged and routing decisions taken; then every directed link forwards, oldest first, up to its capacity of
|
| 169 |
+
the packets whose next hop crosses it (virtual output queueing, no head-of-line blocking). A packet
|
| 170 |
+
forwarded at step `t` over a link of latency ℓ arrives at `t + ℓ`, so delay is propagation plus queueing,
|
| 171 |
+
and a packet already on the wire is unaffected by a failure of that link. Traffic is open-loop: there is no
|
| 172 |
+
congestion control, which is what makes the routers' behaviour under overload comparable.
|
| 173 |
+
|
| 174 |
+
## Routers
|
| 175 |
+
|
| 176 |
+
| router | decision | recomputed | capacity-aware | congestion-aware | multipath |
|
| 177 |
+
|---|---|---|---|---|---|
|
| 178 |
+
| `potential` | link with the largest current I_ij = w_ij(φ_i − φ_j) | every step | yes | yes | no |
|
| 179 |
+
| `potential_split` | packets sprayed in proportion to the positive currents | every step | yes | yes | yes |
|
| 180 |
+
| `potential_static` | largest current of the field without congestion injection | topology change | yes | no | no |
|
| 181 |
+
| `shortest_path` | Dijkstra on latency (OSPF-like) | topology change | no | no | no |
|
| 182 |
+
| `ecmp` | round-robin over all equal-latency shortest-path next hops | topology change | no | no | yes |
|
| 183 |
+
| `adaptive_shortest_path` | Dijkstra on latency + queue / capacity, quantised to 10⁻⁶ steps (ARPANET-style) | every step | partly | yes | no |
|
| 184 |
+
|
| 185 |
+
**Potential field.** For flow *f* with source *s* and sink *t*,
|
| 186 |
+
|
| 187 |
+
```
|
| 188 |
+
L_g φ = b, L = D − W, w_ij = capacity_ij / latency_ij (live links only)
|
| 189 |
+
b_i = source_injection · [i = s] + background_injection / (N − 1) + congestion_gain · queue_i / buffer_size
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
where `L_g` is the weighted graph Laplacian with the sink's row and column removed — the Dirichlet condition
|
| 193 |
+
φ_t = 0 that makes the sink the grounded well of the field (defaults 1.0, 0.5 and 2.0). The grounded inverse
|
| 194 |
+
is available in closed form from the Laplacian pseudo-inverse, `(L_g⁻¹)_ij = L⁺_ij − L⁺_it − L⁺_tj + L⁺_tt`,
|
| 195 |
+
and because the background and congestion injections are shared by all flows, the fields of all flows follow
|
| 196 |
+
from one matrix–vector product with L⁺ plus O(N) work per flow; L⁺ is formed once per topology change. On
|
| 197 |
+
every live directed link the current is I_ij = w_ij(φ_i − φ_j). Since b_i > 0 at every non-sink node,
|
| 198 |
+
Σ_j I_ij = b_i > 0: at least one current is positive and every positive-current link leads strictly
|
| 199 |
+
downhill, so both potential rules are loop-free and reach the sink in at most N − 1 hops for *any*
|
| 200 |
+
congestion pattern — congestion bends routes but can never trap a packet. Proportional splitting is the
|
| 201 |
+
physically faithful rule (electrical current divides over parallel paths); it uses a low-discrepancy
|
| 202 |
+
per-packet coordinate so that the split is exact and the simulation stays deterministic.
|
| 203 |
+
|
| 204 |
+
**Baselines.** `shortest_path` is the classic link-state behaviour, blind to capacity and queues but
|
| 205 |
+
reacting to failures. `ecmp` spreads packets over all equal-cost paths, the data-centre default. The
|
| 206 |
+
adaptive baseline recomputes Dijkstra each step with link cost latency + queue/capacity, the queue-aware
|
| 207 |
+
policy that famously oscillates; its `route_changes` make that visible. Together with `potential_static`,
|
| 208 |
+
the suite separates the value of capacity awareness, congestion awareness and multipath.
|
| 209 |
+
|
| 210 |
+
On the defaults, at moderate load with microbursts, mean loss over episodes is about 1 % for `potential`,
|
| 211 |
+
under 0.5 % for `potential_split` and `adaptive_shortest_path`, 2–3 % for `potential_static` and around
|
| 212 |
+
10 % for `shortest_path` and `ecmp`. At heavy load every router loses packets: a few percent for the
|
| 213 |
+
adaptive ones, about 20 % for the static potential field and a third or more for shortest path and ECMP.
|
| 214 |
+
The multipath and static potential variants pay for their robustness with longer paths (path stretch
|
| 215 |
+
about 1.4–1.5 against 1.2 for the others), and the adaptive routers change next hops several orders of
|
| 216 |
+
magnitude more often than the static baselines.
|
| 217 |
+
|
| 218 |
+
## Generating the dataset
|
| 219 |
+
|
| 220 |
+
Any Python ≥ 3.9 environment works; the commands below are written with forward slashes, which both
|
| 221 |
+
PowerShell and POSIX shells accept.
|
| 222 |
+
|
| 223 |
+
```bat
|
| 224 |
+
cd "<path to this repository>"
|
| 225 |
+
pip install -r requirements.txt
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
Check the whole pipeline end to end in about a minute — fifteen short episodes covering every topology
|
| 229 |
+
family, traffic profile and router in a temporary folder that is deleted afterwards:
|
| 230 |
+
|
| 231 |
+
```bat
|
| 232 |
+
python scripts/run_local_sweep.py --smoke
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
Generate the dataset (5,400 episodes on every logical core, shards of 40 episodes streamed to `data/`):
|
| 236 |
+
|
| 237 |
+
```bat
|
| 238 |
+
python scripts/run_local_sweep.py
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
An episode costs roughly 3–7 s of CPU at size 32, 6–13 s at 64, 20–35 s at 128 and 60–100 s at 256
|
| 242 |
+
(six routers, 1 000 steps; heavier load and larger fabrics cost more), i.e. about 4–5 CPU-hours per
|
| 243 |
+
replicate: expect the default run to take **one night on an 8-core laptop** and to write about 20 GB.
|
| 244 |
+
Keep the machine plugged in with sleep disabled. The sweep
|
| 245 |
+
prints progress with an ETA, and if it is interrupted, running the same command again resumes with the
|
| 246 |
+
missing shards; when it finishes it writes `data/manifest.json` (provenance, coverage, table sizes) and
|
| 247 |
+
prints the router benchmark. `data/config.json` binds the folder to its configuration, so a changed setting
|
| 248 |
+
must go to another `--out` folder.
|
| 249 |
+
|
| 250 |
+
Every design level and model knob is a flag (`python scripts/run_local_sweep.py --help`). A half-size run
|
| 251 |
+
with exact 60/20/20 splits, a smaller design, or a potential-field-only run:
|
| 252 |
+
|
| 253 |
+
```bat
|
| 254 |
+
python scripts/run_local_sweep.py --replicates 5
|
| 255 |
+
python scripts/run_local_sweep.py --sizes 32,64 --topologies barabasi_albert,fat_tree --out data_small
|
| 256 |
+
python scripts/run_local_sweep.py --routers potential,shortest_path --out data_pair
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
Requirements: Python ≥ 3.9 with NumPy, SciPy, pandas, PyArrow, NetworkX, huggingface_hub and, for the
|
| 260 |
+
figures, Matplotlib (`requirements.txt`). Workers use one BLAS thread each; all parallelism comes from the
|
| 261 |
+
process pool.
|
| 262 |
+
|
| 263 |
+
## Validating a generated dataset
|
| 264 |
+
|
| 265 |
+
`scripts/validate_dataset.py` is the test suite of a data folder. It re-derives every quantity it can from
|
| 266 |
+
an independent path and compares, rather than merely re-reading what the generator wrote:
|
| 267 |
+
|
| 268 |
+
```bat
|
| 269 |
+
python scripts/validate_dataset.py :: validates data/
|
| 270 |
+
python scripts/validate_dataset.py --out data_small --resimulate 5
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
| Group | What is checked |
|
| 274 |
+
|---|---|
|
| 275 |
+
| Structure | every table has the same number of shards; `manifest.json` present |
|
| 276 |
+
| Design coverage | all cells present, replicates balanced to ±1, episode ids unique, the three splits present |
|
| 277 |
+
| Invariants | `offered = delivered + dropped + in_flight`; loss ratio in [0, 1]; `mean_delay ≥ min_latency` and `mean_hops ≥ min_hops`; delay quantiles ordered; `mean_delay = mean_queueing_delay + mean_path_latency`; `flow_summary` sums to `router_summary`; `network_telemetry` and `flow_telemetry` sum to their summaries per (episode, router[, flow]); `admitted ≤ offered` on every step; link utilisation and saturation in [0, 1] |
|
| 278 |
+
| Physical bounds (sampled episodes) | buffer occupancy within `buffer_size`; per-node drops sum to the step total; link loads never exceed the capacity in force at that step (recomputed from `episodes` + `events`); potentials non-negative and exactly 0 at each flow's sink |
|
| 279 |
+
| Reproducibility | sampled episodes re-simulated from `config.json` alone and compared **bit for bit**, every table and column (NaN equal to NaN) |
|
| 280 |
+
| Field reconstruction | one stored `potential_field` snapshot recovered from the graph state and queue depths with the sparse SuperLU reference solver, independent of the pseudo-inverse path used by the generator |
|
| 281 |
+
|
| 282 |
+
Sampled episodes are the smallest, the largest and one drawn at random (`--seed`); `--resimulate` sets how
|
| 283 |
+
many are re-simulated. Every line is printed as `[ok ]` or `[FAIL]`, the script exits **1** with a summary
|
| 284 |
+
of the failures if anything is wrong, and a failing cross-table sum names the first group that differs
|
| 285 |
+
(abridged output of a full default run):
|
| 286 |
+
|
| 287 |
+
```
|
| 288 |
+
Structure
|
| 289 |
+
[ok ] 135 shards present
|
| 290 |
+
[ok ] every table has every shard
|
| 291 |
+
[ok ] manifest.json present
|
| 292 |
+
Design coverage
|
| 293 |
+
[ok ] all 540 design cells present
|
| 294 |
+
[ok ] balanced: 10-10 episodes per cell
|
| 295 |
+
[ok ] episode ids unique
|
| 296 |
+
[ok ] splits present: ['test', 'train', 'validation']
|
| 297 |
+
Invariants
|
| 298 |
+
[ok ] flow conservation: offered = delivered + dropped + in-flight
|
| 299 |
+
...
|
| 300 |
+
[ok ] tracked-flow telemetry sums to the flow summary
|
| 301 |
+
[ok ] admitted <= offered
|
| 302 |
+
Physical bounds (sampled episodes)
|
| 303 |
+
[ok ] episode 0: queue depths within the buffer
|
| 304 |
+
[ok ] episode 0: link loads never exceed the capacity in force
|
| 305 |
+
[ok ] episode 0: potentials non-negative and zero at the sinks
|
| 306 |
+
Reproducibility (re-simulating from config.json)
|
| 307 |
+
[ok ] episode 0: every table reproduced bit for bit
|
| 308 |
+
Potential-field reconstruction (sparse reference solver)
|
| 309 |
+
[ok ] episode 0, step 100: stored field matches the sparse solve (max rel err 4.5e-08)
|
| 310 |
+
|
| 311 |
+
Dataset v2.0: 5400 episodes, 20.14 GB
|
| 312 |
+
All checks passed.
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
**Memory.** The cross-table checks never load a step-level table. The shards are scanned one record batch
|
| 316 |
+
at a time (`--batch-rows`, default 262,144) and folded into a dense accumulator whose size is fixed by the
|
| 317 |
+
design — episodes × routers × tracked flows, about 260 k slots — not by the 260 M rows being read. Peak
|
| 318 |
+
resident memory is therefore flat in dataset size: **well under 1 GB** for the full 20 GB dataset, of which
|
| 319 |
+
the PyArrow buffers are about 20 MB. The invariant pass costs roughly a minute per 10 GB on one core; the
|
| 320 |
+
re-simulation of a few episodes dominates the total runtime.
|
| 321 |
+
|
| 322 |
+
A quick end-to-end rehearsal of generation *and* validation, in about two minutes:
|
| 323 |
+
|
| 324 |
+
```bat
|
| 325 |
+
python scripts/run_local_sweep.py --out data_tiny --sizes 32 --replicates 5 --steps 200 --shard_episodes 25
|
| 326 |
+
python scripts/validate_dataset.py --out data_tiny
|
| 327 |
+
python examples/benchmark_routers.py --data data_tiny
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
## Using the data
|
| 331 |
+
|
| 332 |
+
```python
|
| 333 |
+
import numpy as np, pandas as pd
|
| 334 |
+
|
| 335 |
+
rs = pd.read_parquet("data/router_summary")
|
| 336 |
+
ep = pd.read_parquet("data/episodes").set_index("episode_id")
|
| 337 |
+
df = rs.join(ep[["topology", "size", "traffic_profile", "load_level", "dynamics_level", "split"]], on="episode_id")
|
| 338 |
+
print(df.pivot_table(index=["traffic_profile", "load_level"], columns="router", values="loss_ratio"))
|
| 339 |
+
|
| 340 |
+
# One episode, step by step
|
| 341 |
+
eid = 7
|
| 342 |
+
net = pd.read_parquet("data/network_telemetry", filters=[("episode_id", "=", eid), ("router", "=", "potential")]).sort_values("step")
|
| 343 |
+
queue = np.stack(net.queue_depth).astype(np.int32) # (steps, n_nodes); int16 on disk
|
| 344 |
+
link = pd.read_parquet("data/link_telemetry", filters=[("episode_id", "=", eid), ("router", "=", "potential")]).sort_values("step")
|
| 345 |
+
load = np.stack(link.load_uv).astype(np.int32) + np.stack(link.load_vu) # (steps, n_edges), both directions
|
| 346 |
+
field = pd.read_parquet("data/potential_field", filters=[("episode_id", "=", eid)]).sort_values("step")
|
| 347 |
+
row = ep.loc[eid]
|
| 348 |
+
phi = np.stack(field.potential).reshape(-1, row.tracked_flows, row.n_nodes) # (snapshots, tracked flows, nodes)
|
| 349 |
+
```
|
| 350 |
+
|
| 351 |
+
The graph state at any step — the N × N capacity matrix in force — follows from `episodes` and `events`:
|
| 352 |
+
|
| 353 |
+
```python
|
| 354 |
+
def capacity_matrix(row, events, step):
|
| 355 |
+
cap = row.capacity.astype(float).copy()
|
| 356 |
+
factor, failed = np.ones(row.n_nodes), np.zeros(len(cap), bool)
|
| 357 |
+
for e in events[(events.start <= step) & (step < events.end)].itertuples():
|
| 358 |
+
if e.kind == "node_degradation":
|
| 359 |
+
factor[e.node] *= e.factor
|
| 360 |
+
else:
|
| 361 |
+
failed |= (row.edge_u == e.edge_u) & (row.edge_v == e.edge_v)
|
| 362 |
+
cap = np.maximum(1, np.floor(cap * factor[row.edge_u] * factor[row.edge_v]))
|
| 363 |
+
cap[failed] = 0
|
| 364 |
+
A = np.zeros((row.n_nodes, row.n_nodes))
|
| 365 |
+
A[row.edge_u, row.edge_v] = A[row.edge_v, row.edge_u] = cap
|
| 366 |
+
return A
|
| 367 |
+
|
| 368 |
+
events = pd.read_parquet("data/events", filters=[("episode_id", "=", eid)])
|
| 369 |
+
A = capacity_matrix(row, events, step=500)
|
| 370 |
+
```
|
| 371 |
+
|
| 372 |
+
The same reconstruction, the telemetry of any router and an exact recomputation of the field of any flow at
|
| 373 |
+
any step are one call each in the read API:
|
| 374 |
+
|
| 375 |
+
```python
|
| 376 |
+
from src.dataset import Dataset
|
| 377 |
+
|
| 378 |
+
ds = Dataset("data")
|
| 379 |
+
ep = ds.episode(7)
|
| 380 |
+
A = ep.capacity_matrix(500) # the graph state at step 500
|
| 381 |
+
queue = ep.queue_depth("potential") # (steps, n_nodes)
|
| 382 |
+
phi = ep.solve_field(500, flows=[0, 1, 2]) # exact field of any flows at any step
|
| 383 |
+
path = ep.descent_path(500, phi[0], ep.source[0], ep.sink[0])
|
| 384 |
+
```
|
| 385 |
+
|
| 386 |
+
`scripts/validate_dataset.py` checks such recomputations against the sparse SuperLU reference solver. From
|
| 387 |
+
the Hub, each table is a configuration:
|
| 388 |
+
|
| 389 |
+
```python
|
| 390 |
+
from datasets import load_dataset
|
| 391 |
+
rs = load_dataset("<user>/<dataset>", "router_summary", split="train")
|
| 392 |
+
```
|
| 393 |
+
|
| 394 |
+
Suggested uses: benchmarking routing policies on identical scenarios; forecasting queue build-up, drops
|
| 395 |
+
or link saturation from step-level telemetry (`network_telemetry`, `link_telemetry`); learning graph
|
| 396 |
+
surrogates of the potential field or of the routers' next-hop decisions (`potential_field` plus the graph
|
| 397 |
+
state); studying route flapping of adaptive policies (`route_changes`); and out-of-distribution evaluation
|
| 398 |
+
across topology families, sizes or dynamics levels using the factor columns of `episodes`.
|
| 399 |
+
|
| 400 |
+
## Examples
|
| 401 |
+
|
| 402 |
+
`examples/` holds four scripts written against the small read API in `src/dataset.py` — `Dataset(path)`
|
| 403 |
+
opens a data folder, `ds.table(name, columns, filters)` and `ds.summary(name)` return tables (the latter
|
| 404 |
+
joined with the design factors and split), and `ds.episode(id)` bundles one episode: its graph, event
|
| 405 |
+
timeline and flows, the capacities in force at any step (`capacity_at`, `live_graph`, `capacity_matrix`),
|
| 406 |
+
its telemetry under any router (`queue_depth`, `node_dropped`, `link_load`, `link_utilisation`), the stored
|
| 407 |
+
field (`field`) and an exact recomputation of the field of *any* flow at *any* step (`solve_field`,
|
| 408 |
+
`next_hops`, `descent_path`). Every script runs on `data/` by default (`--data` selects another folder),
|
| 409 |
+
prints its results, asserts the properties it relies on and ends with "All checks passed", so the set also
|
| 410 |
+
serves as a usage test of a generated dataset.
|
| 411 |
+
|
| 412 |
+
```bat
|
| 413 |
+
python examples/benchmark_routers.py :: paired router comparison with bootstrap intervals, per factor
|
| 414 |
+
python examples/inspect_episode.py --episode 7 --step 500
|
| 415 |
+
python examples/forecast_congestion.py :: ridge forecast of near-term loss on the splits
|
| 416 |
+
python examples/visualize.py :: eight figures into figures/
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
### `benchmark_routers.py` — paired router comparison
|
| 420 |
+
|
| 421 |
+
Compares every router with a reference (`--reference`, default `shortest_path`) on the identical episodes:
|
| 422 |
+
mean loss and delay differences with 95 % bootstrap confidence intervals, win and tie rates, the loss ratio
|
| 423 |
+
broken down by each design factor, and flow-level path stretch, latency stretch and queueing delay.
|
| 424 |
+
`--csv figures/benchmark.csv` writes the per-episode joined summary. Abridged output:
|
| 425 |
+
|
| 426 |
+
```
|
| 427 |
+
Paired differences to 'shortest_path' (negative = better; bootstrap 95 % CI over episodes):
|
| 428 |
+
episodes loss_diff loss_ci_low loss_ci_high wins_loss delay_diff wins_delay
|
| 429 |
+
router
|
| 430 |
+
adaptive_shortest_path 675 -0.0770 -0.0863 -0.0681 0.4593 -0.8561 0.5837
|
| 431 |
+
ecmp 675 -0.0082 -0.0107 -0.0059 0.3096 -0.1613 0.5244
|
| 432 |
+
potential 675 -0.0685 -0.0766 -0.0601 0.4607 0.3886 0.3615
|
| 433 |
+
potential_split 675 -0.0828 -0.0924 -0.0734 0.4637 2.6682 0.1630
|
| 434 |
+
potential_static 675 -0.0409 -0.0472 -0.0352 0.4074 1.0377 0.1733
|
| 435 |
+
|
| 436 |
+
Flow level (flows with at least one delivered packet):
|
| 437 |
+
flows lossless_share path_stretch latency_stretch queueing_delay p99_delay
|
| 438 |
+
potential 38879 0.9174 1.2646 1.2213 0.2678 11.0834
|
| 439 |
+
potential_split 38879 0.9505 1.4912 1.6238 0.1118 23.9248
|
| 440 |
+
potential_static 38879 0.8506 1.4371 1.2912 0.5299 11.4198
|
| 441 |
+
shortest_path 38879 0.7846 1.2540 1.0038 1.6477 11.1648
|
| 442 |
+
ecmp 38879 0.7945 1.2541 1.0038 1.5072 11.2295
|
| 443 |
+
adaptive_shortest_path 38879 0.9359 1.1999 1.0494 0.2220 9.3849
|
| 444 |
+
```
|
| 445 |
+
|
| 446 |
+
Read it as: the potential routers and the adaptive baseline cut loss by 4–8 percentage points against
|
| 447 |
+
shortest path; the multipath split trades 2.7 steps of extra delay and 49 % path stretch for the lowest
|
| 448 |
+
loss of all; the win rates are below 0.5 only because at light load more than half the episode pairs are
|
| 449 |
+
exact ties (`ties_loss`, printed in the full table). The numbers above come from the two-minute rehearsal
|
| 450 |
+
run (675 size-32 episodes, 200 steps), so they are noisier and lossier than a full sweep — the *ordering*
|
| 451 |
+
of the routers is what reproduces.
|
| 452 |
+
|
| 453 |
+
### `inspect_episode.py` — one episode, checked against the physics
|
| 454 |
+
|
| 455 |
+
Prints the design cell, graph, flows, event timeline and router summary; then, at one step, the capacities
|
| 456 |
+
in force, the busiest buffers and links; recomputes the tracked flows' potential field from the graph state
|
| 457 |
+
and queue depths and asserts it against the stored snapshot *and* the sparse reference solver; and follows
|
| 458 |
+
one flow's steepest-current descent to its sink.
|
| 459 |
+
|
| 460 |
+
```
|
| 461 |
+
Episode 7 [barabasi_albert/32/poisson/heavy/moderate] 32 nodes, 87 links, 64 flows, 200 steps, split=train
|
| 462 |
+
degree min/mean/max 3/5.44/16, capacity 8-80 pkt/step, latency 1-10 steps, total directed capacity 7678 pkt/step
|
| 463 |
+
flows: 64 between 32 endpoints, offered load rho = 0.100, tracked flows 8, field stride 1
|
| 464 |
+
|
| 465 |
+
Topology events (1):
|
| 466 |
+
kind start end node factor
|
| 467 |
+
node_degradation 72 128 6 0.4374
|
| 468 |
+
|
| 469 |
+
Step 100: 0 failed links, 9 links with reduced capacity, 87 live links
|
| 470 |
+
busiest buffers under potential: node 0: 256, node 4: 189, node 6: 142
|
| 471 |
+
[ok] potential field of the 8 tracked flows recomputed from graph state + queues (max rel dev 4.9e-08)
|
| 472 |
+
[ok] pseudo-inverse solution agrees with the sparse SuperLU solve for flow 0
|
| 473 |
+
[ok] steepest-current descent of flow 0 reaches its sink: 12 -> 1 -> 7 (2 hops, shortest possible 2);
|
| 474 |
+
potentials 0.4934 > 0.4433 > 0.0000
|
| 475 |
+
```
|
| 476 |
+
|
| 477 |
+
The last line is the loop-freedom guarantee made concrete: the potential decreases strictly along the path
|
| 478 |
+
and the walk terminates at the sink.
|
| 479 |
+
|
| 480 |
+
### `forecast_congestion.py` — a learning task on the splits
|
| 481 |
+
|
| 482 |
+
Predicts the network's loss ratio over the next `--horizon` steps from the last `--window` steps of
|
| 483 |
+
`network_telemetry`, normalised by `total_capacity` so all sizes share one feature scale, with a closed-form
|
| 484 |
+
ridge regression tuned on validation and reported on test against a persistence baseline:
|
| 485 |
+
|
| 486 |
+
```
|
| 487 |
+
data/: router potential, window 10, horizon 10, stride 5
|
| 488 |
+
samples: train 14,985 (405 episodes), validation 4,995 (135), test 4,995 (135); features 52
|
| 489 |
+
Ridge penalty chosen on validation: lambda = 0.0001 (validation RMSE 0.0270)
|
| 490 |
+
MAE RMSE R2
|
| 491 |
+
ridge (validation) 0.0096 0.0270 0.8405
|
| 492 |
+
persistence (validation) 0.0091 0.0325 0.7689
|
| 493 |
+
ridge (test) 0.0099 0.0268 0.8285
|
| 494 |
+
persistence (test) 0.0096 0.0342 0.7215
|
| 495 |
+
```
|
| 496 |
+
|
| 497 |
+
As a squared-loss model the ridge wins on RMSE and R² while persistence keeps a marginally lower MAE on the
|
| 498 |
+
many loss-free windows — a useful reminder to state the metric before claiming a win. The script asserts
|
| 499 |
+
that the splits are disjoint by episode and that no feature is undefined.
|
| 500 |
+
|
| 501 |
+
### `visualize.py` — the figure gallery
|
| 502 |
+
|
| 503 |
+
Draws eight PNGs into `figures/` (`--out`) with one fixed palette in which every router keeps its hue.
|
| 504 |
+
Select a subset with `--figures`, and steer the single-episode panels with `--episode` (default: a busy
|
| 505 |
+
one), `--step`, `--flow`, `--routers` (default `potential,shortest_path`) and `--dpi`:
|
| 506 |
+
|
| 507 |
+
```bat
|
| 508 |
+
python examples/visualize.py --data data_small --figures potential_field,timeline --episode 12 --step 400
|
| 509 |
+
```
|
| 510 |
+
|
| 511 |
+
| File | Shows |
|
| 512 |
+
|---|---|
|
| 513 |
+
| `topologies.png` | one graph per family, link width scaled by capacity |
|
| 514 |
+
| `benchmark.png` | loss and mean delay per router at each load level, 95 % bootstrap intervals |
|
| 515 |
+
| `timeline.png` | one episode step by step under two routers, with bursts and topology events marked |
|
| 516 |
+
| `queue_heatmap.png` | buffer occupancy of every node over time, same episode, two routers side by side |
|
| 517 |
+
| `link_utilisation.png` | CCDF of per-link-step utilisation: how often links run near saturation, per router |
|
| 518 |
+
| `potential_field.png` | the field of one flow on the graph, node size = buffer occupancy, with the steepest-current next hops and the descent path |
|
| 519 |
+
| `delays.png` | flow-level p99 delay and path stretch per router |
|
| 520 |
+
| `traffic_profiles.png` | offered packets of one flow under each of the three profiles |
|
| 521 |
+
|
| 522 |
+

|
| 523 |
+
|
| 524 |
+

|
| 525 |
+
|
| 526 |
+

|
| 527 |
+
|
| 528 |
+

|
| 529 |
+
|
| 530 |
+
## Reproducibility and provenance
|
| 531 |
+
|
| 532 |
+
Episode `e` draws every random quantity from `numpy.random.default_rng([seed, e])` in a fixed order and
|
| 533 |
+
the routers are deterministic, so `scripts/validate_dataset.py` can re-simulate any episode and compare it
|
| 534 |
+
bit for bit. The generator also avoids the two places where platforms usually disagree: shortest-path
|
| 535 |
+
next hops are derived from Dijkstra *distances* (exact, because latencies and the quantised adaptive
|
| 536 |
+
costs are integer-valued) with a fixed tie rule rather than from the solver's predecessor tie-breaking,
|
| 537 |
+
and the potential routers resolve mathematically tied currents — common on symmetric fabrics — within a
|
| 538 |
+
relative tolerance far above rounding noise. All twenty sample episodes generated during development were
|
| 539 |
+
bit-identical under NumPy 1.26 / SciPy 1.11 and NumPy 2.4 / SciPy 1.17. `data/config.json` records the
|
| 540 |
+
configuration and `data/manifest.json` the dataset version, library versions, platform, design coverage
|
| 541 |
+
and table statistics of the shards present.
|
| 542 |
+
|
| 543 |
+
## Limitations
|
| 544 |
+
|
| 545 |
+
Traffic is open-loop (no TCP-like feedback), nodes have a single shared drop-tail buffer, all packets
|
| 546 |
+
have the same size, time is discretised to 1 ms steps and capacities to whole packets per step, and the
|
| 547 |
+
topologies are synthetic families rather than measured networks. Routing tables are recomputed
|
| 548 |
+
instantaneously with global knowledge, which is an upper bound on what a distributed implementation can
|
| 549 |
+
achieve. These choices keep the routers comparable and the episodes reproducible; they should be kept in
|
| 550 |
+
mind when transferring conclusions to production networks.
|
| 551 |
+
|
| 552 |
+
## Publishing
|
| 553 |
+
|
| 554 |
+
Uploading is the one manual step. Draw the figures this card embeds, log in once with a write token, then
|
| 555 |
+
push the project folder — Parquet shards, `config.json`, `manifest.json`, this dataset card with its
|
| 556 |
+
figures, and the generator and example source — as a dataset repository; the upload is resumable and its
|
| 557 |
+
bookkeeping lives in `.cache/`:
|
| 558 |
+
|
| 559 |
+
```bat
|
| 560 |
+
python examples/visualize.py
|
| 561 |
+
hf auth login
|
| 562 |
+
python scripts/push_to_huggingface.py --repo <user>/<dataset>
|
| 563 |
+
```
|
| 564 |
+
|
| 565 |
+
Add `--private` for a private repository. The `configs:` block at the top of this file makes every table
|
| 566 |
+
browsable in the Dataset Viewer as soon as the upload finishes.
|
| 567 |
+
|
| 568 |
+
## Repository layout
|
| 569 |
+
|
| 570 |
+
```
|
| 571 |
+
├── README.md dataset card and this guide
|
| 572 |
+
├── requirements.txt
|
| 573 |
+
├── .gitignore keeps generated data and caches out of git
|
| 574 |
+
├── src/
|
| 575 |
+
│ ├── design.py factors, levels, episode �� cell / replicate / split
|
| 576 |
+
│ ├── config.py every knob of the generator, one frozen dataclass
|
| 577 |
+
│ ├── graph_generator.py five topology families, connectivity-preserving event timelines
|
| 578 |
+
│ ├── physics_engine.py Laplacian potential field, routing gradient, multipath spraying, baselines
|
| 579 |
+
│ ├── simulation_loop.py traffic, vectorised packet queueing, six routers, multiprocessing sweep
|
| 580 |
+
│ ├── telemetry_logger.py Parquet schemas, sharded resumable writing, manifest
|
| 581 |
+
│ └── dataset.py read API: tables, episodes, graph state and field at any step
|
| 582 |
+
├── scripts/
|
| 583 |
+
│ ├── run_local_sweep.py generate (automatic, resumable)
|
| 584 |
+
│ ├── validate_dataset.py verify a generated dataset
|
| 585 |
+
│ └── push_to_huggingface.py publish (manual)
|
| 586 |
+
├── examples/
|
| 587 |
+
│ ├── benchmark_routers.py paired router benchmark
|
| 588 |
+
│ ├── inspect_episode.py one episode end to end, checked against the physics
|
| 589 |
+
│ ├── forecast_congestion.py loss forecasting on the splits
|
| 590 |
+
│ └── visualize.py figure gallery
|
| 591 |
+
├── figures/ drawn by examples/visualize.py
|
| 592 |
+
└── data/ generated shards, one folder per table, plus config.json and manifest.json
|
| 593 |
+
```
|
| 594 |
+
|
| 595 |
+
## Changelog
|
| 596 |
+
|
| 597 |
+
**2.0** — full factorial design over five topology families, four sizes, three traffic profiles, three
|
| 598 |
+
offered-load levels and three dynamics levels with balanced replicates and 60/20/20 splits; six routers
|
| 599 |
+
(three potential-field variants, three classical baselines); two flows per endpoint with log-normal rates
|
| 600 |
+
and offered load defined relative to network capacity; potential fields via the Laplacian pseudo-inverse
|
| 601 |
+
(exact, O(N·F) per step); per-link loads, per-node drops, queueing/propagation delay decomposition, route
|
| 602 |
+
changes, network-level per-step totals; manifest with provenance and coverage; validation script.
|
| 603 |
+
|
| 604 |
+
**1.0** — 1,000 Barabási–Albert episodes with four flows, potential field vs. shortest path, six tables.
|
| 605 |
+
|
| 606 |
+
Tooling fixes since the 2.0 data release (the Parquet schemas and the generated data are unchanged, so no
|
| 607 |
+
regeneration is needed): the cross-table invariant checks in `scripts/validate_dataset.py` now stream the
|
| 608 |
+
shards into a dense per-group accumulator instead of loading `flow_telemetry` into pandas, which exhausted
|
| 609 |
+
memory on the full dataset, and they report the first group that differs when a sum disagrees; the
|
| 610 |
+
potential-field figure widens the int16 `queue_depth` before scaling it into marker sizes, which previously
|
| 611 |
+
overflowed and hid the busiest nodes.
|
| 612 |
+
|
| 613 |
+
## Design notes
|
| 614 |
+
|
| 615 |
+
The original blueprint solved `L φ = b` on the full Laplacian, which is singular and only consistent when
|
| 616 |
+
`b` sums to zero — a condition that congestion injections break. Grounding the sink removes the
|
| 617 |
+
singularity, gives the sink its physical meaning as the well of the field and yields the loop-freedom
|
| 618 |
+
guarantee above. Choosing the next hop by the largest current rather than the lowest neighbouring
|
| 619 |
+
potential makes the decision conductance-aware, so a low-capacity or high-latency link is not chosen merely
|
| 620 |
+
because its far end sits at a low potential. Telemetry is streamed straight to Parquet in atomic, resumable
|
| 621 |
+
shards, which is what the Hub reads natively and makes a separate HDF5 staging layer unnecessary.
|
data/config.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"replicates": 10,
|
| 3 |
+
"topologies": [
|
| 4 |
+
"barabasi_albert",
|
| 5 |
+
"watts_strogatz",
|
| 6 |
+
"erdos_renyi",
|
| 7 |
+
"waxman",
|
| 8 |
+
"fat_tree"
|
| 9 |
+
],
|
| 10 |
+
"sizes": [
|
| 11 |
+
32,
|
| 12 |
+
64,
|
| 13 |
+
128,
|
| 14 |
+
256
|
| 15 |
+
],
|
| 16 |
+
"traffic_profiles": [
|
| 17 |
+
"poisson",
|
| 18 |
+
"microburst",
|
| 19 |
+
"sustained"
|
| 20 |
+
],
|
| 21 |
+
"load_levels": [
|
| 22 |
+
"light",
|
| 23 |
+
"moderate",
|
| 24 |
+
"heavy"
|
| 25 |
+
],
|
| 26 |
+
"dynamics_levels": [
|
| 27 |
+
"static",
|
| 28 |
+
"moderate",
|
| 29 |
+
"severe"
|
| 30 |
+
],
|
| 31 |
+
"routers": [
|
| 32 |
+
"potential",
|
| 33 |
+
"potential_split",
|
| 34 |
+
"potential_static",
|
| 35 |
+
"shortest_path",
|
| 36 |
+
"ecmp",
|
| 37 |
+
"adaptive_shortest_path"
|
| 38 |
+
],
|
| 39 |
+
"seed": 2026,
|
| 40 |
+
"shard_episodes": 40,
|
| 41 |
+
"field_budget_bytes": 1000000,
|
| 42 |
+
"steps": 1000,
|
| 43 |
+
"buffer_size": 256,
|
| 44 |
+
"mean_degree": 6,
|
| 45 |
+
"capacity_range": [
|
| 46 |
+
8,
|
| 47 |
+
80
|
| 48 |
+
],
|
| 49 |
+
"latency_range": [
|
| 50 |
+
1,
|
| 51 |
+
10
|
| 52 |
+
],
|
| 53 |
+
"fat_tree_capacity": 40,
|
| 54 |
+
"flows_per_endpoint": 2,
|
| 55 |
+
"tracked_flows": 8,
|
| 56 |
+
"source_injection": 1.0,
|
| 57 |
+
"background_injection": 0.5,
|
| 58 |
+
"congestion_gain": 2.0
|
| 59 |
+
}
|
data/episodes/part-00072.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5ecf052ed4ef92c24913089aa4c8dd998dbdffce6502fde45402f6e4ec098d89
|
| 3 |
+
size 363288
|
data/episodes/part-00073.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b0c032d6863e6488d0507d315fc6262de9d736eb7965462a56b24037acee0197
|
| 3 |
+
size 87814
|
data/episodes/part-00074.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:726738214f37ab900980a2afd1b7b650b38689a93b3c716b4f5f5cfae6c80148
|
| 3 |
+
size 226545
|
data/episodes/part-00075.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:05d42b81dfb83e1cc82c670ec7b2812e4c5f22acdc15e6feec9df72d6dfa3c63
|
| 3 |
+
size 314892
|
data/episodes/part-00076.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:808734d31a2d4f7e4edeff5c7e1c06375f65c713f47d0b178f3b7072f2635f78
|
| 3 |
+
size 135633
|
data/episodes/part-00077.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e2374f59da68f12225532e9b4886e49bce0948d1fec373f0f4550968bc1f54e
|
| 3 |
+
size 395860
|
data/episodes/part-00078.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04a8d15e17408c3a06c981e2f75d1b5ca57c62605262847c69291f51f59feafc
|
| 3 |
+
size 195735
|
data/episodes/part-00079.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:58a811bd11c0eac612f44e973e89b67e95fe9ff7cfaccdf9e30219049d31a26b
|
| 3 |
+
size 125645
|
data/episodes/part-00080.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5f559e188882f1fe6c6088f07d6f8e97bfbf1c5e887446e5dd380e2d4cfa05de
|
| 3 |
+
size 331317
|
data/episodes/part-00081.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:12128b7d39d144e06a797e056cff02da8638cf2f227e562c7e90d6f230e329c8
|
| 3 |
+
size 80533
|
data/episodes/part-00082.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6600ad65186a0b4b3898eefce9e5bb8954a430ae28a1491b009f31afbf6e4501
|
| 3 |
+
size 194180
|
data/episodes/part-00083.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ade31f367023d9053cc593c8f199fffe4d8556fbeb6ecb36536bf9fd26aef7c
|
| 3 |
+
size 340456
|
data/episodes/part-00084.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a820111a2584d259dbde72310472d690819f07ff54c9b7200cf56e3676e6cbee
|
| 3 |
+
size 96209
|
data/episodes/part-00085.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1960d92c92ffc8ad59a548ccf07df8ee5ec92fd0e8d82477ef37e5da3b0017f4
|
| 3 |
+
size 286165
|
data/episodes/part-00086.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:12c1e209931a228d37f5c5fdee7297158c4907a5301c74958cdfa7f1c9fd5c3d
|
| 3 |
+
size 220559
|
data/episodes/part-00087.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:efefb69c75589c27f9573071191bec474e9f2676c6266dda21bef519e9aa7f46
|
| 3 |
+
size 146520
|
data/episodes/part-00088.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e9a43f4df12209ea0e467f3dfa63d59fe782567403d057068145b7e3f0132f06
|
| 3 |
+
size 372537
|
data/episodes/part-00089.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a517559f8a28874b4effd956d599e87f5c7385777beef99c0192496d2cf0fffb
|
| 3 |
+
size 132831
|
data/episodes/part-00090.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d49ecab2f7efc1bd1fbd344fca63c27ddcadeb1ecbfb1e44cbbed413f3542a99
|
| 3 |
+
size 222785
|
data/episodes/part-00091.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:96e7b620ea35a41a2fb7ca83a12884111fe1bc7af6ab906055629b0b048dc549
|
| 3 |
+
size 432232
|
data/episodes/part-00092.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f795ab76d4433cbb2dc1fa62c653ecdf545a68c9ae93fc770c51bc2b79d53688
|
| 3 |
+
size 61897
|
data/episodes/part-00093.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f0176f2904390bc61556e813cbaecb84ac5e84858cf7c22a71e7e75890221522
|
| 3 |
+
size 220585
|
data/episodes/part-00094.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1d8616c8ace06aec0a10b96bd74c12b327b2125dc45196ace43adc17eb7eace
|
| 3 |
+
size 228291
|
data/episodes/part-00095.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:019ce64d5bd45027b6e26b3971e073f506690c8e4ac7b809c0aaffc9a0d59018
|
| 3 |
+
size 127159
|
data/episodes/part-00096.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2bdd1d10035beac3facc20097a46ac2cea583e920309b5a7a97520aa02d5d818
|
| 3 |
+
size 346484
|
data/episodes/part-00097.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ffcc878913bd21827348cfb00ef526ce28455011eeabf4a62940fba47b7745a
|
| 3 |
+
size 150993
|
data/episodes/part-00098.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:71d30bb06c73e24de6f4c2a29899b9e904a476b902280058239810d9773b42ac
|
| 3 |
+
size 168108
|
data/episodes/part-00099.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:34528f8fead5135edf38157c1a0aedf3c2301c797cf9b85ff317690853ec133e
|
| 3 |
+
size 363223
|
data/episodes/part-00100.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:42eeda03f6cca2abcf19fb7738c8b10d3d5786ee7f59b7c145bbdeddd94050dc
|
| 3 |
+
size 87427
|
data/episodes/part-00101.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:70572b9a8568e9617d4ed3e17bb060acee567b1035dfa049ef464a793f96f72b
|
| 3 |
+
size 226256
|
data/manifest.json
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dataset_version": "2.0",
|
| 3 |
+
"created_utc": "2026-08-30T03:43:51+00:00",
|
| 4 |
+
"provenance": {
|
| 5 |
+
"python": "3.14.7",
|
| 6 |
+
"platform": "Windows-11-10.0.26200-SP0",
|
| 7 |
+
"numpy": "2.5.2",
|
| 8 |
+
"scipy": "1.18.1",
|
| 9 |
+
"pyarrow": "25.0.1",
|
| 10 |
+
"pandas": "3.0.5",
|
| 11 |
+
"networkx": "3.6.1"
|
| 12 |
+
},
|
| 13 |
+
"config": {
|
| 14 |
+
"replicates": 10,
|
| 15 |
+
"topologies": [
|
| 16 |
+
"barabasi_albert",
|
| 17 |
+
"watts_strogatz",
|
| 18 |
+
"erdos_renyi",
|
| 19 |
+
"waxman",
|
| 20 |
+
"fat_tree"
|
| 21 |
+
],
|
| 22 |
+
"sizes": [
|
| 23 |
+
32,
|
| 24 |
+
64,
|
| 25 |
+
128,
|
| 26 |
+
256
|
| 27 |
+
],
|
| 28 |
+
"traffic_profiles": [
|
| 29 |
+
"poisson",
|
| 30 |
+
"microburst",
|
| 31 |
+
"sustained"
|
| 32 |
+
],
|
| 33 |
+
"load_levels": [
|
| 34 |
+
"light",
|
| 35 |
+
"moderate",
|
| 36 |
+
"heavy"
|
| 37 |
+
],
|
| 38 |
+
"dynamics_levels": [
|
| 39 |
+
"static",
|
| 40 |
+
"moderate",
|
| 41 |
+
"severe"
|
| 42 |
+
],
|
| 43 |
+
"routers": [
|
| 44 |
+
"potential",
|
| 45 |
+
"potential_split",
|
| 46 |
+
"potential_static",
|
| 47 |
+
"shortest_path",
|
| 48 |
+
"ecmp",
|
| 49 |
+
"adaptive_shortest_path"
|
| 50 |
+
],
|
| 51 |
+
"seed": 2026,
|
| 52 |
+
"shard_episodes": 40,
|
| 53 |
+
"field_budget_bytes": 1000000,
|
| 54 |
+
"steps": 1000,
|
| 55 |
+
"buffer_size": 256,
|
| 56 |
+
"mean_degree": 6,
|
| 57 |
+
"capacity_range": [
|
| 58 |
+
8,
|
| 59 |
+
80
|
| 60 |
+
],
|
| 61 |
+
"latency_range": [
|
| 62 |
+
1,
|
| 63 |
+
10
|
| 64 |
+
],
|
| 65 |
+
"fat_tree_capacity": 40,
|
| 66 |
+
"flows_per_endpoint": 2,
|
| 67 |
+
"tracked_flows": 8,
|
| 68 |
+
"source_injection": 1.0,
|
| 69 |
+
"background_injection": 0.5,
|
| 70 |
+
"congestion_gain": 2.0
|
| 71 |
+
},
|
| 72 |
+
"design": {
|
| 73 |
+
"cells": 540,
|
| 74 |
+
"episodes_planned": 5400,
|
| 75 |
+
"episodes_present": 5400,
|
| 76 |
+
"episodes_per_cell_min": 10,
|
| 77 |
+
"episodes_per_cell_max": 10
|
| 78 |
+
},
|
| 79 |
+
"coverage": {
|
| 80 |
+
"topology": {
|
| 81 |
+
"barabasi_albert": 1080,
|
| 82 |
+
"erdos_renyi": 1080,
|
| 83 |
+
"fat_tree": 1080,
|
| 84 |
+
"watts_strogatz": 1080,
|
| 85 |
+
"waxman": 1080
|
| 86 |
+
},
|
| 87 |
+
"size": {
|
| 88 |
+
"32": 1350,
|
| 89 |
+
"64": 1350,
|
| 90 |
+
"128": 1350,
|
| 91 |
+
"256": 1350
|
| 92 |
+
},
|
| 93 |
+
"traffic_profile": {
|
| 94 |
+
"microburst": 1800,
|
| 95 |
+
"poisson": 1800,
|
| 96 |
+
"sustained": 1800
|
| 97 |
+
},
|
| 98 |
+
"load_level": {
|
| 99 |
+
"heavy": 1800,
|
| 100 |
+
"light": 1800,
|
| 101 |
+
"moderate": 1800
|
| 102 |
+
},
|
| 103 |
+
"dynamics_level": {
|
| 104 |
+
"moderate": 1800,
|
| 105 |
+
"severe": 1800,
|
| 106 |
+
"static": 1800
|
| 107 |
+
},
|
| 108 |
+
"split": {
|
| 109 |
+
"test": 1080,
|
| 110 |
+
"train": 3240,
|
| 111 |
+
"validation": 1080
|
| 112 |
+
}
|
| 113 |
+
},
|
| 114 |
+
"tables": {
|
| 115 |
+
"episodes": {
|
| 116 |
+
"files": 135,
|
| 117 |
+
"rows": 5400,
|
| 118 |
+
"bytes": 30041631
|
| 119 |
+
},
|
| 120 |
+
"events": {
|
| 121 |
+
"files": 135,
|
| 122 |
+
"rows": 43246,
|
| 123 |
+
"bytes": 873246
|
| 124 |
+
},
|
| 125 |
+
"router_summary": {
|
| 126 |
+
"files": 135,
|
| 127 |
+
"rows": 32400,
|
| 128 |
+
"bytes": 1821131
|
| 129 |
+
},
|
| 130 |
+
"flow_summary": {
|
| 131 |
+
"files": 135,
|
| 132 |
+
"rows": 7672320,
|
| 133 |
+
"bytes": 188357615
|
| 134 |
+
},
|
| 135 |
+
"flow_telemetry": {
|
| 136 |
+
"files": 135,
|
| 137 |
+
"rows": 259200000,
|
| 138 |
+
"bytes": 959075231
|
| 139 |
+
},
|
| 140 |
+
"network_telemetry": {
|
| 141 |
+
"files": 135,
|
| 142 |
+
"rows": 32400000,
|
| 143 |
+
"bytes": 3687668325
|
| 144 |
+
},
|
| 145 |
+
"link_telemetry": {
|
| 146 |
+
"files": 135,
|
| 147 |
+
"rows": 32400000,
|
| 148 |
+
"bytes": 9272669204
|
| 149 |
+
},
|
| 150 |
+
"potential_field": {
|
| 151 |
+
"files": 135,
|
| 152 |
+
"rows": 1501470,
|
| 153 |
+
"bytes": 3481173416
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
}
|
examples/benchmark_routers.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Benchmark the routers on identical scenarios.
|
| 2 |
+
|
| 3 |
+
python examples/benchmark_routers.py # data/
|
| 4 |
+
python examples/benchmark_routers.py --data data_small --reference potential --csv figures/benchmark.csv
|
| 5 |
+
|
| 6 |
+
Every episode is replayed under every router, so the comparison is *paired*: for each router the
|
| 7 |
+
script reports its per-episode difference to a reference router (loss ratio, mean delay) with a
|
| 8 |
+
bootstrap 95 % confidence interval over episodes and the fraction of episodes it wins, then
|
| 9 |
+
breaks the loss ratio down by each design factor and the flow-level path stretch and queueing
|
| 10 |
+
delay. The script also asserts the structural properties the analysis relies on (every episode
|
| 11 |
+
present under every router, aligned pairs), so it doubles as an end-to-end read test.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import sys
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
sys.path.insert(0, str(ROOT))
|
| 22 |
+
|
| 23 |
+
from src.dataset import FACTORS, Dataset # noqa: E402
|
| 24 |
+
|
| 25 |
+
METRICS = ["loss_ratio", "mean_delay", "p99_delay", "link_utilisation", "link_saturation", "route_changes"]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def bootstrap_ci(values: np.ndarray, rng: np.random.Generator, samples: int = 2000, level: float = 0.95):
|
| 29 |
+
"""Percentile bootstrap confidence interval of the mean over episodes."""
|
| 30 |
+
means = rng.choice(values, size=(samples, len(values)), replace=True).mean(axis=1)
|
| 31 |
+
lo, hi = np.percentile(means, [50 * (1 - level), 50 * (1 + level)])
|
| 32 |
+
return values.mean(), lo, hi
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def paired_table(summary: pd.DataFrame, reference: str, rng: np.random.Generator) -> pd.DataFrame:
|
| 36 |
+
wide = {m: summary.pivot(index="episode_id", columns="router", values=m) for m in ("loss_ratio", "mean_delay")}
|
| 37 |
+
rows = []
|
| 38 |
+
for router in wide["loss_ratio"].columns:
|
| 39 |
+
if router == reference:
|
| 40 |
+
continue
|
| 41 |
+
d_loss = (wide["loss_ratio"][router] - wide["loss_ratio"][reference]).to_numpy()
|
| 42 |
+
pair = wide["mean_delay"][[router, reference]].dropna() # NaN delay only if nothing was delivered
|
| 43 |
+
d_delay = (pair[router] - pair[reference]).to_numpy()
|
| 44 |
+
m, lo, hi = bootstrap_ci(d_loss, rng)
|
| 45 |
+
md, dlo, dhi = bootstrap_ci(d_delay, rng)
|
| 46 |
+
rows.append({"router": router, "episodes": len(d_loss),
|
| 47 |
+
"loss_diff": m, "loss_ci_low": lo, "loss_ci_high": hi,
|
| 48 |
+
"wins_loss": np.mean(d_loss < 0), "ties_loss": np.mean(d_loss == 0),
|
| 49 |
+
"delay_diff": md, "delay_ci_low": dlo, "delay_ci_high": dhi,
|
| 50 |
+
"wins_delay": np.mean(d_delay < 0)})
|
| 51 |
+
return pd.DataFrame(rows).set_index("router")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main() -> None:
|
| 55 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 56 |
+
parser.add_argument("--data", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
|
| 57 |
+
parser.add_argument("--reference", default="shortest_path", help="router the others are compared with")
|
| 58 |
+
parser.add_argument("--csv", type=Path, default=None, help="write the per-episode joined summary here")
|
| 59 |
+
parser.add_argument("--seed", type=int, default=0, help="bootstrap seed")
|
| 60 |
+
args = parser.parse_args()
|
| 61 |
+
pd.set_option("display.width", 160)
|
| 62 |
+
pd.set_option("display.precision", 4)
|
| 63 |
+
|
| 64 |
+
ds = Dataset(args.data)
|
| 65 |
+
summary = ds.summary("router_summary")
|
| 66 |
+
routers = list(ds.routers)
|
| 67 |
+
assert set(summary.router) == set(routers), "router_summary does not contain every configured router"
|
| 68 |
+
per_episode = summary.groupby("episode_id").router.nunique()
|
| 69 |
+
assert (per_episode == len(routers)).all(), "every episode must be present under every router"
|
| 70 |
+
assert args.reference in routers, f"--reference must be one of {routers}"
|
| 71 |
+
print(f"{ds.path}: {summary.episode_id.nunique()} episodes x {len(routers)} routers, "
|
| 72 |
+
f"{len(ds.config.cells)} design cells\n")
|
| 73 |
+
|
| 74 |
+
print("Mean over episodes:")
|
| 75 |
+
print(summary.groupby("router")[METRICS].mean().loc[routers].to_string(), "\n")
|
| 76 |
+
|
| 77 |
+
print(f"Paired differences to '{args.reference}' (negative = better; bootstrap 95 % CI over episodes):")
|
| 78 |
+
print(paired_table(summary, args.reference, np.random.default_rng(args.seed)).to_string(), "\n")
|
| 79 |
+
|
| 80 |
+
for factor in FACTORS:
|
| 81 |
+
if summary[factor].nunique() > 1:
|
| 82 |
+
print(f"Mean loss ratio by {factor}:")
|
| 83 |
+
print(summary.pivot_table(index=factor, columns="router", values="loss_ratio", aggfunc="mean")[routers]
|
| 84 |
+
.to_string(), "\n")
|
| 85 |
+
|
| 86 |
+
flows = ds.summary("flow_summary")
|
| 87 |
+
delivered = flows[flows.delivered > 0].copy()
|
| 88 |
+
delivered["path_stretch"] = delivered.mean_hops / delivered.min_hops
|
| 89 |
+
delivered["latency_stretch"] = delivered.mean_path_latency / delivered.min_latency
|
| 90 |
+
print("Flow level (flows with at least one delivered packet):")
|
| 91 |
+
print(delivered.groupby("router").agg(flows=("flow", "size"), lossless_share=("dropped", lambda d: np.mean(d == 0)),
|
| 92 |
+
path_stretch=("path_stretch", "mean"),
|
| 93 |
+
latency_stretch=("latency_stretch", "mean"),
|
| 94 |
+
queueing_delay=("mean_queueing_delay", "mean"),
|
| 95 |
+
p99_delay=("p99_delay", "mean")).loc[routers].to_string(), "\n")
|
| 96 |
+
|
| 97 |
+
if args.csv:
|
| 98 |
+
args.csv.parent.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
summary.to_csv(args.csv, index=False)
|
| 100 |
+
print(f"Per-episode summary written to {args.csv}")
|
| 101 |
+
print("All checks passed.")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
examples/forecast_congestion.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Forecast near-term packet loss from step-level telemetry: a learning example on the splits.
|
| 2 |
+
|
| 3 |
+
python examples/forecast_congestion.py # data/, potential router
|
| 4 |
+
python examples/forecast_congestion.py --router shortest_path --window 20 --horizon 20 --stride 10
|
| 5 |
+
|
| 6 |
+
Task: at step t, predict the network's loss ratio over the next `horizon` steps (dropped / offered)
|
| 7 |
+
from the last `window` steps of the network totals in ``network_telemetry`` (offered, delivered,
|
| 8 |
+
dropped, queued, in transit), normalised by the episode's total capacity so that networks of
|
| 9 |
+
different sizes share one feature scale, plus the recent loss ratio itself. A ridge regression (closed form, NumPy only) is fitted
|
| 10 |
+
on the train split, its penalty chosen on the validation split, and reported on the test split
|
| 11 |
+
against a persistence baseline (the loss ratio of the preceding `horizon` steps). The script
|
| 12 |
+
asserts that the splits are disjoint by episode and that no feature is undefined.
|
| 13 |
+
"""
|
| 14 |
+
import argparse
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from numpy.lib.stride_tricks import sliding_window_view
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from src.dataset import Dataset # noqa: E402
|
| 26 |
+
|
| 27 |
+
CHANNELS = ("offered", "delivered", "dropped", "queued", "in_transit")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def windows(frame: pd.DataFrame, capacity: float, n_nodes: int, window: int, horizon: int, stride: int):
|
| 31 |
+
"""Feature matrix, target, baseline and step index for one episode's step series."""
|
| 32 |
+
series = frame[list(CHANNELS)].to_numpy(np.float64)
|
| 33 |
+
steps = len(series)
|
| 34 |
+
t = np.arange(max(window, horizon), steps - horizon + 1, stride)
|
| 35 |
+
if len(t) == 0:
|
| 36 |
+
return None
|
| 37 |
+
past = sliding_window_view(series, window, axis=0)[t - window] # (samples, channels, window)
|
| 38 |
+
future = sliding_window_view(series[:, :3], horizon, axis=0)[t] # offered, delivered, dropped
|
| 39 |
+
offered_next, dropped_next = future[:, 0].sum(1), future[:, 2].sum(1)
|
| 40 |
+
recent = sliding_window_view(series[:, :3], horizon, axis=0)[t - horizon]
|
| 41 |
+
keep = offered_next > 0 # loss ratio well defined
|
| 42 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 43 |
+
baseline = np.where(recent[:, 0].sum(1) > 0, recent[:, 2].sum(1) / recent[:, 0].sum(1), 0.0)
|
| 44 |
+
features = np.concatenate([past.reshape(len(t), -1) / capacity, baseline[:, None],
|
| 45 |
+
np.full((len(t), 1), np.log10(n_nodes))], axis=1)
|
| 46 |
+
target = dropped_next / np.maximum(offered_next, 1)
|
| 47 |
+
return features[keep], target[keep], baseline[keep], t[keep]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def ridge_fit(x: np.ndarray, y: np.ndarray, lam: float) -> np.ndarray:
|
| 51 |
+
n, d = x.shape
|
| 52 |
+
return np.linalg.solve(x.T @ x / n + lam * np.eye(d), x.T @ y / n)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def metrics(y: np.ndarray, pred: np.ndarray) -> dict:
|
| 56 |
+
pred = np.clip(pred, 0.0, 1.0)
|
| 57 |
+
sse = np.sum((y - pred) ** 2)
|
| 58 |
+
return {"MAE": np.mean(np.abs(y - pred)), "RMSE": np.sqrt(sse / len(y)),
|
| 59 |
+
"R2": 1.0 - sse / max(np.sum((y - y.mean()) ** 2), 1e-12)}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main() -> None:
|
| 63 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 64 |
+
parser.add_argument("--data", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
|
| 65 |
+
parser.add_argument("--router", default="potential")
|
| 66 |
+
parser.add_argument("--window", type=int, default=10, help="steps of history used as features")
|
| 67 |
+
parser.add_argument("--horizon", type=int, default=10, help="steps ahead over which loss is predicted")
|
| 68 |
+
parser.add_argument("--stride", type=int, default=5, help="steps between consecutive samples")
|
| 69 |
+
parser.add_argument("--max-episodes", type=int, default=0, help="cap on episodes (0 = all)")
|
| 70 |
+
args = parser.parse_args()
|
| 71 |
+
pd.set_option("display.width", 160)
|
| 72 |
+
pd.set_option("display.precision", 4)
|
| 73 |
+
|
| 74 |
+
ds = Dataset(args.data)
|
| 75 |
+
episodes = ds.episodes
|
| 76 |
+
if args.max_episodes:
|
| 77 |
+
episodes = episodes.iloc[: args.max_episodes]
|
| 78 |
+
if episodes.split.nunique() < 3: # fewer than five replicates: fall back to a split by episode id
|
| 79 |
+
fallback = np.array(["train", "train", "train", "validation", "test"])[episodes.index % 5]
|
| 80 |
+
episodes = episodes.assign(split=fallback)
|
| 81 |
+
print("note: the dataset has no validation/test replicates; splitting by episode id modulo 5 instead")
|
| 82 |
+
net = ds.table("network_telemetry", columns=["episode_id", "step"] + list(CHANNELS),
|
| 83 |
+
filters=[("router", "=", args.router)])
|
| 84 |
+
net = net[net.episode_id.isin(episodes.index)].sort_values(["episode_id", "step"])
|
| 85 |
+
|
| 86 |
+
parts = {"train": [], "validation": [], "test": []}
|
| 87 |
+
seen = {s: set() for s in parts}
|
| 88 |
+
for eid, frame in net.groupby("episode_id", sort=False):
|
| 89 |
+
row = episodes.loc[eid]
|
| 90 |
+
sample = windows(frame, float(row.total_capacity), int(row.n_nodes), args.window, args.horizon, args.stride)
|
| 91 |
+
if sample is not None:
|
| 92 |
+
parts[row.split].append((eid, *sample))
|
| 93 |
+
seen[row.split].add(eid)
|
| 94 |
+
assert not (seen["train"] & seen["test"]) and not (seen["train"] & seen["validation"]), "splits overlap"
|
| 95 |
+
assert all(parts.values()), "every split needs episodes: " + ", ".join(f"{k} {len(v)}" for k, v in parts.items())
|
| 96 |
+
|
| 97 |
+
def stack(split):
|
| 98 |
+
x = np.concatenate([p[1] for p in parts[split]])
|
| 99 |
+
y = np.concatenate([p[2] for p in parts[split]])
|
| 100 |
+
b = np.concatenate([p[3] for p in parts[split]])
|
| 101 |
+
eids = np.concatenate([np.full(len(p[2]), p[0]) for p in parts[split]])
|
| 102 |
+
return x, y, b, eids
|
| 103 |
+
|
| 104 |
+
x_tr, y_tr, _, _ = stack("train")
|
| 105 |
+
x_va, y_va, b_va, _ = stack("validation")
|
| 106 |
+
x_te, y_te, b_te, e_te = stack("test")
|
| 107 |
+
assert np.isfinite(x_tr).all() and np.isfinite(x_va).all() and np.isfinite(x_te).all()
|
| 108 |
+
mean, std = x_tr.mean(0), x_tr.std(0) + 1e-12
|
| 109 |
+
z = lambda x: np.hstack([(x - mean) / std, np.ones((len(x), 1))]) # noqa: E731 standardise + intercept
|
| 110 |
+
print(f"{ds.path}: router {args.router}, window {args.window}, horizon {args.horizon}, stride {args.stride}")
|
| 111 |
+
print(f" samples: train {len(y_tr):,} ({len(seen['train'])} episodes), validation {len(y_va):,} "
|
| 112 |
+
f"({len(seen['validation'])}), test {len(y_te):,} ({len(seen['test'])}); features {x_tr.shape[1]}")
|
| 113 |
+
print(f" target: loss ratio over the next {args.horizon} steps; mean {y_tr.mean():.4f}, "
|
| 114 |
+
f"share of samples with loss {np.mean(y_tr > 0):.3f}")
|
| 115 |
+
|
| 116 |
+
grid = [10 ** k for k in range(-6, 3)]
|
| 117 |
+
scores = {lam: metrics(y_va, z(x_va) @ ridge_fit(z(x_tr), y_tr, lam))["RMSE"] for lam in grid}
|
| 118 |
+
lam = min(scores, key=scores.get)
|
| 119 |
+
w = ridge_fit(z(x_tr), y_tr, lam)
|
| 120 |
+
print(f"\nRidge penalty chosen on validation: lambda = {lam:g} (validation RMSE {scores[lam]:.4f})")
|
| 121 |
+
report = pd.DataFrame({"ridge (validation)": metrics(y_va, z(x_va) @ w),
|
| 122 |
+
"persistence (validation)": metrics(y_va, b_va),
|
| 123 |
+
"ridge (test)": metrics(y_te, z(x_te) @ w),
|
| 124 |
+
"persistence (test)": metrics(y_te, b_te)}).T
|
| 125 |
+
print(report.to_string())
|
| 126 |
+
|
| 127 |
+
test_pred = np.clip(z(x_te) @ w, 0, 1)
|
| 128 |
+
by_load = pd.DataFrame({"episode_id": e_te, "ridge_error": np.abs(y_te - test_pred),
|
| 129 |
+
"persistence_error": np.abs(y_te - b_te), "target": y_te})
|
| 130 |
+
by_load = by_load.join(episodes[["load_level", "traffic_profile"]], on="episode_id")
|
| 131 |
+
print("\nTest MAE by load level and traffic profile:")
|
| 132 |
+
print(by_load.groupby(["load_level", "traffic_profile"])[["target", "ridge_error", "persistence_error"]]
|
| 133 |
+
.mean().rename(columns={"target": "mean_loss"}).to_string())
|
| 134 |
+
print("\nAll checks passed.")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
main()
|
examples/inspect_episode.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Walk through one episode with the ``Dataset`` API and check it against the physics.
|
| 2 |
+
|
| 3 |
+
python examples/inspect_episode.py # episode 0 of data/
|
| 4 |
+
python examples/inspect_episode.py --data data_small --episode 7 --step 500 --router potential
|
| 5 |
+
|
| 6 |
+
Prints the design cell, the graph, the flows, the event timeline and the router summary; then,
|
| 7 |
+
at one step, the capacities in force, the busiest buffers and links; recomputes the potential
|
| 8 |
+
field of the tracked flows from the graph state and queue depths and compares it with the stored
|
| 9 |
+
snapshot; and follows the steepest-current descent of a tracked flow from its source to its sink.
|
| 10 |
+
Every comparison is asserted, so the script is also a test of the relational tables.
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 20 |
+
sys.path.insert(0, str(ROOT))
|
| 21 |
+
|
| 22 |
+
from src.dataset import Dataset # noqa: E402
|
| 23 |
+
from src.physics_engine import grounded_solve # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main() -> None:
|
| 27 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 28 |
+
parser.add_argument("--data", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
|
| 29 |
+
parser.add_argument("--episode", type=int, default=0)
|
| 30 |
+
parser.add_argument("--step", type=int, default=500, help="step to inspect (snapped to a logged field step)")
|
| 31 |
+
parser.add_argument("--router", default="potential", help="router whose telemetry is shown")
|
| 32 |
+
args = parser.parse_args()
|
| 33 |
+
pd.set_option("display.width", 160)
|
| 34 |
+
|
| 35 |
+
ds = Dataset(args.data)
|
| 36 |
+
ep = ds.episode(args.episode)
|
| 37 |
+
print(ep)
|
| 38 |
+
degree = np.bincount(ep.edges.ravel(), minlength=ep.n_nodes)
|
| 39 |
+
print(f" degree min/mean/max {degree.min()}/{degree.mean():.2f}/{degree.max()}, "
|
| 40 |
+
f"capacity {ep.capacity.min()}-{ep.capacity.max()} pkt/step, latency {ep.latency.min()}-{ep.latency.max()} steps, "
|
| 41 |
+
f"total directed capacity {ep.row.total_capacity:.0f} pkt/step")
|
| 42 |
+
rates = np.asarray(ep.row.flow_mean_rate)
|
| 43 |
+
print(f" flows: {ep.n_flows} between {len(ep.topology.endpoints)} endpoints, offered load rho = {ep.row.offered_load:.3f}, "
|
| 44 |
+
f"mean rate min/median/max {rates.min():.2f}/{np.median(rates):.2f}/{rates.max():.2f} pkt/step, "
|
| 45 |
+
f"tracked flows {ep.tracked_flows}, field stride {ep.field_stride}")
|
| 46 |
+
|
| 47 |
+
print(f"\nTopology events ({len(ep.events)}):")
|
| 48 |
+
if len(ep.events):
|
| 49 |
+
print(ep.events[["kind", "start", "end", "node", "edge_u", "edge_v", "factor"]].to_string(index=False))
|
| 50 |
+
else:
|
| 51 |
+
print(" none (static dynamics level)")
|
| 52 |
+
|
| 53 |
+
print("\nRouter summary:")
|
| 54 |
+
summary = ep.telemetry("router_summary").set_index("router")
|
| 55 |
+
print(summary[["loss_ratio", "mean_delay", "p99_delay", "mean_queue", "max_queue",
|
| 56 |
+
"link_utilisation", "link_saturation", "route_changes"]].to_string())
|
| 57 |
+
flows = ep.telemetry("flow_summary")
|
| 58 |
+
assert (flows.offered == flows.delivered + flows.dropped + flows.in_flight).all()
|
| 59 |
+
print(" [ok] packet conservation holds for every flow and router")
|
| 60 |
+
|
| 61 |
+
step = ep.nearest_logged_step(args.step)
|
| 62 |
+
cap = ep.capacity_at(step)
|
| 63 |
+
failed, degraded = int((cap == 0).sum()), int((cap < ep.capacity).sum() - (cap == 0).sum())
|
| 64 |
+
print(f"\nStep {step} (nearest logged field step to {args.step}): {failed} failed links, "
|
| 65 |
+
f"{degraded} links with reduced capacity, {len(ep.live_graph(step).src) // 2} live links")
|
| 66 |
+
queue = ep.queue_depth(args.router)[step]
|
| 67 |
+
busiest = np.argsort(-queue)[:5]
|
| 68 |
+
print(f" busiest buffers under {args.router}: " + ", ".join(f"node {i}: {queue[i]}" for i in busiest))
|
| 69 |
+
util = ep.link_utilisation(args.router)[step]
|
| 70 |
+
flat = np.nan_to_num(util, nan=-1).ravel()
|
| 71 |
+
top = np.argsort(-flat)[:5]
|
| 72 |
+
print(" most utilised directed links: " + ", ".join(
|
| 73 |
+
f"{ep.edges[k // 2, k % 2]}->{ep.edges[k // 2, 1 - k % 2]}: {flat[k]:.0%}" for k in top))
|
| 74 |
+
|
| 75 |
+
stored = ep.field(step)
|
| 76 |
+
queue_potential = ep.queue_depth("potential")[step] # the field responds to its own router's buffers
|
| 77 |
+
recomputed = ep.solve_field(step, queue_potential)
|
| 78 |
+
rel = np.abs(recomputed - stored).max() / np.abs(stored).max()
|
| 79 |
+
assert rel < 1e-5, rel
|
| 80 |
+
print(f" [ok] potential field of the {ep.tracked_flows} tracked flows recomputed from graph state + queues "
|
| 81 |
+
f"(max relative deviation from the stored float32 snapshot {rel:.1e})")
|
| 82 |
+
g = ep.live_graph(step)
|
| 83 |
+
b = (ep.config.background_injection / (ep.n_nodes - 1)
|
| 84 |
+
+ ep.config.congestion_gain * queue_potential.astype(np.float64) / ep.config.buffer_size)
|
| 85 |
+
b[ep.source[0]] += ep.config.source_injection
|
| 86 |
+
reference = grounded_solve(g, int(ep.sink[0]), b)
|
| 87 |
+
assert np.abs(reference - recomputed[0]).max() < 1e-9 * max(1.0, np.abs(reference).max())
|
| 88 |
+
print(" [ok] pseudo-inverse solution agrees with the sparse SuperLU solve for flow 0")
|
| 89 |
+
|
| 90 |
+
s, t = int(ep.source[0]), int(ep.sink[0])
|
| 91 |
+
path = ep.descent_path(step, recomputed[0], s, t)
|
| 92 |
+
phi = recomputed[0][path]
|
| 93 |
+
assert path[0] == s and path[-1] == t and np.all(np.diff(phi) < 0) and len(path) <= ep.n_nodes
|
| 94 |
+
print(f" [ok] steepest-current descent of flow 0 reaches its sink: {' -> '.join(map(str, path))} "
|
| 95 |
+
f"({len(path) - 1} hops, shortest possible {int(flows.min_hops.iloc[0])}); potentials "
|
| 96 |
+
+ " > ".join(f"{p:.4f}" for p in phi))
|
| 97 |
+
tracked = flows[(flows.router == args.router) & (flows.flow < ep.tracked_flows)]
|
| 98 |
+
print(f"\nTracked flows under {args.router}:")
|
| 99 |
+
print(tracked[["flow", "source", "sink", "mean_rate", "min_hops", "offered", "delivered", "dropped",
|
| 100 |
+
"loss_ratio", "mean_delay", "mean_queueing_delay", "mean_hops", "route_changes"]].to_string(index=False))
|
| 101 |
+
print("\nAll checks passed.")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
examples/visualize.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Figure gallery for a generated dataset (matplotlib, PNG).
|
| 2 |
+
|
| 3 |
+
python examples/visualize.py # every figure from data/ into figures/
|
| 4 |
+
python examples/visualize.py --data data_small --figures potential_field,timeline --episode 12 --step 400
|
| 5 |
+
|
| 6 |
+
Figures: `topologies` (one graph per family, links scaled by capacity), `benchmark` (loss and
|
| 7 |
+
delay per router by offered load, with 95 % bootstrap intervals), `timeline` (one episode step by
|
| 8 |
+
step under two routers, with bursts and topology events), `queue_heatmap` (buffer occupancy of
|
| 9 |
+
every node over time, same episode, two routers), `link_utilisation` (how often links run near
|
| 10 |
+
saturation, per router), `potential_field` (the field of one flow on the graph with the
|
| 11 |
+
steepest-current next hops and the descent path), `delays` (flow-level p99 delay and path stretch
|
| 12 |
+
per router) and `traffic_profiles` (offered packets of one flow under each profile). Colours
|
| 13 |
+
follow one fixed palette: every router keeps its hue in every figure.
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import matplotlib
|
| 20 |
+
import matplotlib.pyplot as plt
|
| 21 |
+
import networkx as nx
|
| 22 |
+
import numpy as np
|
| 23 |
+
from matplotlib.collections import LineCollection
|
| 24 |
+
from matplotlib.colors import LinearSegmentedColormap, Normalize
|
| 25 |
+
from matplotlib.ticker import FuncFormatter, MaxNLocator
|
| 26 |
+
|
| 27 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 28 |
+
sys.path.insert(0, str(ROOT))
|
| 29 |
+
|
| 30 |
+
from src.config import ROUTERS # noqa: E402
|
| 31 |
+
from src.dataset import Dataset, Episode # noqa: E402
|
| 32 |
+
from src.design import LOAD_LEVELS, TRAFFIC_PROFILES # noqa: E402
|
| 33 |
+
|
| 34 |
+
matplotlib.use("Agg")
|
| 35 |
+
|
| 36 |
+
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"] # categorical slots 1-6
|
| 37 |
+
ROUTER_COLOR = dict(zip(ROUTERS, SERIES))
|
| 38 |
+
BLUES = LinearSegmentedColormap.from_list("sequential", ["#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5",
|
| 39 |
+
"#256abf", "#184f95", "#0d366b"])
|
| 40 |
+
ACCENT, SURFACE, INK, INK2, MUTED, GRID, ALERT = "#eb6834", "#fcfcfb", "#0b0b0b", "#52514e", "#a09f9a", "#e6e5e1", "#e34948"
|
| 41 |
+
FIGURES = ("topologies", "benchmark", "timeline", "queue_heatmap", "link_utilisation",
|
| 42 |
+
"potential_field", "delays", "traffic_profiles")
|
| 43 |
+
LABEL = {"potential": "potential", "potential_split": "potential split", "potential_static": "potential static",
|
| 44 |
+
"shortest_path": "shortest path", "ecmp": "ECMP", "adaptive_shortest_path": "adaptive shortest path"}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def style() -> None:
|
| 48 |
+
plt.rcParams.update({
|
| 49 |
+
"figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
|
| 50 |
+
"font.size": 9, "axes.titlesize": 10, "axes.labelsize": 9, "axes.titleweight": "medium",
|
| 51 |
+
"text.color": INK, "axes.labelcolor": INK2, "xtick.color": INK2, "ytick.color": INK2,
|
| 52 |
+
"axes.edgecolor": GRID, "axes.spines.top": False, "axes.spines.right": False,
|
| 53 |
+
"axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.6, "axes.axisbelow": True,
|
| 54 |
+
"xtick.major.size": 0, "ytick.major.size": 0, "legend.frameon": False, "legend.fontsize": 8,
|
| 55 |
+
"lines.linewidth": 1.6,
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def save(fig, out: Path, name: str, dpi: int) -> None:
|
| 60 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 61 |
+
path = out / f"{name}.png"
|
| 62 |
+
fig.savefig(path, dpi=dpi, bbox_inches="tight")
|
| 63 |
+
plt.close(fig)
|
| 64 |
+
print(f" wrote {path}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def bootstrap_ci(values: np.ndarray, rng: np.random.Generator, samples: int = 2000):
|
| 68 |
+
means = rng.choice(values, size=(samples, len(values)), replace=True).mean(axis=1)
|
| 69 |
+
return np.percentile(means, [2.5, 97.5])
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def layout(ep: Episode) -> np.ndarray:
|
| 73 |
+
"""Node positions: true coordinates (Waxman), tiers (fat-tree) or a seeded spring layout."""
|
| 74 |
+
if len(ep.node_xy):
|
| 75 |
+
return ep.node_xy.astype(float)
|
| 76 |
+
if ep.node_role.max() > 0:
|
| 77 |
+
tier = {1: 3.0, 2: 2.0, 3: 1.0, 4: 0.0}
|
| 78 |
+
pos = np.zeros((ep.n_nodes, 2))
|
| 79 |
+
for role, y in tier.items():
|
| 80 |
+
members = np.flatnonzero(ep.node_role == role)
|
| 81 |
+
pos[members, 0] = (np.arange(len(members)) + 0.5) / len(members)
|
| 82 |
+
pos[members, 1] = y / 3.0
|
| 83 |
+
return pos
|
| 84 |
+
graph = nx.Graph()
|
| 85 |
+
graph.add_nodes_from(range(ep.n_nodes))
|
| 86 |
+
graph.add_edges_from(ep.edges.tolist())
|
| 87 |
+
spring = nx.spring_layout(graph, seed=0)
|
| 88 |
+
return np.array([spring[i] for i in range(ep.n_nodes)])
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def draw_links(ax, ep: Episode, pos: np.ndarray, capacity: np.ndarray, base: np.ndarray) -> None:
|
| 92 |
+
live = capacity > 0
|
| 93 |
+
width = 0.3 + 1.7 * base[live] / base.max()
|
| 94 |
+
ax.add_collection(LineCollection(pos[ep.edges[live]], linewidths=width, colors=MUTED, alpha=0.55, zorder=1))
|
| 95 |
+
if (~live).any():
|
| 96 |
+
ax.add_collection(LineCollection(pos[ep.edges[~live]], linewidths=1.0, colors=ALERT,
|
| 97 |
+
linestyles=(0, (2, 2)), zorder=1, label="failed link"))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def clean_axes(ax) -> None:
|
| 101 |
+
ax.set_xticks([])
|
| 102 |
+
ax.set_yticks([])
|
| 103 |
+
ax.grid(False)
|
| 104 |
+
for side in ("left", "bottom"):
|
| 105 |
+
ax.spines[side].set_visible(False)
|
| 106 |
+
ax.set_aspect("equal", adjustable="datalim")
|
| 107 |
+
ax.set_box_aspect(1)
|
| 108 |
+
ax.margins(0.05)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def fig_topologies(ds: Dataset, out: Path, dpi: int, **_) -> None:
|
| 112 |
+
episodes = ds.episodes
|
| 113 |
+
picks = episodes.sort_values("n_nodes").groupby("topology", sort=False).head(1)
|
| 114 |
+
fig, axes = plt.subplots(1, len(picks), figsize=(3.4 * len(picks), 3.4))
|
| 115 |
+
for ax, (eid, row) in zip(np.atleast_1d(axes), picks.iterrows()):
|
| 116 |
+
ep = ds.episode(eid)
|
| 117 |
+
pos = layout(ep)
|
| 118 |
+
draw_links(ax, ep, pos, ep.capacity, ep.capacity)
|
| 119 |
+
if ep.node_role.max() > 0:
|
| 120 |
+
colours = [BLUES(0.85 - 0.22 * (r - 1)) for r in ep.node_role]
|
| 121 |
+
else:
|
| 122 |
+
colours = SERIES[0]
|
| 123 |
+
ax.scatter(pos[:, 0], pos[:, 1], s=16, c=colours, edgecolors=SURFACE, linewidths=0.6, zorder=3)
|
| 124 |
+
clean_axes(ax)
|
| 125 |
+
ax.set_title(f"{row.topology.replace('_', ' ')}\n{ep.n_nodes} nodes, {ep.n_edges} links, "
|
| 126 |
+
f"mean degree {2 * ep.n_edges / ep.n_nodes:.1f}")
|
| 127 |
+
fig.suptitle("Topology families (link width proportional to capacity; fat-tree tiers core to hosts, dark to light)", y=1.02)
|
| 128 |
+
save(fig, out, "topologies", dpi)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def fig_benchmark(ds: Dataset, out: Path, dpi: int, seed: int, **_) -> None:
|
| 132 |
+
summary = ds.summary("router_summary")
|
| 133 |
+
loads = [l for l in LOAD_LEVELS if l in set(summary.load_level)]
|
| 134 |
+
routers = [r for r in ROUTERS if r in set(summary.router)]
|
| 135 |
+
rng = np.random.default_rng(seed)
|
| 136 |
+
metrics = [("loss_ratio", "loss ratio"), ("mean_delay", "mean end-to-end delay (steps)")]
|
| 137 |
+
fig, axes = plt.subplots(len(metrics), len(loads), figsize=(3.6 * len(loads), 2.6 * len(metrics)),
|
| 138 |
+
sharey=True, squeeze=False)
|
| 139 |
+
for i, (metric, label) in enumerate(metrics):
|
| 140 |
+
for j, load in enumerate(loads):
|
| 141 |
+
ax = axes[i, j]
|
| 142 |
+
sub = summary[summary.load_level == load]
|
| 143 |
+
for k, router in enumerate(routers):
|
| 144 |
+
values = sub[sub.router == router][metric].dropna().to_numpy()
|
| 145 |
+
mean = values.mean()
|
| 146 |
+
lo, hi = bootstrap_ci(values, rng)
|
| 147 |
+
y = len(routers) - 1 - k # first router on top
|
| 148 |
+
ax.barh(y, mean, height=0.72, color=ROUTER_COLOR[router], zorder=2)
|
| 149 |
+
ax.errorbar(mean, y, xerr=[[mean - lo], [hi - mean]], fmt="none", ecolor=INK2, elinewidth=0.8, capsize=2, zorder=3)
|
| 150 |
+
ax.set_yticks(range(len(routers)))
|
| 151 |
+
ax.set_yticklabels([LABEL[r] for r in reversed(routers)])
|
| 152 |
+
ax.grid(axis="y", visible=False)
|
| 153 |
+
if i == 0:
|
| 154 |
+
ax.set_title(f"{load} load ({sub.episode_id.nunique()} episodes)")
|
| 155 |
+
ax.set_xlabel(label)
|
| 156 |
+
ax.set_xlim(left=0)
|
| 157 |
+
ax.xaxis.set_major_locator(MaxNLocator(4))
|
| 158 |
+
if metric == "loss_ratio":
|
| 159 |
+
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: f"{100 * x:g}%"))
|
| 160 |
+
fig.suptitle("Router benchmark by offered load: mean over episodes with 95 % bootstrap intervals", y=1.01)
|
| 161 |
+
fig.tight_layout()
|
| 162 |
+
save(fig, out, "benchmark", dpi)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def bursting_flows(ep: Episode) -> np.ndarray:
|
| 166 |
+
"""Number of tracked flows in the burst state at every step."""
|
| 167 |
+
flows = ep.telemetry("flow_telemetry", ep.dataset.routers[0], ["episode_id", "router", "step", "flow", "mmpp_state"])
|
| 168 |
+
return flows.groupby("step").mmpp_state.sum().reindex(range(ep.steps), fill_value=0).to_numpy()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def shade_bursts(ax, mask: np.ndarray) -> None:
|
| 172 |
+
edges = np.flatnonzero(np.diff(np.r_[0, mask.astype(int), 0]))
|
| 173 |
+
for start, end in zip(edges[::2], edges[1::2]):
|
| 174 |
+
ax.axvspan(start, end, color=INK2, alpha=0.08, linewidth=0, zorder=0)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def mark_events(ax, ep: Episode) -> None:
|
| 178 |
+
for e in ep.events.itertuples():
|
| 179 |
+
ax.axvline(e.start, color=ALERT if e.kind == "link_failure" else MUTED, linewidth=0.8, zorder=1)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def fig_timeline(ds: Dataset, out: Path, dpi: int, episode: int, routers, **_) -> None:
|
| 183 |
+
ep = ds.episode(episode)
|
| 184 |
+
frames = {r: ep.telemetry("network_telemetry", r, ["episode_id", "router", "step", "offered", "delivered",
|
| 185 |
+
"dropped", "queued", "route_changes"]) for r in routers}
|
| 186 |
+
bursts = bursting_flows(ep)
|
| 187 |
+
fig, axes = plt.subplots(5, 1, figsize=(10, 8.2), sharex=True, gridspec_kw={"height_ratios": [1, 3, 3, 3, 3]})
|
| 188 |
+
axes[0].fill_between(np.arange(ep.steps), bursts, step="mid", color=INK2, alpha=0.35, linewidth=0)
|
| 189 |
+
axes[0].set_ylabel(f"tracked flows\nin burst (of {ep.tracked_flows})", fontsize=8)
|
| 190 |
+
axes[0].set_ylim(0, max(1, bursts.max()))
|
| 191 |
+
axes[0].yaxis.set_major_locator(MaxNLocator(integer=True, nbins=3))
|
| 192 |
+
panels = [("delivered", "delivered\n(packets / step)"), ("dropped", "dropped\n(packets / step)"),
|
| 193 |
+
("queued", "waiting in buffers\n(packets)"), ("route_changes", "next-hop changes\n(per step)")]
|
| 194 |
+
for ax, (column, label) in zip(axes[1:], panels):
|
| 195 |
+
if column == "delivered":
|
| 196 |
+
ax.plot(frames[routers[0]].step, frames[routers[0]].offered, color=MUTED, linewidth=1.0, label="offered")
|
| 197 |
+
for r in routers:
|
| 198 |
+
ax.plot(frames[r].step, frames[r][column], color=ROUTER_COLOR[r], label=LABEL[r])
|
| 199 |
+
ax.set_ylabel(label, fontsize=8)
|
| 200 |
+
ax.set_ylim(bottom=0)
|
| 201 |
+
for ax in axes:
|
| 202 |
+
mark_events(ax, ep)
|
| 203 |
+
axes[4].set_yscale("symlog", linthresh=10)
|
| 204 |
+
axes[4].set_xlabel("step (1 step = 1 ms)")
|
| 205 |
+
axes[1].legend(loc="upper right", ncol=3)
|
| 206 |
+
summary = ep.telemetry("router_summary").set_index("router")
|
| 207 |
+
losses = ", ".join(f"{LABEL[r]} loss {summary.loss_ratio[r]:.1%}" for r in routers)
|
| 208 |
+
fig.suptitle(f"Episode {ep.id} ({'/'.join(str(v) for v in ep.cell.values())}): {losses}\n"
|
| 209 |
+
f"vertical lines: link failure (red) or node degradation (grey) begins", fontsize=9)
|
| 210 |
+
fig.align_ylabels(axes)
|
| 211 |
+
save(fig, out, "timeline", dpi)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def fig_queue_heatmap(ds: Dataset, out: Path, dpi: int, episode: int, routers, **_) -> None:
|
| 215 |
+
ep = ds.episode(episode)
|
| 216 |
+
queues = {r: ep.queue_depth(r) for r in routers}
|
| 217 |
+
order = np.argsort(-queues[routers[-1]].mean(0)) # same node order in every panel
|
| 218 |
+
vmax = max(q.max() for q in queues.values())
|
| 219 |
+
fig, axes = plt.subplots(1, len(routers), figsize=(5.2 * len(routers), 4.2), sharey=True)
|
| 220 |
+
summary = ep.telemetry("router_summary").set_index("router")
|
| 221 |
+
for ax, r in zip(np.atleast_1d(axes), routers):
|
| 222 |
+
image = ax.imshow(queues[r][:, order].T, aspect="auto", cmap=BLUES, vmin=0, vmax=vmax,
|
| 223 |
+
interpolation="nearest", origin="upper")
|
| 224 |
+
ax.set_title(f"{LABEL[r]}: loss {summary.loss_ratio[r]:.1%}, mean occupancy {summary.mean_queue[r]:.1f}")
|
| 225 |
+
ax.set_xlabel("step (1 step = 1 ms)")
|
| 226 |
+
ax.grid(False)
|
| 227 |
+
np.atleast_1d(axes)[0].set_ylabel(f"node rank by mean occupancy under {LABEL[routers[-1]]} (busiest first)")
|
| 228 |
+
fig.colorbar(image, ax=list(np.atleast_1d(axes)), label=f"packets in buffer (capacity {ds.config.buffer_size})", shrink=0.9)
|
| 229 |
+
fig.suptitle(f"Buffer occupancy, episode {ep.id} ({'/'.join(str(v) for v in ep.cell.values())})", y=0.98)
|
| 230 |
+
save(fig, out, "queue_heatmap", dpi)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def fig_link_utilisation(ds: Dataset, out: Path, dpi: int, episode: int, **_) -> None:
|
| 234 |
+
ep = ds.episode(episode)
|
| 235 |
+
fig, ax = plt.subplots(figsize=(6.4, 4))
|
| 236 |
+
grid = np.linspace(0, 1, 101)
|
| 237 |
+
for r in [r for r in ROUTERS if r in ds.routers]:
|
| 238 |
+
util = ep.link_utilisation(r)
|
| 239 |
+
util = util[np.isfinite(util)]
|
| 240 |
+
ccdf = [(util >= x).mean() for x in grid]
|
| 241 |
+
ax.plot(grid, ccdf, color=ROUTER_COLOR[r], label=LABEL[r])
|
| 242 |
+
ax.set_yscale("log")
|
| 243 |
+
ax.set_xlabel("utilisation of a directed link in one step (packets forwarded / capacity in force)")
|
| 244 |
+
ax.set_ylabel("share of link-steps at or above this utilisation")
|
| 245 |
+
ax.set_xlim(0, 1)
|
| 246 |
+
ax.legend(loc="lower left")
|
| 247 |
+
ax.set_title(f"How often links run near saturation, episode {ep.id} ({'/'.join(str(v) for v in ep.cell.values())})")
|
| 248 |
+
save(fig, out, "link_utilisation", dpi)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def fig_potential_field(ds: Dataset, out: Path, dpi: int, episode: int, step: int, flow: int, **_) -> None:
|
| 252 |
+
ep = ds.episode(episode)
|
| 253 |
+
step = ep.nearest_logged_step(step)
|
| 254 |
+
phi = ep.field(step)[flow]
|
| 255 |
+
queue = ep.queue_depth("potential")[step].astype(np.float64) # int16 telemetry: widen before scaling
|
| 256 |
+
pos = layout(ep)
|
| 257 |
+
source, sink = int(ep.source[flow]), int(ep.sink[flow])
|
| 258 |
+
hops = ep.next_hops(step, phi[None, :])[0]
|
| 259 |
+
path = ep.descent_path(step, phi, source, sink)
|
| 260 |
+
fig, ax = plt.subplots(figsize=(8.5, 7))
|
| 261 |
+
draw_links(ax, ep, pos, ep.capacity_at(step), ep.capacity)
|
| 262 |
+
ax.add_collection(LineCollection(pos[np.stack([path[:-1], path[1:]], 1)], linewidths=3.2, colors=ACCENT,
|
| 263 |
+
zorder=2, label="descent path of the flow"))
|
| 264 |
+
valid = hops >= 0
|
| 265 |
+
start, end = pos[valid], pos[hops[valid]]
|
| 266 |
+
thin = min(1.0, (100 / ep.n_nodes) ** 0.5) # lighter arrows on large graphs
|
| 267 |
+
ax.quiver(start[:, 0], start[:, 1], (end - start)[:, 0] * 0.55, (end - start)[:, 1] * 0.55,
|
| 268 |
+
angles="xy", scale_units="xy", scale=1, width=0.0035 * thin, color=INK2, alpha=0.8, zorder=2,
|
| 269 |
+
headwidth=5, headlength=6, label="steepest-current next hop")
|
| 270 |
+
norm = Normalize(vmin=0, vmax=phi.max())
|
| 271 |
+
scatter = ax.scatter(pos[:, 0], pos[:, 1], s=18 + 160 * queue / ds.config.buffer_size, c=phi, cmap=BLUES, norm=norm,
|
| 272 |
+
edgecolors=SURFACE, linewidths=0.8, zorder=3)
|
| 273 |
+
ax.scatter(*pos[source], s=170, marker="s", facecolors="none", edgecolors=ACCENT, linewidths=2, zorder=4, label="source")
|
| 274 |
+
ax.scatter(*pos[sink], s=260, marker="*", facecolors="none", edgecolors=ACCENT, linewidths=2, zorder=4, label="sink")
|
| 275 |
+
clean_axes(ax)
|
| 276 |
+
fig.colorbar(scatter, ax=ax, label="potential of the flow (0 at its sink)", shrink=0.75)
|
| 277 |
+
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.01), ncol=4, fontsize=8)
|
| 278 |
+
ax.set_title(f"Potential field of tracked flow {flow} ({source} to {sink}), episode {ep.id}, step {step}\n"
|
| 279 |
+
f"node size: buffer occupancy under the potential router; link width: base capacity")
|
| 280 |
+
save(fig, out, "potential_field", dpi)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def fig_delays(ds: Dataset, out: Path, dpi: int, **_) -> None:
|
| 284 |
+
flows = ds.summary("flow_summary")
|
| 285 |
+
flows = flows[flows.delivered > 0].copy()
|
| 286 |
+
flows["path_stretch"] = flows.mean_hops / flows.min_hops
|
| 287 |
+
routers = [r for r in ROUTERS if r in set(flows.router)]
|
| 288 |
+
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
|
| 289 |
+
for ax, (column, label, log) in zip(axes, [("p99_delay", "flow p99 end-to-end delay (steps)", True),
|
| 290 |
+
("path_stretch", "flow path stretch (mean hops / shortest hops)", False)]):
|
| 291 |
+
data = [flows[flows.router == r][column].to_numpy() for r in routers]
|
| 292 |
+
boxes = ax.boxplot(data, vert=False, widths=0.6, showfliers=False, patch_artist=True,
|
| 293 |
+
medianprops={"color": INK, "linewidth": 1.2},
|
| 294 |
+
whiskerprops={"color": INK2, "linewidth": 0.8}, capprops={"color": INK2, "linewidth": 0.8})
|
| 295 |
+
for patch, r in zip(boxes["boxes"], routers):
|
| 296 |
+
patch.set(facecolor=ROUTER_COLOR[r], edgecolor=SURFACE, alpha=0.9)
|
| 297 |
+
ax.set_yticks(range(1, len(routers) + 1))
|
| 298 |
+
ax.set_yticklabels([LABEL[r] for r in routers])
|
| 299 |
+
ax.invert_yaxis()
|
| 300 |
+
ax.grid(axis="y", visible=False)
|
| 301 |
+
if log:
|
| 302 |
+
ax.set_xscale("log")
|
| 303 |
+
ax.set_xlabel(label)
|
| 304 |
+
fig.suptitle(f"Flow-level delay and path stretch per router ({flows.episode_id.nunique()} episodes, "
|
| 305 |
+
f"{len(flows) // len(routers):,} delivered flows each; boxes: quartiles, whiskers: 1.5 IQR)", y=1.02)
|
| 306 |
+
fig.tight_layout()
|
| 307 |
+
save(fig, out, "delays", dpi)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def fig_traffic_profiles(ds: Dataset, out: Path, dpi: int, **_) -> None:
|
| 311 |
+
episodes = ds.episodes
|
| 312 |
+
profiles = [p for p in TRAFFIC_PROFILES if p in set(episodes.traffic_profile)]
|
| 313 |
+
fig, axes = plt.subplots(len(profiles), 1, figsize=(10, 1.9 * len(profiles) + 0.6), sharex=True, squeeze=False)
|
| 314 |
+
order = {"heavy": 0, "moderate": 1, "light": 2}
|
| 315 |
+
for ax, profile in zip(axes[:, 0], profiles):
|
| 316 |
+
candidates = episodes[episodes.traffic_profile == profile]
|
| 317 |
+
eid = candidates.index[np.argsort(candidates.load_level.map(order).to_numpy(), kind="stable")[0]]
|
| 318 |
+
ep = ds.episode(eid)
|
| 319 |
+
f = int(np.argmax(np.asarray(ep.row.flow_mean_rate)[: ep.tracked_flows])) # largest tracked flow
|
| 320 |
+
flow = ep.telemetry("flow_telemetry", ds.routers[0], ["episode_id", "router", "step", "flow", "offered", "mmpp_state"])
|
| 321 |
+
flow = flow[flow.flow == f]
|
| 322 |
+
shade_bursts(ax, flow.mmpp_state.to_numpy() > 0)
|
| 323 |
+
ax.plot(flow.step, flow.offered, color=SERIES[0], linewidth=1.0)
|
| 324 |
+
ax.set_ylabel("packets / step", fontsize=8)
|
| 325 |
+
ax.set_ylim(bottom=0)
|
| 326 |
+
ax.set_title(f"{profile}: flow {f} of episode {eid} ({ep.row.load_level} load), mean rate "
|
| 327 |
+
f"{ep.row.flow_mean_rate[f]:.2f} packets/step (idle {ep.row.flow_idle_rate[f]:.2f}, "
|
| 328 |
+
f"burst {ep.row.flow_burst_rate[f]:.2f})", loc="left")
|
| 329 |
+
axes[-1, 0].set_xlabel("step (1 step = 1 ms)")
|
| 330 |
+
fig.suptitle("Traffic profiles: offered packets of one flow (grey bands: burst state)", y=1.0)
|
| 331 |
+
fig.tight_layout()
|
| 332 |
+
save(fig, out, "traffic_profiles", dpi)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def choose_episode(ds: Dataset) -> int:
|
| 336 |
+
"""A busy episode: heaviest load, burstiest profile and most dynamic level present."""
|
| 337 |
+
episodes = ds.episodes.reset_index()
|
| 338 |
+
rank = {"heavy": 0, "moderate": 1, "light": 2}, {"microburst": 0, "sustained": 1, "poisson": 2}, {"severe": 0, "moderate": 1, "static": 2}
|
| 339 |
+
key = (episodes.load_level.map(rank[0]) * 100 + episodes.traffic_profile.map(rank[1]) * 10
|
| 340 |
+
+ episodes.dynamics_level.map(rank[2]))
|
| 341 |
+
return int(episodes.episode_id[key.idxmin()])
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def main() -> None:
|
| 345 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 346 |
+
parser.add_argument("--data", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
|
| 347 |
+
parser.add_argument("--out", type=Path, default=ROOT / "figures", help="output folder (default: figures/)")
|
| 348 |
+
parser.add_argument("--figures", default="all", help="comma-separated subset of " + ",".join(FIGURES))
|
| 349 |
+
parser.add_argument("--episode", type=int, default=None, help="episode for the single-episode figures (default: a busy one)")
|
| 350 |
+
parser.add_argument("--step", type=int, default=500, help="step for the potential-field figure")
|
| 351 |
+
parser.add_argument("--flow", type=int, default=0, help="tracked flow for the potential-field figure")
|
| 352 |
+
parser.add_argument("--routers", default="potential,shortest_path", help="two routers for the timeline and heatmap")
|
| 353 |
+
parser.add_argument("--dpi", type=int, default=150)
|
| 354 |
+
parser.add_argument("--seed", type=int, default=0, help="bootstrap seed")
|
| 355 |
+
args = parser.parse_args()
|
| 356 |
+
|
| 357 |
+
style()
|
| 358 |
+
ds = Dataset(args.data)
|
| 359 |
+
wanted = FIGURES if args.figures == "all" else tuple(args.figures.split(","))
|
| 360 |
+
unknown = set(wanted) - set(FIGURES)
|
| 361 |
+
assert not unknown, f"unknown figures {unknown}; choose from {FIGURES}"
|
| 362 |
+
routers = tuple(args.routers.split(","))
|
| 363 |
+
assert all(r in ds.routers for r in routers), f"routers must be among {ds.routers}"
|
| 364 |
+
episode = choose_episode(ds) if args.episode is None else args.episode
|
| 365 |
+
print(f"{ds.path}: {len(ds.episodes)} episodes; single-episode figures use episode {episode}")
|
| 366 |
+
for name in wanted:
|
| 367 |
+
globals()[f"fig_{name}"](ds, args.out, args.dpi, seed=args.seed, episode=episode,
|
| 368 |
+
step=args.step, flow=args.flow, routers=routers)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
if __name__ == "__main__":
|
| 372 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.26
|
| 2 |
+
scipy>=1.11
|
| 3 |
+
pandas>=2.0
|
| 4 |
+
pyarrow>=15.0
|
| 5 |
+
networkx>=3.1
|
| 6 |
+
huggingface_hub>=0.34
|
| 7 |
+
matplotlib>=3.7
|
scripts/push_to_huggingface.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish the generated dataset to the Hugging Face Hub (the one manual step).
|
| 2 |
+
|
| 3 |
+
hf auth login # once, paste a write token
|
| 4 |
+
python scripts/push_to_huggingface.py --repo <user>/<dataset> # add --private if you like
|
| 5 |
+
|
| 6 |
+
The whole project folder becomes the dataset repository: the Parquet shards in data/ (with
|
| 7 |
+
config.json and manifest.json), the README.md dataset card whose `configs:` block makes every
|
| 8 |
+
table browsable in the Dataset Viewer, and the generator source, so the dataset is reproducible
|
| 9 |
+
from the repository alone. The upload is resumable: re-run the same command after any
|
| 10 |
+
interruption and it continues where it stopped (its bookkeeping lives in .cache/, ignored by git).
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
from huggingface_hub import HfApi
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 19 |
+
IGNORE = ["__pycache__/**", "*.pyc", "*.tmp", ".git/**", ".gitignore", ".cache/**", ".DS_Store",
|
| 20 |
+
"data_*/**", "*.log"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main() -> None:
|
| 24 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 25 |
+
parser.add_argument("--repo", required=True, help="dataset repository id, e.g. alexander/semantic-potential-routing")
|
| 26 |
+
parser.add_argument("--private", action="store_true", help="create the repository as private")
|
| 27 |
+
parser.add_argument("--token", default=os.environ.get("HF_TOKEN"), help="write token (default: HF_TOKEN or cached login)")
|
| 28 |
+
parser.add_argument("--workers", type=int, default=None, help="parallel upload workers (default: library choice)")
|
| 29 |
+
args = parser.parse_args()
|
| 30 |
+
|
| 31 |
+
shards = sorted((ROOT / "data").glob("*/part-*.parquet"))
|
| 32 |
+
if not shards or not (ROOT / "data" / "manifest.json").exists():
|
| 33 |
+
raise SystemExit("No finished dataset in data/ - run scripts/run_local_sweep.py first.")
|
| 34 |
+
print(f"Uploading {len(shards)} Parquet shards "
|
| 35 |
+
f"({sum(f.stat().st_size for f in shards) / 1e9:.2f} GB) plus README and source to {args.repo} ...")
|
| 36 |
+
|
| 37 |
+
api = HfApi(token=args.token)
|
| 38 |
+
api.create_repo(args.repo, repo_type="dataset", private=args.private, exist_ok=True)
|
| 39 |
+
api.upload_large_folder(repo_id=args.repo, folder_path=ROOT, repo_type="dataset",
|
| 40 |
+
ignore_patterns=IGNORE, num_workers=args.workers)
|
| 41 |
+
print(f"Done: https://huggingface.co/datasets/{args.repo}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
main()
|
scripts/run_local_sweep.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate the dataset on this machine.
|
| 2 |
+
|
| 3 |
+
python scripts/run_local_sweep.py --smoke # ~1-minute end-to-end check in a temporary folder
|
| 4 |
+
python scripts/run_local_sweep.py # full design with the defaults into data/
|
| 5 |
+
python scripts/run_local_sweep.py --help # every design level and model knob is a flag
|
| 6 |
+
|
| 7 |
+
Every CPU core runs independent Monte Carlo episodes; shards are streamed to Parquet as they
|
| 8 |
+
complete, and re-running the same command resumes an interrupted sweep. When the sweep finishes
|
| 9 |
+
the script writes data/manifest.json and prints the router benchmark, the design coverage and the
|
| 10 |
+
size of every table.
|
| 11 |
+
"""
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
|
| 15 |
+
os.environ.setdefault(_var, "1") # one BLAS thread per worker process; parallelism comes from the pool
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import shutil
|
| 19 |
+
import sys
|
| 20 |
+
import tempfile
|
| 21 |
+
from dataclasses import fields, replace
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 25 |
+
sys.path.insert(0, str(ROOT))
|
| 26 |
+
|
| 27 |
+
from src.config import DATASET_VERSION, SimConfig # noqa: E402
|
| 28 |
+
from src.simulation_loop import run_sweep # noqa: E402
|
| 29 |
+
from src.telemetry_logger import read_table, write_manifest # noqa: E402
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def parse_args() -> argparse.Namespace:
|
| 33 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 34 |
+
parser.add_argument("--out", type=Path, default=ROOT / "data", help="output folder (default: data/)")
|
| 35 |
+
parser.add_argument("--workers", type=int, default=os.cpu_count(), help="worker processes (default: all cores)")
|
| 36 |
+
parser.add_argument("--smoke", action="store_true", help="tiny sweep over every family, profile and router "
|
| 37 |
+
"in a temporary folder, deleted afterwards")
|
| 38 |
+
group = parser.add_argument_group("design and model configuration")
|
| 39 |
+
for f in fields(SimConfig):
|
| 40 |
+
if isinstance(f.default, tuple):
|
| 41 |
+
item = type(f.default[0])
|
| 42 |
+
kind = lambda s, item=item: tuple(item(x) for x in s.split(",")) # noqa: E731
|
| 43 |
+
shown = ",".join(str(x) for x in f.default)
|
| 44 |
+
else:
|
| 45 |
+
kind, shown = type(f.default), f.default
|
| 46 |
+
group.add_argument(f"--{f.name}", type=kind, default=None, metavar="",
|
| 47 |
+
help=f"{f.metadata['help']} (default: {shown})")
|
| 48 |
+
return parser.parse_args()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def summarize(data_dir: Path, cfg: SimConfig) -> None:
|
| 52 |
+
manifest = write_manifest(data_dir, cfg, DATASET_VERSION)
|
| 53 |
+
summary = read_table(data_dir, "router_summary").to_pandas()
|
| 54 |
+
bench = summary.groupby("router").agg(
|
| 55 |
+
loss_ratio=("loss_ratio", "mean"), mean_delay=("mean_delay", "mean"), p99_delay=("p99_delay", "mean"),
|
| 56 |
+
link_utilisation=("link_utilisation", "mean"), route_changes=("route_changes", "mean"))
|
| 57 |
+
print("\nRouter benchmark (means over episodes):")
|
| 58 |
+
print(bench.round(3).to_string())
|
| 59 |
+
print("\nDesign coverage (episodes per level):")
|
| 60 |
+
for factor, counts in manifest["coverage"].items():
|
| 61 |
+
print(f" {factor:16s} " + " ".join(f"{k}={v}" for k, v in counts.items()))
|
| 62 |
+
design = manifest["design"]
|
| 63 |
+
print(f" cells {design['cells']}, episodes {design['episodes_present']}/{design['episodes_planned']}, "
|
| 64 |
+
f"per cell {design['episodes_per_cell_min']}-{design['episodes_per_cell_max']}")
|
| 65 |
+
print("\nTables:")
|
| 66 |
+
total = 0
|
| 67 |
+
for name, stats in manifest["tables"].items():
|
| 68 |
+
total += stats["bytes"]
|
| 69 |
+
print(f" {name:18s} {stats['files']:5d} files {stats['rows']:14,d} rows {stats['bytes'] / 1e9:8.2f} GB")
|
| 70 |
+
print(f" {'total':18s} {'':5s} {'':14s} {total / 1e9:8.2f} GB")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main() -> None:
|
| 74 |
+
args = parse_args()
|
| 75 |
+
overrides = {f.name: getattr(args, f.name) for f in fields(SimConfig) if getattr(args, f.name) is not None}
|
| 76 |
+
cfg = SimConfig(**overrides)
|
| 77 |
+
data_dir = args.out
|
| 78 |
+
if args.smoke:
|
| 79 |
+
cfg = replace(cfg, replicates=1, sizes=(32,), load_levels=("heavy",), dynamics_levels=("severe",),
|
| 80 |
+
steps=200, shard_episodes=5)
|
| 81 |
+
data_dir = Path(tempfile.mkdtemp(prefix="sprt-smoke-"))
|
| 82 |
+
print(f"Smoke test in {data_dir}")
|
| 83 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
config_path = data_dir / "config.json"
|
| 85 |
+
if config_path.exists() and SimConfig.load(config_path) != cfg:
|
| 86 |
+
sys.exit(f"{config_path} was written by a different configuration; use another --out folder "
|
| 87 |
+
f"or delete it to start over.")
|
| 88 |
+
cfg.save(config_path)
|
| 89 |
+
try:
|
| 90 |
+
run_sweep(cfg, data_dir, max(1, min(args.workers, cfg.episodes)))
|
| 91 |
+
summarize(data_dir, cfg)
|
| 92 |
+
if args.smoke:
|
| 93 |
+
print("\nSmoke test passed.")
|
| 94 |
+
finally:
|
| 95 |
+
if args.smoke:
|
| 96 |
+
shutil.rmtree(data_dir, ignore_errors=True)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
main()
|
scripts/validate_dataset.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate a generated dataset: structure, design coverage, physical invariants and reproducibility.
|
| 2 |
+
|
| 3 |
+
python scripts/validate_dataset.py # validates data/
|
| 4 |
+
python scripts/validate_dataset.py --out data_large --resimulate 5
|
| 5 |
+
|
| 6 |
+
Checks, in order: every shard has every table; the design is balanced and the splits present;
|
| 7 |
+
packet conservation and metric consistency across the summary and telemetry tables; buffers,
|
| 8 |
+
link loads and potentials respect their physical bounds; a sample of episodes re-simulated from
|
| 9 |
+
``config.json`` reproduces the stored tables bit for bit; and a stored potential-field snapshot
|
| 10 |
+
is recovered from the graph state and queue depths with the sparse SuperLU reference solver.
|
| 11 |
+
Exits with status 1 if any check fails.
|
| 12 |
+
|
| 13 |
+
The step-level tables are far larger than memory at the full design (``flow_telemetry`` alone is
|
| 14 |
+
episodes x routers x steps x tracked_flows = 2.6e8 rows), so every check over them streams the
|
| 15 |
+
shards one record batch at a time and folds partial aggregates together; peak memory is a few
|
| 16 |
+
hundred MB regardless of dataset size.
|
| 17 |
+
"""
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
|
| 21 |
+
os.environ.setdefault(_var, "1")
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import sys
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Iterator, Sequence
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import pyarrow as pa
|
| 31 |
+
import pyarrow.dataset as pads
|
| 32 |
+
|
| 33 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 34 |
+
sys.path.insert(0, str(ROOT))
|
| 35 |
+
|
| 36 |
+
from src.config import SimConfig # noqa: E402
|
| 37 |
+
from src.graph_generator import effective_capacity, TopologyEvent, Topology # noqa: E402
|
| 38 |
+
from src.physics_engine import grounded_solve, live_graph # noqa: E402
|
| 39 |
+
from src.simulation_loop import simulate_episode # noqa: E402
|
| 40 |
+
from src.telemetry_logger import read_table, shard_files, table_names # noqa: E402
|
| 41 |
+
|
| 42 |
+
BATCH_ROWS = 1 << 18 # rows per streamed record batch (~10 MB for the scalar telemetry columns)
|
| 43 |
+
READAHEAD = 2 # batches/fragments the scanner may buffer ahead; keeps peak memory flat
|
| 44 |
+
FOLD_EVERY = 8 # partial aggregates combined before they accumulate
|
| 45 |
+
|
| 46 |
+
failures = []
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def check(condition: bool, message: str) -> None:
|
| 50 |
+
status = "ok " if condition else "FAIL"
|
| 51 |
+
print(f" [{status}] {message}")
|
| 52 |
+
if not condition:
|
| 53 |
+
failures.append(message)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# --------------------------------------------------------------------------------------
|
| 57 |
+
# Streaming helpers. Nothing below ever materialises a whole step-level table: the shards are
|
| 58 |
+
# read one record batch at a time and folded into a dense per-group accumulator whose size is
|
| 59 |
+
# fixed by the design (episodes x routers x tracked flows), not by the number of rows.
|
| 60 |
+
# --------------------------------------------------------------------------------------
|
| 61 |
+
|
| 62 |
+
def scan(data_dir: Path, table: str, columns: Sequence[str], filter=None,
|
| 63 |
+
batch_rows: int = BATCH_ROWS) -> Iterator[pa.RecordBatch]:
|
| 64 |
+
"""Record batches of a table's shards, reading only `columns`."""
|
| 65 |
+
files = [str(p) for p in shard_files(data_dir, table)]
|
| 66 |
+
dataset = pads.dataset(files, format="parquet")
|
| 67 |
+
yield from dataset.to_batches(columns=list(columns), filter=filter, batch_size=batch_rows,
|
| 68 |
+
batch_readahead=READAHEAD, fragment_readahead=READAHEAD)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class Groups:
|
| 72 |
+
"""Dense (episode, router[, flow]) -> slot mapping shared by a telemetry and a summary table."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, episode_ids: Sequence[int], routers: Sequence[str], width: int = 1):
|
| 75 |
+
ids = np.asarray(sorted(int(e) for e in episode_ids), np.int64)
|
| 76 |
+
self.episode_ids = ids
|
| 77 |
+
self.lookup = np.full(int(ids.max()) + 1, -1, np.int64)
|
| 78 |
+
self.lookup[ids] = np.arange(len(ids))
|
| 79 |
+
self.routers = list(routers)
|
| 80 |
+
self.router_slot = {r: i for i, r in enumerate(self.routers)}
|
| 81 |
+
self.width = int(width)
|
| 82 |
+
self.size = len(ids) * len(self.routers) * self.width
|
| 83 |
+
|
| 84 |
+
def slots(self, batch: pa.RecordBatch) -> np.ndarray:
|
| 85 |
+
episode = self.lookup[batch.column("episode_id").to_numpy(zero_copy_only=False).astype(np.int64)]
|
| 86 |
+
encoded = batch.column("router").dictionary_encode()
|
| 87 |
+
codes = np.array([self.router_slot[v] for v in encoded.dictionary.to_pylist()], np.int64)
|
| 88 |
+
router = codes[encoded.indices.to_numpy(zero_copy_only=False).astype(np.int64)]
|
| 89 |
+
slot = (episode * len(self.routers) + router) * self.width
|
| 90 |
+
if self.width > 1:
|
| 91 |
+
slot = slot + batch.column("flow").to_numpy(zero_copy_only=False).astype(np.int64)
|
| 92 |
+
return slot
|
| 93 |
+
|
| 94 |
+
def label(self, slot: int) -> str:
|
| 95 |
+
episode, rest = divmod(int(slot), len(self.routers) * self.width)
|
| 96 |
+
router, flow = divmod(rest, self.width)
|
| 97 |
+
name = f"episode {self.episode_ids[episode]}, router {self.routers[router]}"
|
| 98 |
+
return name + (f", flow {flow}" if self.width > 1 else "")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class Sums:
|
| 102 |
+
"""Per-group sums of integer counters, accumulated batch by batch."""
|
| 103 |
+
|
| 104 |
+
def __init__(self, groups: Groups, values: Sequence[str]):
|
| 105 |
+
self.groups = groups
|
| 106 |
+
self.values = list(values)
|
| 107 |
+
self.rows = np.zeros(groups.size, np.int64)
|
| 108 |
+
self.totals = {v: np.zeros(groups.size, np.int64) for v in self.values}
|
| 109 |
+
|
| 110 |
+
def add(self, batch: pa.RecordBatch) -> None:
|
| 111 |
+
slot = self.groups.slots(batch)
|
| 112 |
+
self.rows += np.bincount(slot, minlength=self.groups.size)
|
| 113 |
+
for name in self.values:
|
| 114 |
+
column = batch.column(name).to_numpy(zero_copy_only=False).astype(np.float64)
|
| 115 |
+
self.totals[name] += np.rint(np.bincount(slot, weights=column,
|
| 116 |
+
minlength=self.groups.size)).astype(np.int64)
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def present(self) -> np.ndarray:
|
| 120 |
+
return self.rows > 0
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def accumulate(data_dir: Path, table: str, groups: Groups, values: Sequence[str],
|
| 124 |
+
batch_rows: int = BATCH_ROWS, on_batch=None) -> Sums:
|
| 125 |
+
"""Stream `table` and sum `values` per group."""
|
| 126 |
+
sums = Sums(groups, values)
|
| 127 |
+
columns = ["episode_id", "router"] + (["flow"] if groups.width > 1 else [])
|
| 128 |
+
extra = [v for v in values if v not in columns]
|
| 129 |
+
for batch in scan(data_dir, table, columns + extra, batch_rows=batch_rows):
|
| 130 |
+
if on_batch is not None:
|
| 131 |
+
on_batch(batch)
|
| 132 |
+
sums.add(batch)
|
| 133 |
+
return sums
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def compare_sums(streamed: Sums, reference: Sums, columns: Sequence[str], label: str) -> None:
|
| 137 |
+
"""Check that per-group sums streamed from a telemetry table equal those of a summary table."""
|
| 138 |
+
groups = streamed.groups
|
| 139 |
+
same_groups = bool((streamed.present == reference.present).all())
|
| 140 |
+
if not same_groups:
|
| 141 |
+
missing = np.flatnonzero(streamed.present != reference.present)
|
| 142 |
+
check(False, f"{label}: {len(missing)} group(s) on one side only, e.g. {groups.label(missing[0])}")
|
| 143 |
+
return
|
| 144 |
+
check(True, f"{label}: the same groups appear in both tables")
|
| 145 |
+
where = streamed.present
|
| 146 |
+
bad = [c for c in columns if not bool((streamed.totals[c][where] == reference.totals[c][where]).all())]
|
| 147 |
+
if bad:
|
| 148 |
+
c = bad[0]
|
| 149 |
+
first = np.flatnonzero(where & (streamed.totals[c] != reference.totals[c]))[0]
|
| 150 |
+
check(False, f"{label} (differs in {', '.join(bad)}; first at {groups.label(first)}: "
|
| 151 |
+
f"{streamed.totals[c][first]} vs {reference.totals[c][first]})")
|
| 152 |
+
else:
|
| 153 |
+
check(True, label)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# --------------------------------------------------------------------------------------
|
| 157 |
+
# Checks
|
| 158 |
+
# --------------------------------------------------------------------------------------
|
| 159 |
+
|
| 160 |
+
def structure(data_dir: Path, cfg: SimConfig) -> int:
|
| 161 |
+
print("Structure")
|
| 162 |
+
tables = table_names(cfg.routers)
|
| 163 |
+
counts = {t: len(shard_files(data_dir, t)) for t in tables}
|
| 164 |
+
n_shards = max(counts.values()) if counts else 0
|
| 165 |
+
check(n_shards > 0, f"{n_shards} shards present")
|
| 166 |
+
check(all(c == n_shards for c in counts.values()), "every table has every shard")
|
| 167 |
+
check((data_dir / "manifest.json").exists(), "manifest.json present")
|
| 168 |
+
return n_shards
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def coverage(data_dir: Path, cfg: SimConfig) -> None:
|
| 172 |
+
print("Design coverage")
|
| 173 |
+
ep = read_table(data_dir, "episodes", columns=["episode_id", "cell_id", "replicate", "split"]).to_pandas()
|
| 174 |
+
per_cell = ep.cell_id.value_counts()
|
| 175 |
+
check(len(per_cell) == len(cfg.cells), f"all {len(cfg.cells)} design cells present")
|
| 176 |
+
check(per_cell.max() - per_cell.min() <= 1, f"balanced: {per_cell.min()}-{per_cell.max()} episodes per cell")
|
| 177 |
+
check(ep.episode_id.is_unique, "episode ids unique")
|
| 178 |
+
check({"train", "validation", "test"} <= set(ep.split) or cfg.replicates < 5,
|
| 179 |
+
f"splits present: {sorted(set(ep.split))}")
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
FLOW_SUMMARY_COLUMNS = ["offered", "delivered", "dropped", "in_flight", "loss_ratio", "mean_delay",
|
| 183 |
+
"min_latency", "min_hops", "mean_hops", "p50_delay", "p95_delay", "p99_delay",
|
| 184 |
+
"max_delay", "mean_queueing_delay", "mean_path_latency"]
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def flow_summary_elementwise(data_dir: Path, batch_rows: int) -> None:
|
| 188 |
+
"""Per-row invariants of flow_summary, accumulated over streamed batches."""
|
| 189 |
+
results = dict(conservation=True, loss=True, delay=True, hops=True, quantiles=True, decomposition=True)
|
| 190 |
+
for batch in scan(data_dir, "flow_summary", FLOW_SUMMARY_COLUMNS, batch_rows=batch_rows):
|
| 191 |
+
c = {name: batch.column(name).to_numpy(zero_copy_only=False) for name in FLOW_SUMMARY_COLUMNS}
|
| 192 |
+
ok = c["delivered"] > 0
|
| 193 |
+
results["conservation"] &= bool((c["offered"] == c["delivered"] + c["dropped"] + c["in_flight"]).all())
|
| 194 |
+
results["loss"] &= bool(((c["loss_ratio"] >= 0) & (c["loss_ratio"] <= 1)).all())
|
| 195 |
+
results["delay"] &= bool((c["mean_delay"][ok] >= c["min_latency"][ok] - 1e-3).all())
|
| 196 |
+
results["hops"] &= bool((c["mean_hops"][ok] >= c["min_hops"][ok] - 1e-3).all())
|
| 197 |
+
results["quantiles"] &= bool(((c["p50_delay"][ok] <= c["p95_delay"][ok] + 1e-3)
|
| 198 |
+
& (c["p95_delay"][ok] <= c["p99_delay"][ok] + 1e-3)
|
| 199 |
+
& (c["p99_delay"][ok] <= c["max_delay"][ok] + 1e-3)).all())
|
| 200 |
+
results["decomposition"] &= bool(np.allclose(c["mean_delay"][ok],
|
| 201 |
+
c["mean_queueing_delay"][ok] + c["mean_path_latency"][ok],
|
| 202 |
+
atol=1e-2))
|
| 203 |
+
check(results["conservation"], "flow conservation: offered = delivered + dropped + in-flight")
|
| 204 |
+
check(results["loss"], "loss ratio within [0, 1]")
|
| 205 |
+
check(results["delay"], "mean delay >= minimum path latency")
|
| 206 |
+
check(results["hops"], "mean hops >= minimum hop count")
|
| 207 |
+
check(results["quantiles"], "delay quantiles ordered")
|
| 208 |
+
check(results["decomposition"], "delay = queueing + propagation")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def invariants(data_dir: Path, cfg: SimConfig, batch_rows: int = BATCH_ROWS) -> None:
|
| 212 |
+
print("Invariants")
|
| 213 |
+
flow_summary_elementwise(data_dir, batch_rows)
|
| 214 |
+
|
| 215 |
+
episode_ids = read_table(data_dir, "episodes", columns=["episode_id"]).column("episode_id").to_pylist()
|
| 216 |
+
counters = ["offered", "delivered", "dropped", "in_flight"]
|
| 217 |
+
per_router = Groups(episode_ids, cfg.routers)
|
| 218 |
+
|
| 219 |
+
router_summary = read_table(data_dir, "router_summary")
|
| 220 |
+
reference = Sums(per_router, counters)
|
| 221 |
+
for batch in router_summary.to_batches():
|
| 222 |
+
reference.add(batch)
|
| 223 |
+
check(bool((reference.rows <= 1).all()), "router_summary has one row per (episode, router)")
|
| 224 |
+
compare_sums(accumulate(data_dir, "flow_summary", per_router, counters, batch_rows),
|
| 225 |
+
reference, counters, "router summary equals the sum of its flows")
|
| 226 |
+
util = router_summary.column("link_utilisation").to_numpy(zero_copy_only=False)
|
| 227 |
+
sat = router_summary.column("link_saturation").to_numpy(zero_copy_only=False)
|
| 228 |
+
check(bool(((util >= 0) & (util <= 1) & (sat >= 0) & (sat <= 1)).all()), "utilisation within [0, 1]")
|
| 229 |
+
|
| 230 |
+
admission = {"ok": True}
|
| 231 |
+
|
| 232 |
+
def admitted_le_offered(batch: pa.RecordBatch) -> None:
|
| 233 |
+
admission["ok"] &= bool((batch.column("admitted").to_numpy(zero_copy_only=False)
|
| 234 |
+
<= batch.column("offered").to_numpy(zero_copy_only=False)).all())
|
| 235 |
+
|
| 236 |
+
steps = ["offered", "delivered", "dropped"]
|
| 237 |
+
compare_sums(accumulate(data_dir, "network_telemetry", per_router, steps + ["admitted"], batch_rows,
|
| 238 |
+
on_batch=admitted_le_offered),
|
| 239 |
+
reference, steps, "network telemetry sums to the router summary")
|
| 240 |
+
|
| 241 |
+
per_flow = Groups(episode_ids, cfg.routers, width=int(cfg.tracked_flows))
|
| 242 |
+
tracked = accumulate(data_dir, "flow_telemetry", per_flow, steps + ["admitted"], batch_rows,
|
| 243 |
+
on_batch=admitted_le_offered)
|
| 244 |
+
flow_reference = Sums(per_flow, steps)
|
| 245 |
+
for batch in scan(data_dir, "flow_summary", ["episode_id", "router", "flow"] + steps,
|
| 246 |
+
filter=pads.field("flow") < int(cfg.tracked_flows), batch_rows=batch_rows):
|
| 247 |
+
flow_reference.add(batch)
|
| 248 |
+
compare_sums(tracked, flow_reference, steps, "tracked-flow telemetry sums to the flow summary")
|
| 249 |
+
check(admission["ok"], "admitted <= offered")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def physical_bounds(data_dir: Path, cfg: SimConfig, episode_ids) -> None:
|
| 253 |
+
print("Physical bounds (sampled episodes)")
|
| 254 |
+
episodes = read_table(data_dir, "episodes").to_pandas().set_index("episode_id")
|
| 255 |
+
events = read_table(data_dir, "events").to_pandas()
|
| 256 |
+
for eid in episode_ids:
|
| 257 |
+
ep = episodes.loc[eid]
|
| 258 |
+
net = read_table(data_dir, "network_telemetry", filters=[("episode_id", "=", int(eid))]).to_pandas()
|
| 259 |
+
queue = np.stack(net.queue_depth)
|
| 260 |
+
check(queue.min() >= 0 and queue.max() <= cfg.buffer_size, f"episode {eid}: queue depths within the buffer")
|
| 261 |
+
check((np.stack(net.node_dropped).sum(1) == net.dropped).all(), f"episode {eid}: node drops sum to step drops")
|
| 262 |
+
link = read_table(data_dir, "link_telemetry", filters=[("episode_id", "=", int(eid))]).to_pandas()
|
| 263 |
+
topo = Topology(int(ep.n_nodes), np.stack([ep.edge_u, ep.edge_v], 1).astype(np.int16),
|
| 264 |
+
ep.capacity.astype(np.int16), ep.latency.astype(np.int16),
|
| 265 |
+
np.zeros(0, np.int16), np.zeros(0, np.int8), np.zeros((0, 2), np.float32))
|
| 266 |
+
evs = [TopologyEvent(e.kind, int(e.start), int(e.end),
|
| 267 |
+
edge=int(np.flatnonzero((ep.edge_u == e.edge_u) & (ep.edge_v == e.edge_v))[0]) if e.kind == "link_failure" else -1,
|
| 268 |
+
node=int(e.node), factor=float(e.factor))
|
| 269 |
+
for e in events[events.episode_id == eid].itertuples()]
|
| 270 |
+
steps = sorted({0} | {e.start for e in evs} | {e.end for e in evs if e.end < ep.steps})
|
| 271 |
+
cap_at = {t: effective_capacity(topo, evs, t) for t in steps}
|
| 272 |
+
bounds = np.array([cap_at[steps[np.searchsorted(steps, t, side="right") - 1]] for t in link.step])
|
| 273 |
+
loads = np.maximum(np.stack(link.load_uv), np.stack(link.load_vu))
|
| 274 |
+
check((loads <= bounds).all(), f"episode {eid}: link loads never exceed the capacity in force")
|
| 275 |
+
if "potential_field" in table_names(cfg.routers):
|
| 276 |
+
pf = read_table(data_dir, "potential_field", filters=[("episode_id", "=", int(eid))]).to_pandas()
|
| 277 |
+
phi = np.stack(pf.potential).reshape(len(pf), int(ep.tracked_flows), int(ep.n_nodes))
|
| 278 |
+
sinks = ep.flow_sink[: int(ep.tracked_flows)]
|
| 279 |
+
check(phi.min() >= 0 and np.all(phi[:, np.arange(len(sinks)), sinks] == 0),
|
| 280 |
+
f"episode {eid}: potentials non-negative and zero at the sinks")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def tables_equal(a: pa.Table, b: pa.Table) -> bool:
|
| 284 |
+
"""Exact equality of two tables, treating NaN as equal to NaN."""
|
| 285 |
+
if a.num_rows != b.num_rows or not a.schema.equals(b.schema, check_metadata=False):
|
| 286 |
+
return False
|
| 287 |
+
for name in a.column_names:
|
| 288 |
+
x, y = a.column(name).combine_chunks(), b.column(name).combine_chunks()
|
| 289 |
+
if pa.types.is_list(x.type):
|
| 290 |
+
if not x.offsets.equals(y.offsets):
|
| 291 |
+
return False
|
| 292 |
+
x, y = x.flatten(), y.flatten()
|
| 293 |
+
if pa.types.is_floating(x.type):
|
| 294 |
+
if not np.array_equal(x.to_numpy(zero_copy_only=False), y.to_numpy(zero_copy_only=False), equal_nan=True):
|
| 295 |
+
return False
|
| 296 |
+
elif not x.equals(y):
|
| 297 |
+
return False
|
| 298 |
+
return True
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def reproducibility(data_dir: Path, cfg: SimConfig, episode_ids) -> None:
|
| 302 |
+
print("Reproducibility (re-simulating from config.json)")
|
| 303 |
+
for eid in episode_ids:
|
| 304 |
+
fresh = simulate_episode(cfg, int(eid))
|
| 305 |
+
same = all(tables_equal(read_table(data_dir, name, filters=[("episode_id", "=", int(eid))]), table)
|
| 306 |
+
for name, table in fresh.items())
|
| 307 |
+
check(same, f"episode {eid}: every table reproduced bit for bit")
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def field_reconstruction(data_dir: Path, cfg: SimConfig, eid: int) -> None:
|
| 311 |
+
print("Potential-field reconstruction (sparse reference solver)")
|
| 312 |
+
ep = read_table(data_dir, "episodes", filters=[("episode_id", "=", int(eid))]).to_pandas().iloc[0]
|
| 313 |
+
events = read_table(data_dir, "events", filters=[("episode_id", "=", int(eid))]).to_pandas()
|
| 314 |
+
pf = read_table(data_dir, "potential_field", filters=[("episode_id", "=", int(eid))]).to_pandas()
|
| 315 |
+
row = pf.iloc[len(pf) // 2]
|
| 316 |
+
step = int(row.step)
|
| 317 |
+
net = read_table(data_dir, "network_telemetry",
|
| 318 |
+
filters=[("episode_id", "=", int(eid)), ("router", "=", "potential"), ("step", "=", step)]).to_pandas()
|
| 319 |
+
queue = np.asarray(net.queue_depth.iloc[0], np.float64)
|
| 320 |
+
n = int(ep.n_nodes)
|
| 321 |
+
cap = ep.capacity.astype(np.float64)
|
| 322 |
+
factor, failed = np.ones(n), np.zeros(len(cap), bool)
|
| 323 |
+
for e in events[(events.start <= step) & (step < events.end)].itertuples():
|
| 324 |
+
if e.kind == "node_degradation":
|
| 325 |
+
factor[e.node] *= e.factor
|
| 326 |
+
else:
|
| 327 |
+
failed |= (ep.edge_u == e.edge_u) & (ep.edge_v == e.edge_v)
|
| 328 |
+
cap = np.maximum(1, np.floor(cap * factor[ep.edge_u] * factor[ep.edge_v]))
|
| 329 |
+
cap[failed] = 0
|
| 330 |
+
g = live_graph(n, np.stack([ep.edge_u, ep.edge_v], 1), cap.astype(np.int16), ep.latency.astype(np.int16))
|
| 331 |
+
stored = np.asarray(row.potential, np.float64).reshape(int(ep.tracked_flows), n)
|
| 332 |
+
injection = cfg.background_injection / (n - 1) + cfg.congestion_gain * queue / cfg.buffer_size
|
| 333 |
+
worst = 0.0
|
| 334 |
+
for f in range(int(ep.tracked_flows)):
|
| 335 |
+
b = injection.copy()
|
| 336 |
+
b[ep.flow_source[f]] += cfg.source_injection
|
| 337 |
+
phi = grounded_solve(g, int(ep.flow_sink[f]), b)
|
| 338 |
+
worst = max(worst, np.abs(phi - stored[f]).max() / max(np.abs(phi).max(), 1e-12))
|
| 339 |
+
check(worst < 1e-5, f"episode {eid}, step {step}: stored field matches the sparse solve (max rel err {worst:.1e})")
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def main() -> None:
|
| 343 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 344 |
+
parser.add_argument("--out", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
|
| 345 |
+
parser.add_argument("--resimulate", type=int, default=3, help="episodes to re-simulate for the reproducibility check")
|
| 346 |
+
parser.add_argument("--seed", type=int, default=0, help="seed for choosing the sampled episodes")
|
| 347 |
+
parser.add_argument("--batch-rows", type=int, default=BATCH_ROWS,
|
| 348 |
+
help=f"rows per streamed record batch in the invariant checks (default: {BATCH_ROWS})")
|
| 349 |
+
args = parser.parse_args()
|
| 350 |
+
cfg = SimConfig.load(args.out / "config.json")
|
| 351 |
+
n_shards = structure(args.out, cfg)
|
| 352 |
+
if n_shards == 0:
|
| 353 |
+
sys.exit("no shards found")
|
| 354 |
+
coverage(args.out, cfg)
|
| 355 |
+
invariants(args.out, cfg, max(1024, args.batch_rows))
|
| 356 |
+
ids = read_table(args.out, "episodes", columns=["episode_id", "size"]).to_pandas().sort_values("size")
|
| 357 |
+
rng = np.random.default_rng(args.seed)
|
| 358 |
+
sample = [int(ids.episode_id.iloc[i]) for i in
|
| 359 |
+
np.unique(np.linspace(0, len(ids) - 1, max(1, args.resimulate)).astype(int))]
|
| 360 |
+
if len(ids) > args.resimulate:
|
| 361 |
+
sample = sorted(set(sample) | {int(x) for x in rng.choice(ids.episode_id, 1, replace=False)})
|
| 362 |
+
physical_bounds(args.out, cfg, sample)
|
| 363 |
+
reproducibility(args.out, cfg, sample[:args.resimulate])
|
| 364 |
+
if "potential_field" in table_names(cfg.routers):
|
| 365 |
+
field_reconstruction(args.out, cfg, sample[0])
|
| 366 |
+
manifest = json.loads((args.out / "manifest.json").read_text(encoding="utf-8"))
|
| 367 |
+
print(f"\nDataset v{manifest['dataset_version']}: {manifest['design']['episodes_present']} episodes, "
|
| 368 |
+
f"{sum(t['bytes'] for t in manifest['tables'].values()) / 1e9:.2f} GB")
|
| 369 |
+
if failures:
|
| 370 |
+
sys.exit(f"{len(failures)} check(s) failed: " + "; ".join(failures))
|
| 371 |
+
print("All checks passed.")
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
if __name__ == "__main__":
|
| 375 |
+
main()
|
src/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Semantic Potential Routing Telemetry: training-free potential-field routing under stochastic congestion."""
|
src/config.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generator configuration.
|
| 2 |
+
|
| 3 |
+
One frozen dataclass holds every knob: which levels of the experimental design to generate, how
|
| 4 |
+
many replicates per cell, the physical model constants and the potential-field parameters.
|
| 5 |
+
``scripts/run_local_sweep.py`` turns each field into a command-line flag, and the resolved
|
| 6 |
+
configuration is written next to the data as ``data/config.json`` so that any episode can be
|
| 7 |
+
re-created bit for bit from ``(config, episode_id)``.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
from dataclasses import asdict, dataclass, field, fields
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import List
|
| 15 |
+
|
| 16 |
+
from . import design
|
| 17 |
+
|
| 18 |
+
DATASET_VERSION = "2.0"
|
| 19 |
+
ROUTERS = ("potential", "potential_split", "potential_static",
|
| 20 |
+
"shortest_path", "ecmp", "adaptive_shortest_path")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _f(default, help_text):
|
| 24 |
+
return field(default=default, metadata={"help": help_text})
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass(frozen=True)
|
| 28 |
+
class SimConfig:
|
| 29 |
+
# Experimental design (see src/design.py for the level definitions)
|
| 30 |
+
replicates: int = _f(10, "episodes per design cell; episodes = replicates x cells")
|
| 31 |
+
topologies: tuple = _f(design.TOPOLOGIES, "topology families to include")
|
| 32 |
+
sizes: tuple = _f(design.SIZES, "nominal network sizes to include")
|
| 33 |
+
traffic_profiles: tuple = _f(tuple(design.TRAFFIC_PROFILES), "traffic profiles to include")
|
| 34 |
+
load_levels: tuple = _f(tuple(design.LOAD_LEVELS), "load levels to include")
|
| 35 |
+
dynamics_levels: tuple = _f(tuple(design.DYNAMICS_LEVELS), "topology-dynamics levels to include")
|
| 36 |
+
routers: tuple = _f(ROUTERS, "routers replayed on identical traffic and events")
|
| 37 |
+
|
| 38 |
+
# Sweep
|
| 39 |
+
seed: int = _f(2026, "base seed; episode e draws from numpy default_rng([seed, e])")
|
| 40 |
+
shard_episodes: int = _f(40, "episodes per Parquet shard (one shard = one resumable unit)")
|
| 41 |
+
field_budget_bytes: int = _f(1_000_000, "potential field of the tracked flows is logged every k steps to stay within this budget")
|
| 42 |
+
|
| 43 |
+
# Physical model
|
| 44 |
+
steps: int = _f(1000, "simulated steps per episode (1 step = 1 ms)")
|
| 45 |
+
buffer_size: int = _f(256, "per-node drop-tail buffer in packets (< 32768)")
|
| 46 |
+
mean_degree: int = _f(6, "target mean degree of the random-graph families")
|
| 47 |
+
capacity_range: tuple = _f((8, 80), "link capacity in packets/step for random graphs (1 pkt/step ~ 12 Mbps)")
|
| 48 |
+
latency_range: tuple = _f((1, 10), "link propagation delay in steps for random graphs")
|
| 49 |
+
fat_tree_capacity: int = _f(40, "fat-tree fabric link capacity, packets/step (host links carry twice this)")
|
| 50 |
+
flows_per_endpoint: int = _f(2, "flows per endpoint node; sources and sinks are distinct ordered pairs")
|
| 51 |
+
tracked_flows: int = _f(8, "flows per episode with step-level telemetry and stored potential field")
|
| 52 |
+
|
| 53 |
+
# Potential field L_g phi = b with b = source + background/(N-1) + gain * queue/buffer
|
| 54 |
+
source_injection: float = _f(1.0, "unit injection at a flow's source")
|
| 55 |
+
background_injection: float = _f(0.5, "total background injection spread over all non-sink nodes")
|
| 56 |
+
congestion_gain: float = _f(2.0, "repulsive injection of a full buffer (alpha)")
|
| 57 |
+
|
| 58 |
+
def __post_init__(self):
|
| 59 |
+
for f in fields(self): # JSON round-trips turn tuples into lists
|
| 60 |
+
if isinstance(f.default, tuple):
|
| 61 |
+
object.__setattr__(self, f.name, tuple(getattr(self, f.name)))
|
| 62 |
+
for name, allowed in (("topologies", design.TOPOLOGIES), ("sizes", design.SIZES),
|
| 63 |
+
("traffic_profiles", design.TRAFFIC_PROFILES), ("load_levels", design.LOAD_LEVELS),
|
| 64 |
+
("dynamics_levels", design.DYNAMICS_LEVELS), ("routers", ROUTERS)):
|
| 65 |
+
chosen = getattr(self, name)
|
| 66 |
+
if not chosen or set(chosen) - set(allowed):
|
| 67 |
+
raise ValueError(f"{name} must be a non-empty subset of {tuple(allowed)}, got {chosen}")
|
| 68 |
+
if self.replicates < 1:
|
| 69 |
+
raise ValueError("replicates must be at least 1")
|
| 70 |
+
if not 0 < self.buffer_size < 32768:
|
| 71 |
+
raise ValueError("buffer_size must fit in an int16 telemetry column (< 32768)")
|
| 72 |
+
if self.flows_per_endpoint < 1 or self.tracked_flows < 1:
|
| 73 |
+
raise ValueError("flows_per_endpoint and tracked_flows must be positive")
|
| 74 |
+
if self.mean_degree < 2:
|
| 75 |
+
raise ValueError("mean_degree must be at least 2")
|
| 76 |
+
for name in ("capacity_range", "latency_range"):
|
| 77 |
+
lo, hi = getattr(self, name)
|
| 78 |
+
if not 0 < lo <= hi:
|
| 79 |
+
raise ValueError(f"{name} must satisfy 0 < low <= high, got {(lo, hi)}")
|
| 80 |
+
if self.background_injection <= 0:
|
| 81 |
+
raise ValueError("background_injection must be positive: it guarantees loop-free descent")
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def cells(self) -> List[design.Cell]:
|
| 85 |
+
return design.cells(self.topologies, self.sizes, self.traffic_profiles, self.load_levels, self.dynamics_levels)
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def episodes(self) -> int:
|
| 89 |
+
return self.replicates * len(self.cells)
|
| 90 |
+
|
| 91 |
+
def to_json(self) -> str:
|
| 92 |
+
return json.dumps(asdict(self), indent=2)
|
| 93 |
+
|
| 94 |
+
def save(self, path: Path) -> None:
|
| 95 |
+
path.write_text(self.to_json(), encoding="utf-8")
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def load(cls, path: Path) -> "SimConfig":
|
| 99 |
+
return cls(**json.loads(path.read_text(encoding="utf-8")))
|
| 100 |
+
|
| 101 |
+
def __eq__(self, other) -> bool: # tuples vs. JSON lists compare equal
|
| 102 |
+
return isinstance(other, SimConfig) and self.to_json() == other.to_json()
|
src/dataset.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read access to a generated dataset.
|
| 2 |
+
|
| 3 |
+
``Dataset`` opens a data folder (or any folder of shards) and returns tables as pandas
|
| 4 |
+
DataFrames; ``Episode`` bundles everything about one episode — the static graph, its event
|
| 5 |
+
timeline, the flows, the telemetry of any router — and rebuilds the physical state at any step:
|
| 6 |
+
the live graph with the capacities in force and the potential field of any flow, recomputed
|
| 7 |
+
exactly with the same engine that generated the data. The example scripts are written against
|
| 8 |
+
this API.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
from functools import cached_property
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Dict, List, Optional, Sequence
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
from .config import SimConfig
|
| 21 |
+
from .graph_generator import Topology, TopologyEvent, effective_capacity
|
| 22 |
+
from .physics_engine import LiveGraph, PotentialField, currents, live_graph, steepest_next_hops
|
| 23 |
+
from .telemetry_logger import read_table, shard_files, table_names
|
| 24 |
+
|
| 25 |
+
FACTORS = ("topology", "size", "traffic_profile", "load_level", "dynamics_level")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Dataset:
|
| 29 |
+
def __init__(self, path):
|
| 30 |
+
self.path = Path(path)
|
| 31 |
+
self.config = SimConfig.load(self.path / "config.json")
|
| 32 |
+
manifest = self.path / "manifest.json"
|
| 33 |
+
self.manifest: Optional[Dict] = json.loads(manifest.read_text(encoding="utf-8")) if manifest.exists() else None
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def tables(self) -> List[str]:
|
| 37 |
+
return [t for t in table_names(self.config.routers) if shard_files(self.path, t)]
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def routers(self) -> Sequence[str]:
|
| 41 |
+
return self.config.routers
|
| 42 |
+
|
| 43 |
+
def table(self, name: str, columns=None, filters=None) -> pd.DataFrame:
|
| 44 |
+
return read_table(self.path, name, columns=columns, filters=filters).to_pandas()
|
| 45 |
+
|
| 46 |
+
@cached_property
|
| 47 |
+
def episodes(self) -> pd.DataFrame:
|
| 48 |
+
"""The ``episodes`` table indexed by ``episode_id`` (list columns included)."""
|
| 49 |
+
return self.table("episodes").set_index("episode_id").sort_index()
|
| 50 |
+
|
| 51 |
+
def summary(self, name: str = "router_summary") -> pd.DataFrame:
|
| 52 |
+
"""A summary table joined with the design factors and the split of its episode."""
|
| 53 |
+
keys = list(FACTORS) + ["split", "replicate", "n_nodes", "n_flows", "total_capacity"]
|
| 54 |
+
return self.table(name).join(self.episodes[keys], on="episode_id")
|
| 55 |
+
|
| 56 |
+
def episode(self, episode_id: int) -> "Episode":
|
| 57 |
+
return Episode(self, int(episode_id))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Episode:
|
| 61 |
+
def __init__(self, dataset: Dataset, episode_id: int):
|
| 62 |
+
self.dataset = dataset
|
| 63 |
+
self.id = episode_id
|
| 64 |
+
self.row = dataset.episodes.loc[episode_id]
|
| 65 |
+
self.config = dataset.config
|
| 66 |
+
self.events = dataset.table("events", filters=[("episode_id", "=", episode_id)]).sort_values("start")
|
| 67 |
+
self.n_nodes, self.n_edges = int(self.row.n_nodes), int(self.row.n_edges)
|
| 68 |
+
self.n_flows, self.tracked_flows = int(self.row.n_flows), int(self.row.tracked_flows)
|
| 69 |
+
self.steps, self.field_stride = int(self.row.steps), int(self.row.field_stride)
|
| 70 |
+
self.edges = np.stack([self.row.edge_u, self.row.edge_v], 1).astype(np.int16)
|
| 71 |
+
self.capacity = np.asarray(self.row.capacity, np.int16)
|
| 72 |
+
self.latency = np.asarray(self.row.latency, np.int16)
|
| 73 |
+
self.node_role = np.asarray(self.row.node_role, np.int8)
|
| 74 |
+
self.node_xy = (np.stack([self.row.node_x, self.row.node_y], 1).astype(np.float32)
|
| 75 |
+
if len(self.row.node_x) else np.zeros((0, 2), np.float32))
|
| 76 |
+
self.source = np.asarray(self.row.flow_source, np.int16)
|
| 77 |
+
self.sink = np.asarray(self.row.flow_sink, np.int16)
|
| 78 |
+
|
| 79 |
+
def __repr__(self) -> str:
|
| 80 |
+
cell = "/".join(str(self.row[f]) for f in FACTORS)
|
| 81 |
+
return (f"Episode {self.id} [{cell}] {self.n_nodes} nodes, {self.n_edges} links, "
|
| 82 |
+
f"{self.n_flows} flows, {self.steps} steps, split={self.row.split}")
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def cell(self) -> Dict[str, object]:
|
| 86 |
+
return {f: self.row[f] for f in FACTORS}
|
| 87 |
+
|
| 88 |
+
@cached_property
|
| 89 |
+
def topology(self) -> Topology:
|
| 90 |
+
return Topology(self.n_nodes, self.edges, self.capacity, self.latency,
|
| 91 |
+
np.flatnonzero(self.node_role == self.node_role.max()).astype(np.int16)
|
| 92 |
+
if self.node_role.max() > 0 else np.arange(self.n_nodes, dtype=np.int16),
|
| 93 |
+
self.node_role, self.node_xy)
|
| 94 |
+
|
| 95 |
+
@cached_property
|
| 96 |
+
def timeline(self) -> List[TopologyEvent]:
|
| 97 |
+
"""The event table as generator objects (link failures resolved to edge indices)."""
|
| 98 |
+
edge_index = {(int(u), int(v)): i for i, (u, v) in enumerate(self.edges)}
|
| 99 |
+
return [TopologyEvent(e.kind, int(e.start), int(e.end),
|
| 100 |
+
edge=edge_index[(int(e.edge_u), int(e.edge_v))] if e.kind == "link_failure" else -1,
|
| 101 |
+
node=int(e.node), factor=float(e.factor))
|
| 102 |
+
for e in self.events.itertuples()]
|
| 103 |
+
|
| 104 |
+
@cached_property
|
| 105 |
+
def change_steps(self) -> List[int]:
|
| 106 |
+
steps = {0} | {e.start for e in self.timeline} | {e.end for e in self.timeline if e.end < self.steps}
|
| 107 |
+
return sorted(steps)
|
| 108 |
+
|
| 109 |
+
def capacity_at(self, step: int) -> np.ndarray:
|
| 110 |
+
"""Effective capacity of every link at `step` (0 while failed)."""
|
| 111 |
+
return effective_capacity(self.topology, self.timeline, step)
|
| 112 |
+
|
| 113 |
+
def live_graph(self, step: int = 0) -> LiveGraph:
|
| 114 |
+
return live_graph(self.n_nodes, self.edges, self.capacity_at(step), self.latency)
|
| 115 |
+
|
| 116 |
+
def capacity_matrix(self, step: int) -> np.ndarray:
|
| 117 |
+
"""Dense symmetric N × N matrix of the capacities in force at `step` (the graph state)."""
|
| 118 |
+
cap = self.capacity_at(step)
|
| 119 |
+
matrix = np.zeros((self.n_nodes, self.n_nodes), np.int32)
|
| 120 |
+
matrix[self.edges[:, 0], self.edges[:, 1]] = cap
|
| 121 |
+
matrix[self.edges[:, 1], self.edges[:, 0]] = cap
|
| 122 |
+
return matrix
|
| 123 |
+
|
| 124 |
+
def telemetry(self, table: str, router: Optional[str] = None, columns=None) -> pd.DataFrame:
|
| 125 |
+
"""Rows of a telemetry table for this episode (and router), sorted by step."""
|
| 126 |
+
filters = [("episode_id", "=", self.id)] + ([("router", "=", router)] if router else [])
|
| 127 |
+
frame = self.dataset.table(table, columns=columns, filters=filters)
|
| 128 |
+
keys = [c for c in ("router", "step", "flow") if c in frame.columns]
|
| 129 |
+
return frame.sort_values(keys).reset_index(drop=True)
|
| 130 |
+
|
| 131 |
+
def queue_depth(self, router: str) -> np.ndarray:
|
| 132 |
+
"""(steps, n_nodes) buffer occupancy after admission, before forwarding."""
|
| 133 |
+
return np.stack(self.telemetry("network_telemetry", router, ["episode_id", "router", "step", "queue_depth"]).queue_depth)
|
| 134 |
+
|
| 135 |
+
def node_dropped(self, router: str) -> np.ndarray:
|
| 136 |
+
return np.stack(self.telemetry("network_telemetry", router, ["episode_id", "router", "step", "node_dropped"]).node_dropped)
|
| 137 |
+
|
| 138 |
+
def link_load(self, router: str) -> np.ndarray:
|
| 139 |
+
"""(steps, n_edges, 2) packets forwarded per link and direction (u→v, v→u)."""
|
| 140 |
+
frame = self.telemetry("link_telemetry", router)
|
| 141 |
+
return np.stack([np.stack(frame.load_uv), np.stack(frame.load_vu)], axis=2)
|
| 142 |
+
|
| 143 |
+
def link_utilisation(self, router: str) -> np.ndarray:
|
| 144 |
+
"""(steps, n_edges, 2) load divided by the capacity in force; NaN while a link is failed."""
|
| 145 |
+
load = self.link_load(router).astype(np.float64)
|
| 146 |
+
bounds = np.zeros((self.steps, self.n_edges), np.float64)
|
| 147 |
+
for start, end in zip(self.change_steps, self.change_steps[1:] + [self.steps]):
|
| 148 |
+
bounds[start:end] = self.capacity_at(start)
|
| 149 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 150 |
+
return np.where(bounds[:, :, None] > 0, load / bounds[:, :, None], np.nan)
|
| 151 |
+
|
| 152 |
+
@cached_property
|
| 153 |
+
def field_snapshots(self) -> pd.DataFrame:
|
| 154 |
+
return self.telemetry("potential_field")
|
| 155 |
+
|
| 156 |
+
def field(self, step: int) -> np.ndarray:
|
| 157 |
+
"""Stored potential of the tracked flows at a logged step: (tracked_flows, n_nodes)."""
|
| 158 |
+
row = self.field_snapshots[self.field_snapshots.step == step]
|
| 159 |
+
if row.empty:
|
| 160 |
+
raise KeyError(f"step {step} is not logged; logged steps are multiples of {self.field_stride}")
|
| 161 |
+
return np.asarray(row.potential.iloc[0], np.float64).reshape(self.tracked_flows, self.n_nodes)
|
| 162 |
+
|
| 163 |
+
def nearest_logged_step(self, step: int) -> int:
|
| 164 |
+
return int(min(self.field_snapshots.step, key=lambda s: abs(s - step)))
|
| 165 |
+
|
| 166 |
+
def solve_field(self, step: int, queue: Optional[np.ndarray] = None, flows: Optional[Sequence[int]] = None) -> np.ndarray:
|
| 167 |
+
"""Recompute the potential of any flows at any step from the graph state and queue depths.
|
| 168 |
+
|
| 169 |
+
Uses the generator's own engine (grounded Laplacian via the pseudo-inverse); with the
|
| 170 |
+
potential router's queue depths at `step` this reproduces ``field(step)`` to floating-point
|
| 171 |
+
precision. Returns (len(flows), n_nodes); flows default to the tracked ones.
|
| 172 |
+
"""
|
| 173 |
+
if queue is None:
|
| 174 |
+
queue = self.queue_depth("potential")[step]
|
| 175 |
+
flows = np.arange(self.tracked_flows) if flows is None else np.asarray(flows)
|
| 176 |
+
cfg = self.config
|
| 177 |
+
field = PotentialField(self.live_graph(step), self.source[flows], self.sink[flows], cfg.source_injection)
|
| 178 |
+
injection = cfg.background_injection / (self.n_nodes - 1) + cfg.congestion_gain * np.asarray(queue, np.float64) / cfg.buffer_size
|
| 179 |
+
return field.solve(injection)
|
| 180 |
+
|
| 181 |
+
def next_hops(self, step: int, phi: np.ndarray) -> np.ndarray:
|
| 182 |
+
"""Steepest-current next hop of every node for the given potentials (flows, n_nodes); −1 at the sink."""
|
| 183 |
+
g = self.live_graph(step)
|
| 184 |
+
return steepest_next_hops(currents(phi, g), g)
|
| 185 |
+
|
| 186 |
+
def descent_path(self, step: int, phi: np.ndarray, source: int, sink: int) -> List[int]:
|
| 187 |
+
"""Follow the steepest-current next hops of one potential vector (n_nodes,) from source to sink."""
|
| 188 |
+
hops = self.next_hops(step, np.asarray(phi, np.float64)[None, :])[0]
|
| 189 |
+
node, path = int(source), [int(source)]
|
| 190 |
+
while node != int(sink):
|
| 191 |
+
node = int(hops[node])
|
| 192 |
+
if node < 0 or len(path) > self.n_nodes:
|
| 193 |
+
raise RuntimeError("descent did not reach the sink")
|
| 194 |
+
path.append(node)
|
| 195 |
+
return path
|
src/design.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental design of the dataset.
|
| 2 |
+
|
| 3 |
+
Every episode belongs to one *cell* of a full factorial design over five factors:
|
| 4 |
+
|
| 5 |
+
topology family × nominal size × traffic profile × load level × dynamics level
|
| 6 |
+
|
| 7 |
+
Episode ``e`` maps deterministically to cell ``e mod n_cells`` and replicate ``e div n_cells``, so any
|
| 8 |
+
prefix of the episode range — and therefore any partially generated or resumed dataset — covers
|
| 9 |
+
all cells evenly. Replicates are assigned to train / validation / test splits (60 / 20 / 20).
|
| 10 |
+
The level definitions below are the design; ``SimConfig`` selects which levels to generate.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from itertools import product
|
| 16 |
+
from typing import Dict, List, Tuple
|
| 17 |
+
|
| 18 |
+
TOPOLOGIES = ("barabasi_albert", "watts_strogatz", "erdos_renyi", "waxman", "fat_tree")
|
| 19 |
+
SIZES = (32, 64, 128, 256) # nominal node count (fat-tree: k = 4, 6, 8, 10 → 36, 99, 208, 375 nodes)
|
| 20 |
+
SPLITS = ("train", "train", "train", "validation", "test") # by replicate mod 5
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass(frozen=True)
|
| 24 |
+
class TrafficProfile:
|
| 25 |
+
"""Two-state Markov-modulated Poisson process, parameterised by its mean rate m.
|
| 26 |
+
|
| 27 |
+
With burst duty cycle d = mean_burst_steps / (mean_idle_steps + mean_burst_steps):
|
| 28 |
+
idle_rate = m / ((1 − d) + d · peak_ratio), burst_rate = peak_ratio · idle_rate,
|
| 29 |
+
so the long-run mean rate equals m for every profile.
|
| 30 |
+
"""
|
| 31 |
+
peak_ratio: float # burst_rate / idle_rate (1 = stationary Poisson)
|
| 32 |
+
mean_idle_steps: float
|
| 33 |
+
mean_burst_steps: float
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def duty(self) -> float:
|
| 37 |
+
return self.mean_burst_steps / (self.mean_idle_steps + self.mean_burst_steps)
|
| 38 |
+
|
| 39 |
+
def rates(self, mean_rate: float) -> Tuple[float, float]:
|
| 40 |
+
idle = mean_rate / ((1.0 - self.duty) + self.duty * self.peak_ratio)
|
| 41 |
+
return idle, self.peak_ratio * idle
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
TRAFFIC_PROFILES: Dict[str, TrafficProfile] = {
|
| 45 |
+
"poisson": TrafficProfile(peak_ratio=1.0, mean_idle_steps=100.0, mean_burst_steps=100.0),
|
| 46 |
+
"microburst": TrafficProfile(peak_ratio=16.0, mean_idle_steps=100.0, mean_burst_steps=15.0),
|
| 47 |
+
"sustained": TrafficProfile(peak_ratio=4.0, mean_idle_steps=100.0, mean_burst_steps=100.0),
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# Offered load ρ = Σ_f m_f · hops_f / Σ_links capacity: the fraction of the network's directed link
|
| 51 |
+
# capacity that the flows would occupy on their shortest paths. Per-flow mean rates m_f are log-normal
|
| 52 |
+
# (σ = 0.75, "elephants and mice") and rescaled so that every episode meets its level exactly.
|
| 53 |
+
LOAD_LEVELS: Dict[str, float] = {
|
| 54 |
+
"light": 0.01,
|
| 55 |
+
"moderate": 0.03,
|
| 56 |
+
"heavy": 0.10,
|
| 57 |
+
}
|
| 58 |
+
RATE_SIGMA = 0.75
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class Dynamics:
|
| 63 |
+
link_failure_rate: float # per-step probability that a non-bridge link fails
|
| 64 |
+
node_degradation_rate: float # per-step probability that a node degrades
|
| 65 |
+
duration_range: Tuple[int, int] # event duration, steps
|
| 66 |
+
factor_range: Tuple[float, float] # capacity multiplier of a degraded node's links
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
DYNAMICS_LEVELS: Dict[str, Dynamics] = {
|
| 70 |
+
"static": Dynamics(0.0, 0.0, (0, 0), (1.0, 1.0)),
|
| 71 |
+
"moderate": Dynamics(0.002, 0.002, (50, 200), (0.1, 0.5)),
|
| 72 |
+
"severe": Dynamics(0.01, 0.01, (100, 400), (0.1, 0.5)),
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass(frozen=True)
|
| 77 |
+
class Cell:
|
| 78 |
+
topology: str
|
| 79 |
+
size: int
|
| 80 |
+
traffic_profile: str
|
| 81 |
+
load_level: str
|
| 82 |
+
dynamics_level: str
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def profile(self) -> TrafficProfile:
|
| 86 |
+
return TRAFFIC_PROFILES[self.traffic_profile]
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def load(self) -> float:
|
| 90 |
+
return LOAD_LEVELS[self.load_level]
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def dynamics(self) -> Dynamics:
|
| 94 |
+
return DYNAMICS_LEVELS[self.dynamics_level]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def cells(topologies, sizes, traffic_profiles, load_levels, dynamics_levels) -> List[Cell]:
|
| 98 |
+
return [Cell(*levels) for levels in product(topologies, sizes, traffic_profiles, load_levels, dynamics_levels)]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def locate(episode_id: int, n_cells: int) -> Tuple[int, int, str]:
|
| 102 |
+
"""(cell index, replicate, split) of an episode."""
|
| 103 |
+
replicate = episode_id // n_cells
|
| 104 |
+
return episode_id % n_cells, replicate, SPLITS[replicate % len(SPLITS)]
|
src/graph_generator.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Topology families and dynamic-topology timelines.
|
| 2 |
+
|
| 3 |
+
Five families span the structures routing research cares about: Barabási–Albert scale-free
|
| 4 |
+
graphs (router-level Internet), Watts–Strogatz small worlds, Erdős–Rényi random graphs, Waxman
|
| 5 |
+
geometric graphs (ISP-like, with distance-proportional latencies and node coordinates) and k-ary
|
| 6 |
+
fat-trees (data-centre fabrics whose hosts are the only traffic endpoints; host links carry twice
|
| 7 |
+
the fabric capacity, i.e. a 2:1 oversubscribed edge, so bursts contend inside the fabric). Random families are
|
| 8 |
+
generated at a common mean degree so that size is the only structural factor that changes with
|
| 9 |
+
the nominal network size; any rare disconnected sample is stitched into one component instead of
|
| 10 |
+
being resampled, so the node count is always exactly the nominal one.
|
| 11 |
+
|
| 12 |
+
A pre-sampled timeline of link failures and node degradations makes the graph time-varying.
|
| 13 |
+
Failures are drawn only from non-bridge links of the currently live graph, so the network never
|
| 14 |
+
partitions and traffic can always be routed around the damage.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import List, Tuple
|
| 20 |
+
|
| 21 |
+
import networkx as nx
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from .config import SimConfig
|
| 25 |
+
from .design import Cell, Dynamics
|
| 26 |
+
|
| 27 |
+
ROLE_ROUTER, ROLE_CORE, ROLE_AGGREGATION, ROLE_EDGE, ROLE_HOST = 0, 1, 2, 3, 4
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass(frozen=True)
|
| 31 |
+
class Topology:
|
| 32 |
+
n_nodes: int
|
| 33 |
+
edges: np.ndarray # (E, 2) int16, each row (u, v) with u < v, lexicographically sorted
|
| 34 |
+
capacity: np.ndarray # (E,) int16 packets/step per direction
|
| 35 |
+
latency: np.ndarray # (E,) int16 steps
|
| 36 |
+
endpoints: np.ndarray # (K,) int16 nodes eligible as flow sources and sinks
|
| 37 |
+
node_role: np.ndarray # (N,) int8, ROLE_* constants
|
| 38 |
+
node_xy: np.ndarray # (N, 2) float32 coordinates, or shape (0, 2) for non-geometric families
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass(frozen=True)
|
| 42 |
+
class TopologyEvent:
|
| 43 |
+
kind: str # "link_failure" | "node_degradation"
|
| 44 |
+
start: int # first step the event is active
|
| 45 |
+
end: int # first step it is no longer active (exclusive)
|
| 46 |
+
edge: int = -1 # index into Topology.edges for a link failure
|
| 47 |
+
node: int = -1 # degraded node
|
| 48 |
+
factor: float = 0.0 # capacity multiplier applied to the degraded node's links
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _stitch(graph: nx.Graph, xy: np.ndarray = None, rng: np.random.Generator = None) -> None:
|
| 52 |
+
"""Connect a disconnected graph by joining every component to the largest one (rare)."""
|
| 53 |
+
components = sorted(nx.connected_components(graph), key=len, reverse=True)
|
| 54 |
+
main = np.array(sorted(components[0]))
|
| 55 |
+
for comp in components[1:]:
|
| 56 |
+
comp = np.array(sorted(comp))
|
| 57 |
+
if xy is not None: # geometric: closest pair of nodes
|
| 58 |
+
d = np.linalg.norm(xy[comp][:, None, :] - xy[main][None, :, :], axis=2)
|
| 59 |
+
a, b = np.unravel_index(int(d.argmin()), d.shape)
|
| 60 |
+
graph.add_edge(int(comp[a]), int(main[b]))
|
| 61 |
+
else:
|
| 62 |
+
graph.add_edge(int(rng.choice(comp)), int(rng.choice(main)))
|
| 63 |
+
main = np.concatenate([main, comp])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _random_family(cfg: SimConfig, family: str, n: int, rng: np.random.Generator):
|
| 67 |
+
seed = int(rng.integers(2**31 - 1))
|
| 68 |
+
xy = np.zeros((0, 2), np.float32)
|
| 69 |
+
if family == "barabasi_albert":
|
| 70 |
+
graph = nx.barabasi_albert_graph(n, cfg.mean_degree // 2, seed=seed)
|
| 71 |
+
elif family == "watts_strogatz":
|
| 72 |
+
graph = nx.connected_watts_strogatz_graph(n, cfg.mean_degree, 0.1, tries=1000, seed=seed)
|
| 73 |
+
elif family == "erdos_renyi":
|
| 74 |
+
graph = nx.gnp_random_graph(n, cfg.mean_degree / (n - 1), seed=seed)
|
| 75 |
+
_stitch(graph, rng=rng)
|
| 76 |
+
elif family == "waxman":
|
| 77 |
+
xy = rng.random((n, 2)).astype(np.float32)
|
| 78 |
+
iu, iv = np.triu_indices(n, 1)
|
| 79 |
+
d = np.linalg.norm(xy[iu] - xy[iv], axis=1)
|
| 80 |
+
kernel = np.exp(-d / (0.15 * np.sqrt(2.0))) # Waxman link preference, alpha = 0.15 of the diagonal
|
| 81 |
+
n_edges = round(0.5 * cfg.mean_degree * n) # fixed edge count: exact mean degree at every size
|
| 82 |
+
chosen = rng.choice(len(iu), n_edges, replace=False, p=kernel / kernel.sum())
|
| 83 |
+
graph = nx.Graph()
|
| 84 |
+
graph.add_nodes_from(range(n))
|
| 85 |
+
graph.add_edges_from(zip(iu[chosen].tolist(), iv[chosen].tolist()))
|
| 86 |
+
_stitch(graph, xy=xy)
|
| 87 |
+
else:
|
| 88 |
+
raise ValueError(family)
|
| 89 |
+
edges = np.sort(np.array(graph.edges(), dtype=np.int16), axis=1)
|
| 90 |
+
edges = edges[np.lexsort((edges[:, 1], edges[:, 0]))]
|
| 91 |
+
lo, hi = cfg.capacity_range
|
| 92 |
+
capacity = rng.integers(lo, hi + 1, len(edges)).astype(np.int16)
|
| 93 |
+
if family == "waxman": # latency proportional to Euclidean distance, spanning latency_range
|
| 94 |
+
lo_l, hi_l = cfg.latency_range
|
| 95 |
+
dist = np.linalg.norm(xy[edges[:, 0]] - xy[edges[:, 1]], axis=1) / np.sqrt(2.0)
|
| 96 |
+
latency = np.round(lo_l + (hi_l - lo_l) * dist).astype(np.int16)
|
| 97 |
+
else:
|
| 98 |
+
lo_l, hi_l = cfg.latency_range
|
| 99 |
+
latency = rng.integers(lo_l, hi_l + 1, len(edges)).astype(np.int16)
|
| 100 |
+
return Topology(n, edges, capacity, latency, np.arange(n, dtype=np.int16),
|
| 101 |
+
np.zeros(n, np.int8), xy)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def fat_tree_k(nominal_size: int) -> int:
|
| 105 |
+
"""Fat-tree arity for a nominal size: k = 4, 6, 8, 10 give 36, 99, 208, 375 nodes."""
|
| 106 |
+
return {32: 4, 64: 6, 128: 8, 256: 10}.get(nominal_size, 2 * max(2, round((nominal_size / 4) ** (1 / 3))))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _fat_tree(cfg: SimConfig, nominal_size: int) -> Topology:
|
| 110 |
+
k = fat_tree_k(nominal_size)
|
| 111 |
+
half = k // 2
|
| 112 |
+
n_core = half * half
|
| 113 |
+
|
| 114 |
+
def core(i, j):
|
| 115 |
+
return i * half + j
|
| 116 |
+
|
| 117 |
+
def agg(pod, i):
|
| 118 |
+
return n_core + pod * k + i
|
| 119 |
+
|
| 120 |
+
def edge(pod, i):
|
| 121 |
+
return n_core + pod * k + half + i
|
| 122 |
+
|
| 123 |
+
def host(pod, i, h):
|
| 124 |
+
return n_core + k * k + (pod * half + i) * half + h
|
| 125 |
+
|
| 126 |
+
links = []
|
| 127 |
+
for pod in range(k):
|
| 128 |
+
for i in range(half):
|
| 129 |
+
for j in range(half):
|
| 130 |
+
links.append((core(i, j), agg(pod, i)))
|
| 131 |
+
links.append((agg(pod, i), edge(pod, j)))
|
| 132 |
+
for h in range(half):
|
| 133 |
+
links.append((edge(pod, i), host(pod, i, h)))
|
| 134 |
+
n = n_core + k * k + k * half * half
|
| 135 |
+
edges = np.sort(np.array(links, dtype=np.int16), axis=1)
|
| 136 |
+
edges = edges[np.lexsort((edges[:, 1], edges[:, 0]))]
|
| 137 |
+
role = np.full(n, ROLE_HOST, np.int8)
|
| 138 |
+
role[:n_core] = ROLE_CORE
|
| 139 |
+
for pod in range(k):
|
| 140 |
+
role[agg(pod, 0):agg(pod, 0) + half] = ROLE_AGGREGATION
|
| 141 |
+
role[edge(pod, 0):edge(pod, 0) + half] = ROLE_EDGE
|
| 142 |
+
hosts = np.flatnonzero(role == ROLE_HOST).astype(np.int16)
|
| 143 |
+
host_link = (role[edges[:, 0]] == ROLE_HOST) | (role[edges[:, 1]] == ROLE_HOST)
|
| 144 |
+
capacity = np.where(host_link, 2 * cfg.fat_tree_capacity, cfg.fat_tree_capacity).astype(np.int16)
|
| 145 |
+
return Topology(n, edges, capacity, np.ones(len(edges), np.int16), hosts, role, np.zeros((0, 2), np.float32))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def generate_topology(cfg: SimConfig, cell: Cell, rng: np.random.Generator) -> Topology:
|
| 149 |
+
if cell.topology == "fat_tree":
|
| 150 |
+
return _fat_tree(cfg, cell.size)
|
| 151 |
+
return _random_family(cfg, cell.topology, cell.size, rng)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def effective_capacity(topo: Topology, events: List[TopologyEvent], step: int) -> np.ndarray:
|
| 155 |
+
"""Per-link capacity in force at `step`: base × degradation factors of both endpoints, 0 if failed."""
|
| 156 |
+
failed = np.zeros(len(topo.edges), bool)
|
| 157 |
+
factor = np.ones(topo.n_nodes)
|
| 158 |
+
for ev in events:
|
| 159 |
+
if ev.start <= step < ev.end:
|
| 160 |
+
if ev.kind == "link_failure":
|
| 161 |
+
failed[ev.edge] = True
|
| 162 |
+
else:
|
| 163 |
+
factor[ev.node] *= ev.factor
|
| 164 |
+
u, v = topo.edges.T
|
| 165 |
+
cap = np.maximum(1, np.floor(topo.capacity * factor[u] * factor[v])).astype(np.int16)
|
| 166 |
+
cap[failed] = 0
|
| 167 |
+
return cap
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def generate_timeline(cfg: SimConfig, topo: Topology, dyn: Dynamics, rng: np.random.Generator
|
| 171 |
+
) -> Tuple[List[TopologyEvent], List[Tuple[int, np.ndarray]]]:
|
| 172 |
+
"""Pre-sample every topology event of an episode.
|
| 173 |
+
|
| 174 |
+
Returns ``(events, changes)`` where ``changes`` lists the ``(step, effective_capacity)`` pairs
|
| 175 |
+
at which link capacities change, starting with ``(0, base capacities)``.
|
| 176 |
+
"""
|
| 177 |
+
fail_at = rng.random(cfg.steps) < dyn.link_failure_rate
|
| 178 |
+
degrade_at = rng.random(cfg.steps) < dyn.node_degradation_rate
|
| 179 |
+
lo_d, hi_d = dyn.duration_range
|
| 180 |
+
lo_f, hi_f = dyn.factor_range
|
| 181 |
+
events: List[TopologyEvent] = []
|
| 182 |
+
all_edges = [tuple(e) for e in topo.edges.tolist()]
|
| 183 |
+
|
| 184 |
+
for t in range(cfg.steps):
|
| 185 |
+
if fail_at[t]:
|
| 186 |
+
down = {ev.edge for ev in events if ev.kind == "link_failure" and ev.start <= t < ev.end}
|
| 187 |
+
live = nx.Graph()
|
| 188 |
+
live.add_nodes_from(range(topo.n_nodes))
|
| 189 |
+
live.add_edges_from(e for i, e in enumerate(all_edges) if i not in down)
|
| 190 |
+
bridges = {tuple(sorted(b)) for b in nx.bridges(live)}
|
| 191 |
+
candidates = [i for i, e in enumerate(all_edges) if i not in down and e not in bridges]
|
| 192 |
+
if candidates:
|
| 193 |
+
end = min(t + int(rng.integers(lo_d, hi_d + 1)), cfg.steps)
|
| 194 |
+
events.append(TopologyEvent("link_failure", t, end, edge=int(rng.choice(candidates))))
|
| 195 |
+
if degrade_at[t]:
|
| 196 |
+
end = min(t + int(rng.integers(lo_d, hi_d + 1)), cfg.steps)
|
| 197 |
+
events.append(TopologyEvent("node_degradation", t, end,
|
| 198 |
+
node=int(rng.integers(topo.n_nodes)),
|
| 199 |
+
factor=float(rng.uniform(lo_f, hi_f))))
|
| 200 |
+
|
| 201 |
+
steps = {0} | {ev.start for ev in events} | {ev.end for ev in events if ev.end < cfg.steps}
|
| 202 |
+
changes = [(t, effective_capacity(topo, events, t)) for t in sorted(steps)]
|
| 203 |
+
return events, changes
|
src/physics_engine.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training-free potential-field routing on the graph Laplacian, and the classical baselines.
|
| 2 |
+
|
| 3 |
+
For flow *f* with source *s* and sink *t* the potential φ solves the discrete Poisson equation
|
| 4 |
+
|
| 5 |
+
L_g φ = b, L = D − W, w_ij = capacity_ij / latency_ij (live links only)
|
| 6 |
+
|
| 7 |
+
where L_g is the Laplacian with the sink's row and column removed, i.e. the Dirichlet boundary
|
| 8 |
+
condition φ_t = 0: the sink is the grounded, attractive well of the field. The right-hand side
|
| 9 |
+
injects a unit current at the source, a small positive background at every node and a repulsive
|
| 10 |
+
current proportional to each node's buffer occupancy.
|
| 11 |
+
|
| 12 |
+
The grounded inverse is available in closed form from the Laplacian pseudo-inverse L⁺:
|
| 13 |
+
(L_g⁻¹)_ij = L⁺_ij − L⁺_it − L⁺_tj + L⁺_tt. Because the background and congestion injections are
|
| 14 |
+
the same for every flow, the fields of all F flows follow from one matrix–vector product with L⁺
|
| 15 |
+
plus O(N) work per flow, so L⁺ is formed once per topology change (dense, N ≤ 375) and every step
|
| 16 |
+
costs O(N·F) instead of F sparse solves. ``grounded_solve`` keeps the sparse SuperLU reference
|
| 17 |
+
solution for validation.
|
| 18 |
+
|
| 19 |
+
Packets follow the routing gradient. On every live directed link the current is
|
| 20 |
+
I_ij = w_ij (φ_i − φ_j); the *steepest* rule forwards along the largest current out of a node and
|
| 21 |
+
the *split* rule sprays packets over the outgoing links in proportion to their positive currents,
|
| 22 |
+
exactly how electrical current divides. Because b_i > 0 at every non-sink node, Σ_j I_ij = b_i > 0,
|
| 23 |
+
so at least one current is positive and every positive-current link leads strictly downhill:
|
| 24 |
+
both rules are loop-free and reach the sink in at most N − 1 hops for any congestion pattern.
|
| 25 |
+
|
| 26 |
+
The baselines — static shortest path, equal-cost multipath and queue-aware adaptive shortest
|
| 27 |
+
path — share one Dijkstra helper (``scipy.sparse.csgraph.dijkstra`` on the reversed graph, whose
|
| 28 |
+
predecessor tree is exactly the next-hop table towards each sink).
|
| 29 |
+
"""
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
from dataclasses import dataclass
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
import scipy.sparse as sp
|
| 36 |
+
from scipy.sparse.csgraph import dijkstra, laplacian
|
| 37 |
+
from scipy.sparse.linalg import splu
|
| 38 |
+
|
| 39 |
+
GOLDEN = 0.6180339887498949 # low-discrepancy per-packet coordinate for multipath spraying
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass(frozen=True)
|
| 43 |
+
class LiveGraph:
|
| 44 |
+
"""Directed view of the links with positive capacity at one point in time, sorted by tail node."""
|
| 45 |
+
n: int
|
| 46 |
+
n_edges: int # E of the base topology
|
| 47 |
+
src: np.ndarray # (M,) int32 tail of every live directed link
|
| 48 |
+
dst: np.ndarray # (M,) int32 head
|
| 49 |
+
base: np.ndarray # (M,) int32 index into the 2E directed base links: edge + E * direction
|
| 50 |
+
capacity: np.ndarray # (M,) int32
|
| 51 |
+
latency: np.ndarray # (M,) int32
|
| 52 |
+
conductance: np.ndarray # (M,) float64
|
| 53 |
+
indptr: np.ndarray # (n + 1,) segment boundaries of each tail node
|
| 54 |
+
dir_edge: np.ndarray # (n, n) int32 live directed link index, −1 where there is none
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def degree(self) -> np.ndarray:
|
| 58 |
+
return np.diff(self.indptr)
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def max_degree(self) -> int:
|
| 62 |
+
return int(self.degree.max())
|
| 63 |
+
|
| 64 |
+
def laplacian(self) -> np.ndarray:
|
| 65 |
+
weights = sp.csr_matrix((self.conductance, (self.src, self.dst)), shape=(self.n, self.n))
|
| 66 |
+
return laplacian(weights).toarray()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def live_graph(n: int, edges: np.ndarray, capacity: np.ndarray, latency: np.ndarray) -> LiveGraph:
|
| 70 |
+
n_edges = len(edges)
|
| 71 |
+
live = np.flatnonzero(capacity > 0)
|
| 72 |
+
u, v = edges[live, 0].astype(np.int32), edges[live, 1].astype(np.int32)
|
| 73 |
+
src = np.concatenate([u, v])
|
| 74 |
+
dst = np.concatenate([v, u])
|
| 75 |
+
base = np.concatenate([live, live + n_edges]).astype(np.int32)
|
| 76 |
+
order = np.lexsort((dst, src))
|
| 77 |
+
src, dst, base = src[order], dst[order], base[order]
|
| 78 |
+
cap = capacity[base % n_edges].astype(np.int32)
|
| 79 |
+
lat = latency[base % n_edges].astype(np.int32)
|
| 80 |
+
indptr = np.searchsorted(src, np.arange(n + 1))
|
| 81 |
+
dir_edge = np.full((n, n), -1, np.int32)
|
| 82 |
+
dir_edge[src, dst] = np.arange(len(src))
|
| 83 |
+
return LiveGraph(n, n_edges, src, dst, base, cap, lat, cap / lat, indptr, dir_edge)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class PotentialField:
|
| 87 |
+
"""Grounded-Laplacian Green's functions of every flow, from one dense pseudo-inverse."""
|
| 88 |
+
|
| 89 |
+
def __init__(self, g: LiveGraph, sources: np.ndarray, sinks: np.ndarray, source_injection: float):
|
| 90 |
+
n = g.n
|
| 91 |
+
pinv = np.linalg.inv(g.laplacian() + 1.0 / n) - 1.0 / n # L⁺ = (L + J/N)⁻¹ − J/N
|
| 92 |
+
self.pinv = 0.5 * (pinv + pinv.T) # exactly symmetric, like L⁺ itself
|
| 93 |
+
self.sinks = np.asarray(sinks, np.intp)
|
| 94 |
+
self.flow_ids = np.arange(len(self.sinks))
|
| 95 |
+
s, t = np.asarray(sources, np.intp), self.sinks
|
| 96 |
+
self.row_t = self.pinv[t] # (F, N) rows L⁺_t·
|
| 97 |
+
self.diag_t = self.pinv[t, t] # (F,)
|
| 98 |
+
# Response to the unit source injection, G^(t) e_s, zero at the sink by construction.
|
| 99 |
+
self.source_term = source_injection * (self.pinv[s] - self.row_t
|
| 100 |
+
- self.pinv[t, s][:, None] + self.diag_t[:, None])
|
| 101 |
+
|
| 102 |
+
def solve(self, injection: np.ndarray) -> np.ndarray:
|
| 103 |
+
"""Per-node injection shared by all flows (N,) → potentials φ (F, N) with φ[f, sink_f] = 0."""
|
| 104 |
+
p = self.pinv @ injection
|
| 105 |
+
total = injection.sum()
|
| 106 |
+
# (G^(t) c)_i = p_i − L⁺_it·Σc − (p_t − L⁺_tt·Σc); the injection at the grounded sink cancels.
|
| 107 |
+
phi = p[None, :] - self.row_t * total - (p[self.sinks] - self.diag_t * total)[:, None] + self.source_term
|
| 108 |
+
phi[self.flow_ids, self.sinks] = 0.0 # exact ground, free of rounding residue
|
| 109 |
+
return phi
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def grounded_solve(g: LiveGraph, sink: int, b: np.ndarray) -> np.ndarray:
|
| 113 |
+
"""Reference sparse solution of L_g φ = b for one sink (SuperLU); used for validation."""
|
| 114 |
+
keep = np.delete(np.arange(g.n), sink)
|
| 115 |
+
lap = sp.csr_matrix(g.laplacian())
|
| 116 |
+
phi = np.zeros(g.n)
|
| 117 |
+
phi[keep] = splu(lap[keep][:, keep].tocsc()).solve(b[keep])
|
| 118 |
+
return phi
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def currents(phi: np.ndarray, g: LiveGraph) -> np.ndarray:
|
| 122 |
+
"""I_ij = w_ij (φ_i − φ_j) on every live directed link, shape (F, M)."""
|
| 123 |
+
return (np.take(phi, g.src, axis=1) - np.take(phi, g.dst, axis=1)) * g.conductance
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
TIE_TOLERANCE = 1e-9 # currents within this relative margin of a node's largest current count as tied
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def steepest_next_hops(cur: np.ndarray, g: LiveGraph) -> np.ndarray:
|
| 130 |
+
"""Next hop per (flow, node): the link carrying the largest current; −1 if none is positive.
|
| 131 |
+
|
| 132 |
+
Symmetric topologies produce mathematically equal currents on parallel links; ties are resolved
|
| 133 |
+
towards the first link in tail-node order within a relative tolerance far above rounding noise,
|
| 134 |
+
so the choice does not depend on the last bits of the linear algebra on a given platform.
|
| 135 |
+
"""
|
| 136 |
+
starts = g.indptr[:-1]
|
| 137 |
+
best = np.maximum.reduceat(cur, starts, axis=1) # (F, N)
|
| 138 |
+
tied = cur >= np.take(best, g.src, axis=1) * (1.0 - TIE_TOLERANCE)
|
| 139 |
+
first = np.where(tied, np.arange(len(g.src)), len(g.src))
|
| 140 |
+
k = np.minimum.reduceat(first, starts, axis=1) # (F, N)
|
| 141 |
+
return np.where(best > 0, g.dst[np.minimum(k, len(g.src) - 1)], -1).astype(np.int16)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def spray_next_hops(cur: np.ndarray, g: LiveGraph, node: np.ndarray, flow: np.ndarray,
|
| 145 |
+
packet_id: np.ndarray) -> np.ndarray:
|
| 146 |
+
"""Per-packet next hop drawn in proportion to the positive currents leaving the packet's node.
|
| 147 |
+
|
| 148 |
+
Packets are grouped by (flow, node); each group's outgoing shares form a cumulative
|
| 149 |
+
distribution, all groups are laid out as one monotone array (group index doubled plus CDF),
|
| 150 |
+
and every packet's low-discrepancy coordinate is placed with a single ``searchsorted``.
|
| 151 |
+
"""
|
| 152 |
+
key = flow.astype(np.int64) * g.n + node
|
| 153 |
+
order = np.argsort(key, kind="stable")
|
| 154 |
+
sorted_key = key[order]
|
| 155 |
+
starts = np.flatnonzero(np.r_[True, sorted_key[1:] != sorted_key[:-1]])
|
| 156 |
+
group = np.repeat(np.arange(len(starts)), np.diff(np.r_[starts, len(order)]))
|
| 157 |
+
g_flow, g_node = flow[order][starts].astype(np.int64), node[order][starts].astype(np.int64)
|
| 158 |
+
degree = g.degree[g_node]
|
| 159 |
+
width = int(degree.max())
|
| 160 |
+
slot = np.arange(width)
|
| 161 |
+
valid = slot[None, :] < degree[:, None] # (G, width)
|
| 162 |
+
link = np.minimum(g.indptr[g_node][:, None] + slot[None, :], len(g.src) - 1)
|
| 163 |
+
share = np.where(valid, np.maximum(cur[g_flow[:, None], link], 0.0), 0.0)
|
| 164 |
+
cdf = np.cumsum(share, axis=1)
|
| 165 |
+
total = cdf[:, -1]
|
| 166 |
+
ok = total > 0
|
| 167 |
+
cdf = np.where(valid & ok[:, None], cdf / np.where(ok, total, 1.0)[:, None], 1.0) # exact 1.0 at the last link
|
| 168 |
+
augmented = (cdf + 2.0 * np.arange(len(starts))[:, None]).ravel()
|
| 169 |
+
u = (packet_id[order] * GOLDEN) % 1.0
|
| 170 |
+
pick = np.searchsorted(augmented, 2.0 * group + u, side="right") - group * width
|
| 171 |
+
hop = np.where(ok[group], g.dst[g.indptr[g_node[group]] + pick], -1)
|
| 172 |
+
out = np.empty(len(order), np.int16)
|
| 173 |
+
out[order] = hop
|
| 174 |
+
return out
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
COST_QUANTUM = 1e-6 # adaptive link costs are rounded to this many steps so that path sums are exact integers
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def dijkstra_next_hops(cost: np.ndarray, g: LiveGraph, sinks: np.ndarray):
|
| 181 |
+
"""Shortest paths to each sink under per-directed-link costs: (next_hop (D, N), dist (D, N)).
|
| 182 |
+
|
| 183 |
+
Costs must be integer-valued floats (latencies, or quantised adaptive costs) so that every
|
| 184 |
+
path sum is exact. Distances then do not depend on the solver's tie-breaking, and the next hop
|
| 185 |
+
is derived from them here — the first link, in tail-node order, that lies on a shortest path —
|
| 186 |
+
which keeps the tables identical across SciPy versions and platforms.
|
| 187 |
+
"""
|
| 188 |
+
reverse = sp.csr_matrix((cost, (g.dst, g.src)), shape=(g.n, g.n)) # reverse[j, i] = cost(i → j)
|
| 189 |
+
dist = dijkstra(reverse, directed=True, indices=np.asarray(sinks, np.intp))
|
| 190 |
+
starts = g.indptr[:-1]
|
| 191 |
+
through = np.take(dist, g.dst, axis=1) + cost # (D, M)
|
| 192 |
+
first = np.where(through == np.take(dist, g.src, axis=1), np.arange(len(g.src)), len(g.src))
|
| 193 |
+
k = np.minimum.reduceat(first, starts, axis=1) # (D, N)
|
| 194 |
+
next_hop = g.dst[np.minimum(k, len(g.src) - 1)].astype(np.int16)
|
| 195 |
+
next_hop[np.arange(len(sinks)), np.asarray(sinks, np.intp)] = -1
|
| 196 |
+
return next_hop, dist
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class EcmpTable:
|
| 200 |
+
"""All equal-latency next hops per (sink, node); packets are sprayed round-robin over them."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, dist: np.ndarray, g: LiveGraph):
|
| 203 |
+
starts = g.indptr[:-1]
|
| 204 |
+
equal = np.take(dist, g.dst, axis=1) + g.latency == np.take(dist, g.src, axis=1) # (D, M)
|
| 205 |
+
self.count = np.add.reduceat(equal.astype(np.int32), starts, axis=1) # (D, N)
|
| 206 |
+
csum = np.cumsum(equal, axis=1)
|
| 207 |
+
pos = csum - np.take(csum[:, starts] - equal[:, starts], g.src, axis=1) - 1
|
| 208 |
+
self.table = np.full((dist.shape[0], g.n, g.max_degree), -1, np.int16)
|
| 209 |
+
rows, cols = np.nonzero(equal)
|
| 210 |
+
self.table[rows, g.src[cols], pos[rows, cols]] = g.dst[cols]
|
| 211 |
+
|
| 212 |
+
def hops(self, sink_index: np.ndarray, node: np.ndarray, packet_id: np.ndarray) -> np.ndarray:
|
| 213 |
+
count = self.count[sink_index, node]
|
| 214 |
+
return self.table[sink_index, node, packet_id % np.maximum(count, 1)] # −1 where count is 0
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def path_metrics(g: LiveGraph, sources: np.ndarray, sinks: np.ndarray):
|
| 218 |
+
"""Minimum hop count and minimum latency from every flow's source to its sink."""
|
| 219 |
+
origins, index = np.unique(np.asarray(sources, np.intp), return_inverse=True)
|
| 220 |
+
hops = dijkstra(sp.csr_matrix((np.ones(len(g.src)), (g.src, g.dst)), shape=(g.n, g.n)),
|
| 221 |
+
directed=True, indices=origins)
|
| 222 |
+
lat = dijkstra(sp.csr_matrix((g.latency.astype(np.float64), (g.src, g.dst)), shape=(g.n, g.n)),
|
| 223 |
+
directed=True, indices=origins)
|
| 224 |
+
return hops[index, sinks].astype(np.int16), lat[index, sinks].astype(np.int16)
|
src/simulation_loop.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Monte Carlo episodes: MMPP traffic through a packet-level queueing network under six routers.
|
| 2 |
+
|
| 3 |
+
One episode samples a topology from its design cell, the failure/degradation timeline, F flows
|
| 4 |
+
between distinct ordered (source, sink) pairs whose mean rates realise the cell's offered load,
|
| 5 |
+
and each flow's Markov-modulated Poisson arrival stream. That identical scenario is then replayed
|
| 6 |
+
under every router, so any difference between routers is attributable to the routing policy
|
| 7 |
+
alone. The queueing model is deliberately explicit:
|
| 8 |
+
|
| 9 |
+
* every node owns one drop-tail FIFO buffer of ``buffer_size`` packets shared by all flows;
|
| 10 |
+
* every directed link forwards at most ``capacity`` packets per step, taking the oldest packets at
|
| 11 |
+
its tail whose next hop crosses it (virtual output queueing, no head-of-line blocking);
|
| 12 |
+
* a packet forwarded at step t over a link of latency ℓ reaches the head node at step t + ℓ, where
|
| 13 |
+
it is delivered (its flow's sink), admitted, or dropped if the buffer is full;
|
| 14 |
+
* routing decisions are recomputed every step (potential, potential_split, adaptive_shortest_path)
|
| 15 |
+
or at every topology change (potential_static, shortest_path, ecmp).
|
| 16 |
+
|
| 17 |
+
Every step is vectorised with NumPy over the packets in flight; episodes are mapped across CPU
|
| 18 |
+
cores with ``multiprocessing.Pool`` and streamed to Parquet shard by shard.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import multiprocessing as mp
|
| 23 |
+
import time
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from functools import partial
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Dict, List
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import pyarrow as pa
|
| 31 |
+
|
| 32 |
+
from .config import SimConfig
|
| 33 |
+
from .design import RATE_SIGMA, Cell, TrafficProfile, locate
|
| 34 |
+
from .graph_generator import Topology, TopologyEvent, generate_timeline, generate_topology
|
| 35 |
+
from .physics_engine import (COST_QUANTUM, EcmpTable, LiveGraph, PotentialField, currents,
|
| 36 |
+
dijkstra_next_hops, live_graph, path_metrics, spray_next_hops,
|
| 37 |
+
steepest_next_hops)
|
| 38 |
+
from .telemetry_logger import SCHEMAS, completed_shards, list_column, write_shard
|
| 39 |
+
|
| 40 |
+
FIELD_ROUTER = "potential" # the router whose potential field is stored
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass(frozen=True)
|
| 44 |
+
class Flows:
|
| 45 |
+
source: np.ndarray # (F,) int16
|
| 46 |
+
sink: np.ndarray # (F,) int16
|
| 47 |
+
mean_rate: np.ndarray # (F,) float32 long-run packets/step
|
| 48 |
+
idle_rate: np.ndarray # (F,) float32
|
| 49 |
+
burst_rate: np.ndarray # (F,) float32
|
| 50 |
+
min_hops: np.ndarray # (F,) int16 on the base topology
|
| 51 |
+
min_latency: np.ndarray # (F,) int16 on the base topology
|
| 52 |
+
total_capacity: float # Σ over directed base links of capacity, packets/step
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def sample_flows(cfg: SimConfig, cell: Cell, topo: Topology, base: LiveGraph,
|
| 56 |
+
rng: np.random.Generator) -> Flows:
|
| 57 |
+
endpoints = topo.endpoints
|
| 58 |
+
k = len(endpoints)
|
| 59 |
+
n_flows = cfg.flows_per_endpoint * k
|
| 60 |
+
pair = rng.choice(k * (k - 1), n_flows, replace=False) # distinct ordered pairs
|
| 61 |
+
si, ti = pair // (k - 1), pair % (k - 1)
|
| 62 |
+
ti = ti + (ti >= si)
|
| 63 |
+
source, sink = endpoints[si], endpoints[ti]
|
| 64 |
+
min_hops, min_latency = path_metrics(base, source, sink)
|
| 65 |
+
weight = np.exp(RATE_SIGMA * rng.standard_normal(n_flows)) # elephants and mice
|
| 66 |
+
total_capacity = float(base.capacity.sum())
|
| 67 |
+
mean = cell.load * total_capacity * weight / float(weight @ min_hops)
|
| 68 |
+
idle, burst = cell.profile.rates(mean)
|
| 69 |
+
return Flows(source, sink, mean.astype(np.float32), idle.astype(np.float32),
|
| 70 |
+
burst.astype(np.float32), min_hops, min_latency, total_capacity)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def sample_mmpp(cfg: SimConfig, profile: TrafficProfile, flows: Flows, rng: np.random.Generator):
|
| 74 |
+
"""Two-state MMPP per flow: (state (F, T) int8 with 1 = burst, arrivals (F, T) int32)."""
|
| 75 |
+
n_flows = len(flows.source)
|
| 76 |
+
state = np.zeros((n_flows, cfg.steps), np.int8)
|
| 77 |
+
if profile.peak_ratio > 1.0:
|
| 78 |
+
p_ib, p_bi = 1.0 / profile.mean_idle_steps, 1.0 / profile.mean_burst_steps
|
| 79 |
+
state[:, 0] = rng.random(n_flows) < profile.duty # stationary start
|
| 80 |
+
u = rng.random((n_flows, cfg.steps))
|
| 81 |
+
for t in range(1, cfg.steps):
|
| 82 |
+
idle = state[:, t - 1] == 0
|
| 83 |
+
state[:, t] = np.where(idle, u[:, t] < p_ib, u[:, t] >= p_bi)
|
| 84 |
+
rate = np.where(state == 1, flows.burst_rate[:, None], flows.idle_rate[:, None])
|
| 85 |
+
return state, rng.poisson(rate).astype(np.int32)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _rank_within_groups(sorted_keys: np.ndarray) -> np.ndarray:
|
| 89 |
+
"""Position of every element inside its run of equal keys (keys must be sorted)."""
|
| 90 |
+
n = len(sorted_keys)
|
| 91 |
+
starts = np.flatnonzero(np.r_[True, sorted_keys[1:] != sorted_keys[:-1]])
|
| 92 |
+
return np.arange(n) - np.repeat(starts, np.diff(np.r_[starts, n]))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@dataclass
|
| 96 |
+
class RouterRun:
|
| 97 |
+
queue: np.ndarray # (T, N) int16 buffer occupancy after admission, before forwarding
|
| 98 |
+
node_drops: np.ndarray # (T, N) int16 packets dropped at each node this step
|
| 99 |
+
link_load: np.ndarray # (T, 2E) int16 packets forwarded over each directed base link
|
| 100 |
+
potential: np.ndarray # (S, tracked, N) float32 field snapshots every `stride` steps, or None
|
| 101 |
+
per_flow: Dict[str, np.ndarray] # (T, F) int32: admitted, delivered, dropped, queued, in_transit, route_changes
|
| 102 |
+
delay_sum: np.ndarray # (T, F) sum of end-to-end delays of packets delivered this step
|
| 103 |
+
in_flight: np.ndarray # (F,) packets still queued or on a link when the episode ends
|
| 104 |
+
delays: List[np.ndarray] # per flow, end-to-end delay of every delivered packet
|
| 105 |
+
propagation: List[np.ndarray] # per flow, propagation part of that delay
|
| 106 |
+
hops: List[np.ndarray] # per flow, hop count of every delivered packet
|
| 107 |
+
utilisation: float # packets forwarded / directed link capacity, over all link-steps
|
| 108 |
+
saturation: float # fraction of directed link-steps forwarding at full capacity
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def run_router(cfg: SimConfig, topo: Topology, flows: Flows, arrivals: np.ndarray,
|
| 112 |
+
changes: list, router: str, field_stride: int) -> RouterRun:
|
| 113 |
+
n, n_flows, steps, buffer = topo.n_nodes, len(flows.source), cfg.steps, cfg.buffer_size
|
| 114 |
+
n_edges = len(topo.edges)
|
| 115 |
+
source, sink = flows.source, flows.sink
|
| 116 |
+
flow_ids = np.arange(n_flows)
|
| 117 |
+
sinks, sink_index = np.unique(sink, return_inverse=True) # per-sink tables serve every flow
|
| 118 |
+
background = cfg.background_injection / (n - 1)
|
| 119 |
+
tracked = min(cfg.tracked_flows, n_flows)
|
| 120 |
+
field_based = router in ("potential", "potential_split", "potential_static")
|
| 121 |
+
per_step = router in ("potential", "potential_split", "adaptive_shortest_path")
|
| 122 |
+
|
| 123 |
+
# Packets in flight as a structure of arrays.
|
| 124 |
+
p_flow = np.zeros(0, np.int16)
|
| 125 |
+
p_birth = np.zeros(0, np.int32)
|
| 126 |
+
p_node = np.zeros(0, np.int16)
|
| 127 |
+
p_ready = np.zeros(0, np.int32) # step at which the packet is (or becomes) available at p_node
|
| 128 |
+
p_prop = np.zeros(0, np.int32) # propagation delay accumulated so far
|
| 129 |
+
p_hops = np.zeros(0, np.int16)
|
| 130 |
+
p_id = np.zeros(0, np.int64) # global creation order: FIFO tie-break and spraying coordinate
|
| 131 |
+
next_id = 0
|
| 132 |
+
|
| 133 |
+
queue_log = np.zeros((steps, n), np.int16)
|
| 134 |
+
drop_log = np.zeros((steps, n), np.int16)
|
| 135 |
+
link_log = np.zeros((steps, 2 * n_edges), np.int16)
|
| 136 |
+
phi_log = (np.zeros((-(-steps // field_stride), tracked, n), np.float32)
|
| 137 |
+
if router == FIELD_ROUTER else None)
|
| 138 |
+
per_flow = {k: np.zeros((steps, n_flows), np.int32) for k in
|
| 139 |
+
("admitted", "delivered", "dropped", "queued", "in_transit", "route_changes")}
|
| 140 |
+
delay_sum = np.zeros((steps, n_flows), np.float64)
|
| 141 |
+
done_flow, done_delay, done_prop, done_hops = [], [], [], []
|
| 142 |
+
util_num = util_den = 0.0
|
| 143 |
+
saturated = link_steps = 0
|
| 144 |
+
previous_hops = None
|
| 145 |
+
change_i = 0
|
| 146 |
+
|
| 147 |
+
for t in range(steps):
|
| 148 |
+
# 1. Topology in force at this step; rebuild the routing state when links change.
|
| 149 |
+
if change_i < len(changes) and changes[change_i][0] == t:
|
| 150 |
+
g = live_graph(n, topo.edges, changes[change_i][1], topo.latency)
|
| 151 |
+
change_i += 1
|
| 152 |
+
if field_based:
|
| 153 |
+
field = PotentialField(g, source, sink, cfg.source_injection)
|
| 154 |
+
if router == "potential_static":
|
| 155 |
+
next_hop = steepest_next_hops(currents(field.solve(np.full(n, background)), g), g)
|
| 156 |
+
elif router in ("shortest_path", "ecmp"):
|
| 157 |
+
by_sink, dist = dijkstra_next_hops(g.latency.astype(np.float64), g, sinks)
|
| 158 |
+
next_hop = by_sink[sink_index]
|
| 159 |
+
if router == "ecmp":
|
| 160 |
+
ecmp = EcmpTable(dist, g)
|
| 161 |
+
|
| 162 |
+
# 2. New packets appear at their sources.
|
| 163 |
+
new = arrivals[:, t]
|
| 164 |
+
n_new = int(new.sum())
|
| 165 |
+
if n_new:
|
| 166 |
+
new_flow = np.repeat(flow_ids, new).astype(np.int16)
|
| 167 |
+
p_flow = np.concatenate([p_flow, new_flow])
|
| 168 |
+
p_birth = np.concatenate([p_birth, np.full(n_new, t, np.int32)])
|
| 169 |
+
p_node = np.concatenate([p_node, source[new_flow]])
|
| 170 |
+
p_ready = np.concatenate([p_ready, np.full(n_new, t, np.int32)])
|
| 171 |
+
p_prop = np.concatenate([p_prop, np.zeros(n_new, np.int32)])
|
| 172 |
+
p_hops = np.concatenate([p_hops, np.zeros(n_new, np.int16)])
|
| 173 |
+
p_id = np.concatenate([p_id, np.arange(next_id, next_id + n_new)])
|
| 174 |
+
next_id += n_new
|
| 175 |
+
|
| 176 |
+
# 3. Packets reaching a node this step: deliver at the sink, otherwise admit (drop-tail).
|
| 177 |
+
per_flow["admitted"][t] = new
|
| 178 |
+
arriving = p_ready == t
|
| 179 |
+
if arriving.any():
|
| 180 |
+
at_sink = arriving & (p_node == sink[p_flow])
|
| 181 |
+
remove = at_sink.copy()
|
| 182 |
+
if at_sink.any():
|
| 183 |
+
f, d = p_flow[at_sink], (t - p_birth[at_sink]).astype(np.int32)
|
| 184 |
+
np.add.at(per_flow["delivered"][t], f, 1)
|
| 185 |
+
np.add.at(delay_sum[t], f, d)
|
| 186 |
+
done_flow.append(f)
|
| 187 |
+
done_delay.append(d)
|
| 188 |
+
done_prop.append(p_prop[at_sink])
|
| 189 |
+
done_hops.append(p_hops[at_sink])
|
| 190 |
+
entering = np.flatnonzero(arriving & ~at_sink)
|
| 191 |
+
if len(entering):
|
| 192 |
+
space = buffer - np.bincount(p_node[p_ready < t], minlength=n)
|
| 193 |
+
entering = entering[np.lexsort((p_id[entering], p_node[entering]))] # per node, oldest first
|
| 194 |
+
node = p_node[entering]
|
| 195 |
+
lost = entering[_rank_within_groups(node) >= space[node]]
|
| 196 |
+
if len(lost):
|
| 197 |
+
np.add.at(per_flow["dropped"][t], p_flow[lost], 1)
|
| 198 |
+
np.add.at(drop_log[t], p_node[lost], 1)
|
| 199 |
+
at_source = lost[p_birth[lost] == t]
|
| 200 |
+
per_flow["admitted"][t] -= np.bincount(p_flow[at_source], minlength=n_flows)
|
| 201 |
+
remove[lost] = True
|
| 202 |
+
keep = ~remove
|
| 203 |
+
p_flow, p_birth, p_node, p_ready = p_flow[keep], p_birth[keep], p_node[keep], p_ready[keep]
|
| 204 |
+
p_prop, p_hops, p_id = p_prop[keep], p_hops[keep], p_id[keep]
|
| 205 |
+
|
| 206 |
+
# 4. Telemetry snapshot of every buffer, then the routing decision.
|
| 207 |
+
in_buffer = p_ready <= t
|
| 208 |
+
queue = np.bincount(p_node[in_buffer], minlength=n)
|
| 209 |
+
queue_log[t] = queue
|
| 210 |
+
per_flow["queued"][t] = np.bincount(p_flow[in_buffer], minlength=n_flows)
|
| 211 |
+
per_flow["in_transit"][t] = np.bincount(p_flow[~in_buffer], minlength=n_flows)
|
| 212 |
+
if per_step:
|
| 213 |
+
if router == "adaptive_shortest_path":
|
| 214 |
+
cost = np.round((g.latency + queue[g.src] / g.capacity) / COST_QUANTUM)
|
| 215 |
+
by_sink, _ = dijkstra_next_hops(cost, g, sinks)
|
| 216 |
+
next_hop = by_sink[sink_index]
|
| 217 |
+
else:
|
| 218 |
+
phi = field.solve(background + cfg.congestion_gain * queue / buffer)
|
| 219 |
+
cur = currents(phi, g)
|
| 220 |
+
next_hop = steepest_next_hops(cur, g)
|
| 221 |
+
if router == FIELD_ROUTER and t % field_stride == 0:
|
| 222 |
+
phi_log[t // field_stride] = phi[:tracked]
|
| 223 |
+
if previous_hops is not None and next_hop is not previous_hops:
|
| 224 |
+
per_flow["route_changes"][t] = (next_hop != previous_hops).sum(axis=1)
|
| 225 |
+
previous_hops = next_hop
|
| 226 |
+
|
| 227 |
+
# 5. Forwarding: each directed link takes the oldest packets routed over it, up to capacity.
|
| 228 |
+
idx = np.flatnonzero(in_buffer)
|
| 229 |
+
if len(idx):
|
| 230 |
+
node, flow = p_node[idx], p_flow[idx]
|
| 231 |
+
if router == "potential_split":
|
| 232 |
+
hop = spray_next_hops(cur, g, node, flow, p_id[idx])
|
| 233 |
+
elif router == "ecmp":
|
| 234 |
+
hop = ecmp.hops(sink_index[flow], node, p_id[idx])
|
| 235 |
+
else:
|
| 236 |
+
hop = next_hop[flow, node]
|
| 237 |
+
routable = hop >= 0
|
| 238 |
+
idx, hop = idx[routable], hop[routable]
|
| 239 |
+
link = g.dir_edge[p_node[idx], hop]
|
| 240 |
+
order = np.lexsort((p_id[idx], p_ready[idx], link))
|
| 241 |
+
idx, link = idx[order], link[order]
|
| 242 |
+
forward = _rank_within_groups(link) < g.capacity[link]
|
| 243 |
+
idx, link = idx[forward], link[forward]
|
| 244 |
+
p_ready[idx] = t + g.latency[link]
|
| 245 |
+
p_prop[idx] += g.latency[link]
|
| 246 |
+
p_hops[idx] += 1
|
| 247 |
+
p_node[idx] = g.dst[link]
|
| 248 |
+
load = np.bincount(link, minlength=len(g.src))
|
| 249 |
+
link_log[t] = np.bincount(g.base, weights=load, minlength=2 * n_edges).astype(np.int16)
|
| 250 |
+
util_num += load.sum()
|
| 251 |
+
saturated += int((load == g.capacity).sum())
|
| 252 |
+
util_den += g.capacity.sum()
|
| 253 |
+
link_steps += len(g.src)
|
| 254 |
+
|
| 255 |
+
done_flow = np.concatenate(done_flow) if done_flow else np.zeros(0, np.int16)
|
| 256 |
+
done_delay = np.concatenate(done_delay) if done_delay else np.zeros(0, np.int32)
|
| 257 |
+
done_prop = np.concatenate(done_prop) if done_prop else np.zeros(0, np.int32)
|
| 258 |
+
done_hops = np.concatenate(done_hops) if done_hops else np.zeros(0, np.int16)
|
| 259 |
+
in_flight = np.bincount(p_flow, minlength=n_flows).astype(np.int32)
|
| 260 |
+
conserved = per_flow["delivered"].sum(0) + per_flow["dropped"].sum(0) + in_flight
|
| 261 |
+
assert np.array_equal(arrivals.sum(axis=1), conserved), "packet conservation"
|
| 262 |
+
order = np.argsort(done_flow, kind="stable")
|
| 263 |
+
bounds = np.searchsorted(done_flow[order], np.arange(n_flows + 1))
|
| 264 |
+
|
| 265 |
+
def by_flow(values: np.ndarray) -> List[np.ndarray]:
|
| 266 |
+
values = values[order]
|
| 267 |
+
return [values[bounds[f]:bounds[f + 1]] for f in flow_ids]
|
| 268 |
+
|
| 269 |
+
return RouterRun(queue_log, drop_log, link_log, phi_log, per_flow, delay_sum, in_flight,
|
| 270 |
+
by_flow(done_delay), by_flow(done_prop), by_flow(done_hops),
|
| 271 |
+
util_num / util_den, saturated / link_steps)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def field_stride(cfg: SimConfig, n_nodes: int, n_flows: int) -> int:
|
| 275 |
+
tracked = min(cfg.tracked_flows, n_flows)
|
| 276 |
+
return max(1, -(-4 * n_nodes * tracked * cfg.steps // cfg.field_budget_bytes))
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def simulate_episode(cfg: SimConfig, episode_id: int) -> Dict[str, pa.Table]:
|
| 280 |
+
"""Sample one scenario, replay it under every configured router, return its telemetry tables."""
|
| 281 |
+
cells = cfg.cells
|
| 282 |
+
cell_index, replicate, split = locate(episode_id, len(cells))
|
| 283 |
+
cell = cells[cell_index]
|
| 284 |
+
rng = np.random.default_rng([cfg.seed, episode_id])
|
| 285 |
+
topo = generate_topology(cfg, cell, rng)
|
| 286 |
+
base = live_graph(topo.n_nodes, topo.edges, topo.capacity, topo.latency)
|
| 287 |
+
flows = sample_flows(cfg, cell, topo, base, rng)
|
| 288 |
+
mmpp_state, arrivals = sample_mmpp(cfg, cell.profile, flows, rng)
|
| 289 |
+
events, changes = generate_timeline(cfg, topo, cell.dynamics, rng)
|
| 290 |
+
stride = field_stride(cfg, topo.n_nodes, len(flows.source))
|
| 291 |
+
runs = {r: run_router(cfg, topo, flows, arrivals, changes, r, stride) for r in cfg.routers}
|
| 292 |
+
return _episode_tables(cfg, episode_id, cell, cell_index, replicate, split, topo, flows,
|
| 293 |
+
mmpp_state, arrivals, events, stride, runs)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _stat(values: List[np.ndarray], fn, empty=np.nan, dtype=np.float32) -> np.ndarray:
|
| 297 |
+
return np.array([fn(v) if len(v) else empty for v in values], dtype)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _episode_tables(cfg: SimConfig, episode_id: int, cell: Cell, cell_index: int, replicate: int,
|
| 301 |
+
split: str, topo: Topology, flows: Flows, mmpp_state: np.ndarray,
|
| 302 |
+
arrivals: np.ndarray, events: List[TopologyEvent], stride: int,
|
| 303 |
+
runs: Dict[str, RouterRun]) -> Dict[str, pa.Table]:
|
| 304 |
+
n, n_flows, steps, n_edges = topo.n_nodes, len(flows.source), cfg.steps, len(topo.edges)
|
| 305 |
+
tracked = min(cfg.tracked_flows, n_flows)
|
| 306 |
+
step = np.arange(steps, dtype=np.int32)
|
| 307 |
+
offered = arrivals.sum(axis=1).astype(np.int32)
|
| 308 |
+
profile = cell.profile
|
| 309 |
+
|
| 310 |
+
def ep(size: int) -> np.ndarray:
|
| 311 |
+
return np.full(size, episode_id, np.int32)
|
| 312 |
+
|
| 313 |
+
def text(value: str, size: int) -> pa.Array:
|
| 314 |
+
return pa.array([value] * size, pa.string())
|
| 315 |
+
|
| 316 |
+
tables = {
|
| 317 |
+
"episodes": pa.table({
|
| 318 |
+
"episode_id": ep(1), "cell_id": np.array([cell_index], np.int16),
|
| 319 |
+
"replicate": np.array([replicate], np.int16), "split": [split],
|
| 320 |
+
"topology": [cell.topology], "size": np.array([cell.size], np.int16),
|
| 321 |
+
"traffic_profile": [cell.traffic_profile], "load_level": [cell.load_level],
|
| 322 |
+
"dynamics_level": [cell.dynamics_level],
|
| 323 |
+
"n_nodes": np.array([n], np.int16), "n_edges": np.array([n_edges], np.int32),
|
| 324 |
+
"n_flows": np.array([n_flows], np.int16), "tracked_flows": np.array([tracked], np.int16),
|
| 325 |
+
"steps": np.array([steps], np.int32), "field_stride": np.array([stride], np.int16),
|
| 326 |
+
"offered_load": np.array([cell.load], np.float32),
|
| 327 |
+
"total_capacity": np.array([flows.total_capacity], np.float32),
|
| 328 |
+
"edge_u": [topo.edges[:, 0]], "edge_v": [topo.edges[:, 1]],
|
| 329 |
+
"capacity": [topo.capacity], "latency": [topo.latency],
|
| 330 |
+
"node_role": [topo.node_role], "node_x": [topo.node_xy[:, 0]], "node_y": [topo.node_xy[:, 1]],
|
| 331 |
+
"flow_source": [flows.source], "flow_sink": [flows.sink],
|
| 332 |
+
"flow_mean_rate": [flows.mean_rate], "flow_idle_rate": [flows.idle_rate],
|
| 333 |
+
"flow_burst_rate": [flows.burst_rate],
|
| 334 |
+
"p_idle_to_burst": np.array([1.0 / profile.mean_idle_steps if profile.peak_ratio > 1 else 0.0], np.float32),
|
| 335 |
+
"p_burst_to_idle": np.array([1.0 / profile.mean_burst_steps if profile.peak_ratio > 1 else 0.0], np.float32),
|
| 336 |
+
}, schema=SCHEMAS["episodes"]),
|
| 337 |
+
"events": pa.table({
|
| 338 |
+
"episode_id": ep(len(events)),
|
| 339 |
+
"kind": [e.kind for e in events],
|
| 340 |
+
"start": np.array([e.start for e in events], np.int32),
|
| 341 |
+
"end": np.array([e.end for e in events], np.int32),
|
| 342 |
+
"node": np.array([e.node for e in events], np.int16),
|
| 343 |
+
"edge_u": np.array([topo.edges[e.edge, 0] if e.edge >= 0 else -1 for e in events], np.int16),
|
| 344 |
+
"edge_v": np.array([topo.edges[e.edge, 1] if e.edge >= 0 else -1 for e in events], np.int16),
|
| 345 |
+
"factor": np.array([e.factor for e in events], np.float32),
|
| 346 |
+
}, schema=SCHEMAS["events"]),
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
parts = {name: [] for name in ("router_summary", "flow_summary", "flow_telemetry",
|
| 350 |
+
"network_telemetry", "link_telemetry")}
|
| 351 |
+
for router, run in runs.items():
|
| 352 |
+
pf = run.per_flow
|
| 353 |
+
delivered, dropped = pf["delivered"].sum(0), pf["dropped"].sum(0)
|
| 354 |
+
all_delays = np.concatenate(run.delays)
|
| 355 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 356 |
+
flow_mean_delay = (run.delay_sum / pf["delivered"]).astype(np.float32)
|
| 357 |
+
step_mean_delay = (run.delay_sum.sum(1) / pf["delivered"].sum(1)).astype(np.float32)
|
| 358 |
+
parts["router_summary"].append(pa.table({
|
| 359 |
+
"episode_id": ep(1), "router": [router],
|
| 360 |
+
"offered": np.array([offered.sum()], np.int32), "delivered": np.array([delivered.sum()], np.int32),
|
| 361 |
+
"dropped": np.array([dropped.sum()], np.int32), "in_flight": np.array([run.in_flight.sum()], np.int32),
|
| 362 |
+
"loss_ratio": np.array([dropped.sum() / max(offered.sum(), 1)], np.float32),
|
| 363 |
+
"mean_delay": np.array([all_delays.mean() if len(all_delays) else np.nan], np.float32),
|
| 364 |
+
"p99_delay": np.array([np.percentile(all_delays, 99) if len(all_delays) else np.nan], np.float32),
|
| 365 |
+
"mean_queue": np.array([run.queue.mean()], np.float32),
|
| 366 |
+
"max_queue": np.array([run.queue.max()], np.int32),
|
| 367 |
+
"link_utilisation": np.array([run.utilisation], np.float32),
|
| 368 |
+
"link_saturation": np.array([run.saturation], np.float32),
|
| 369 |
+
"route_changes": np.array([pf["route_changes"].sum()], np.int32),
|
| 370 |
+
}, schema=SCHEMAS["router_summary"]))
|
| 371 |
+
quantiles = np.array([np.percentile(d, [50, 95, 99]) if len(d) else [np.nan] * 3
|
| 372 |
+
for d in run.delays], np.float32)
|
| 373 |
+
parts["flow_summary"].append(pa.table({
|
| 374 |
+
"episode_id": ep(n_flows), "router": text(router, n_flows),
|
| 375 |
+
"flow": np.arange(n_flows, dtype=np.int16), "source": flows.source, "sink": flows.sink,
|
| 376 |
+
"mean_rate": flows.mean_rate, "min_hops": flows.min_hops, "min_latency": flows.min_latency,
|
| 377 |
+
"offered": offered, "delivered": delivered, "dropped": dropped, "in_flight": run.in_flight,
|
| 378 |
+
"loss_ratio": (dropped / np.maximum(offered, 1)).astype(np.float32),
|
| 379 |
+
"mean_delay": _stat(run.delays, np.mean), "delay_std": _stat(run.delays, np.std),
|
| 380 |
+
"p50_delay": quantiles[:, 0], "p95_delay": quantiles[:, 1], "p99_delay": quantiles[:, 2],
|
| 381 |
+
"max_delay": _stat(run.delays, np.max, -1, np.int32),
|
| 382 |
+
"mean_queueing_delay": np.array([(d - p).mean() if len(d) else np.nan
|
| 383 |
+
for d, p in zip(run.delays, run.propagation)], np.float32),
|
| 384 |
+
"mean_path_latency": _stat(run.propagation, np.mean),
|
| 385 |
+
"mean_hops": _stat(run.hops, np.mean),
|
| 386 |
+
"route_changes": pf["route_changes"].sum(0).astype(np.int32),
|
| 387 |
+
}, schema=SCHEMAS["flow_summary"]))
|
| 388 |
+
tf = slice(0, tracked)
|
| 389 |
+
parts["flow_telemetry"].append(pa.table({
|
| 390 |
+
"episode_id": ep(steps * tracked), "router": text(router, steps * tracked),
|
| 391 |
+
"step": np.repeat(step, tracked), "flow": np.tile(np.arange(tracked, dtype=np.int16), steps),
|
| 392 |
+
"mmpp_state": mmpp_state[tf].T.ravel(), "offered": arrivals[tf].T.ravel(),
|
| 393 |
+
"admitted": pf["admitted"][:, tf].ravel(), "delivered": pf["delivered"][:, tf].ravel(),
|
| 394 |
+
"dropped": pf["dropped"][:, tf].ravel(), "queued": pf["queued"][:, tf].ravel(),
|
| 395 |
+
"in_transit": pf["in_transit"][:, tf].ravel(), "mean_delay": flow_mean_delay[:, tf].ravel(),
|
| 396 |
+
"route_changes": pf["route_changes"][:, tf].ravel(),
|
| 397 |
+
}, schema=SCHEMAS["flow_telemetry"]))
|
| 398 |
+
parts["network_telemetry"].append(pa.table({
|
| 399 |
+
"episode_id": ep(steps), "router": text(router, steps), "step": step,
|
| 400 |
+
"offered": arrivals.sum(0).astype(np.int32), "admitted": pf["admitted"].sum(1),
|
| 401 |
+
"delivered": pf["delivered"].sum(1), "dropped": pf["dropped"].sum(1),
|
| 402 |
+
"queued": pf["queued"].sum(1), "in_transit": pf["in_transit"].sum(1),
|
| 403 |
+
"mean_delay": step_mean_delay, "route_changes": pf["route_changes"].sum(1),
|
| 404 |
+
"queue_depth": list_column(run.queue, pa.int16()),
|
| 405 |
+
"node_dropped": list_column(run.node_drops, pa.int16()),
|
| 406 |
+
}, schema=SCHEMAS["network_telemetry"]))
|
| 407 |
+
parts["link_telemetry"].append(pa.table({
|
| 408 |
+
"episode_id": ep(steps), "router": text(router, steps), "step": step,
|
| 409 |
+
"load_uv": list_column(run.link_load[:, :n_edges], pa.int16()),
|
| 410 |
+
"load_vu": list_column(run.link_load[:, n_edges:], pa.int16()),
|
| 411 |
+
}, schema=SCHEMAS["link_telemetry"]))
|
| 412 |
+
if run.potential is not None:
|
| 413 |
+
snapshots = run.potential.shape[0]
|
| 414 |
+
tables["potential_field"] = pa.table({
|
| 415 |
+
"episode_id": ep(snapshots), "step": (np.arange(snapshots) * stride).astype(np.int32),
|
| 416 |
+
"potential": list_column(run.potential.reshape(snapshots, -1), pa.float32()),
|
| 417 |
+
}, schema=SCHEMAS["potential_field"])
|
| 418 |
+
for name, chunks in parts.items():
|
| 419 |
+
tables[name] = pa.concat_tables(chunks)
|
| 420 |
+
return tables
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def run_sweep(cfg: SimConfig, data_dir: Path, workers: int, log=print) -> None:
|
| 424 |
+
"""Map every unfinished shard of episodes across `workers` processes and stream it to Parquet."""
|
| 425 |
+
n_shards = -(-cfg.episodes // cfg.shard_episodes)
|
| 426 |
+
|
| 427 |
+
def shard_ids(shard: int) -> range:
|
| 428 |
+
return range(shard * cfg.shard_episodes, min((shard + 1) * cfg.shard_episodes, cfg.episodes))
|
| 429 |
+
|
| 430 |
+
done = completed_shards(data_dir, n_shards, cfg.routers)
|
| 431 |
+
todo = [s for s in range(n_shards) if s not in done]
|
| 432 |
+
if done:
|
| 433 |
+
log(f"Resuming: {len(done)}/{n_shards} shards already complete.")
|
| 434 |
+
if not todo:
|
| 435 |
+
log("Nothing to do: every shard is complete.")
|
| 436 |
+
return
|
| 437 |
+
episodes_todo = [e for s in todo for e in shard_ids(s)]
|
| 438 |
+
log(f"Simulating {len(episodes_todo)} episodes x {len(cfg.routers)} routers "
|
| 439 |
+
f"({len(cfg.cells)} design cells) on {workers} workers ...")
|
| 440 |
+
start, finished = time.time(), 0
|
| 441 |
+
with mp.get_context("spawn").Pool(workers) as pool: # same start method on every platform
|
| 442 |
+
results = pool.imap(partial(simulate_episode, cfg), episodes_todo, chunksize=1)
|
| 443 |
+
for shard in todo:
|
| 444 |
+
ids = shard_ids(shard)
|
| 445 |
+
write_shard(data_dir, shard, [next(results) for _ in ids])
|
| 446 |
+
finished += len(ids)
|
| 447 |
+
elapsed = time.time() - start
|
| 448 |
+
eta = elapsed / finished * (len(episodes_todo) - finished)
|
| 449 |
+
log(f" shard {shard + 1:>4}/{n_shards} episodes {finished:>6}/{len(episodes_todo)} "
|
| 450 |
+
f"elapsed {elapsed / 3600:5.2f} h eta {eta / 3600:5.2f} h")
|
| 451 |
+
log(f"Done in {(time.time() - start) / 3600:.2f} h.")
|
src/telemetry_logger.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming Parquet serialisation and the dataset manifest.
|
| 2 |
+
|
| 3 |
+
The dataset is a relational schema of eight tables. Each shard of episodes is written as one
|
| 4 |
+
``data/<table>/part-XXXXX.parquet`` file (zstd, modest row groups so readers can stream), through
|
| 5 |
+
a temporary file that is renamed only once complete. A shard is therefore either fully present or
|
| 6 |
+
absent, which makes an interrupted sweep resumable and keeps memory bounded to one shard.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import platform
|
| 12 |
+
import sys
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Dict, List, Sequence
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pyarrow as pa
|
| 19 |
+
import pyarrow.parquet as pq
|
| 20 |
+
|
| 21 |
+
ROW_GROUP_SIZE = 8192
|
| 22 |
+
|
| 23 |
+
SCHEMAS: Dict[str, pa.Schema] = {
|
| 24 |
+
# One row per episode: design cell, split, static graph, flows and traffic parameters.
|
| 25 |
+
"episodes": pa.schema([
|
| 26 |
+
("episode_id", pa.int32()), ("cell_id", pa.int16()), ("replicate", pa.int16()), ("split", pa.string()),
|
| 27 |
+
("topology", pa.string()), ("size", pa.int16()), ("traffic_profile", pa.string()),
|
| 28 |
+
("load_level", pa.string()), ("dynamics_level", pa.string()),
|
| 29 |
+
("n_nodes", pa.int16()), ("n_edges", pa.int32()), ("n_flows", pa.int16()), ("tracked_flows", pa.int16()),
|
| 30 |
+
("steps", pa.int32()), ("field_stride", pa.int16()),
|
| 31 |
+
("offered_load", pa.float32()), ("total_capacity", pa.float32()),
|
| 32 |
+
("edge_u", pa.list_(pa.int16())), ("edge_v", pa.list_(pa.int16())),
|
| 33 |
+
("capacity", pa.list_(pa.int16())), ("latency", pa.list_(pa.int16())),
|
| 34 |
+
("node_role", pa.list_(pa.int8())), ("node_x", pa.list_(pa.float32())), ("node_y", pa.list_(pa.float32())),
|
| 35 |
+
("flow_source", pa.list_(pa.int16())), ("flow_sink", pa.list_(pa.int16())),
|
| 36 |
+
("flow_mean_rate", pa.list_(pa.float32())), ("flow_idle_rate", pa.list_(pa.float32())),
|
| 37 |
+
("flow_burst_rate", pa.list_(pa.float32())),
|
| 38 |
+
("p_idle_to_burst", pa.float32()), ("p_burst_to_idle", pa.float32()),
|
| 39 |
+
]),
|
| 40 |
+
# One row per topology event; active for start <= step < end.
|
| 41 |
+
"events": pa.schema([
|
| 42 |
+
("episode_id", pa.int32()), ("kind", pa.string()), ("start", pa.int32()), ("end", pa.int32()),
|
| 43 |
+
("node", pa.int16()), ("edge_u", pa.int16()), ("edge_v", pa.int16()), ("factor", pa.float32()),
|
| 44 |
+
]),
|
| 45 |
+
# One row per (episode, router): network-level benchmark figures.
|
| 46 |
+
"router_summary": pa.schema([
|
| 47 |
+
("episode_id", pa.int32()), ("router", pa.string()),
|
| 48 |
+
("offered", pa.int32()), ("delivered", pa.int32()), ("dropped", pa.int32()), ("in_flight", pa.int32()),
|
| 49 |
+
("loss_ratio", pa.float32()), ("mean_delay", pa.float32()), ("p99_delay", pa.float32()),
|
| 50 |
+
("mean_queue", pa.float32()), ("max_queue", pa.int32()),
|
| 51 |
+
("link_utilisation", pa.float32()), ("link_saturation", pa.float32()),
|
| 52 |
+
("route_changes", pa.int32()),
|
| 53 |
+
]),
|
| 54 |
+
# One row per (episode, router, flow): end-to-end benchmark figures.
|
| 55 |
+
"flow_summary": pa.schema([
|
| 56 |
+
("episode_id", pa.int32()), ("router", pa.string()), ("flow", pa.int16()),
|
| 57 |
+
("source", pa.int16()), ("sink", pa.int16()), ("mean_rate", pa.float32()),
|
| 58 |
+
("min_hops", pa.int16()), ("min_latency", pa.int16()),
|
| 59 |
+
("offered", pa.int32()), ("delivered", pa.int32()), ("dropped", pa.int32()), ("in_flight", pa.int32()),
|
| 60 |
+
("loss_ratio", pa.float32()), ("mean_delay", pa.float32()), ("delay_std", pa.float32()),
|
| 61 |
+
("p50_delay", pa.float32()), ("p95_delay", pa.float32()), ("p99_delay", pa.float32()),
|
| 62 |
+
("max_delay", pa.int32()), ("mean_queueing_delay", pa.float32()), ("mean_path_latency", pa.float32()),
|
| 63 |
+
("mean_hops", pa.float32()), ("route_changes", pa.int32()),
|
| 64 |
+
]),
|
| 65 |
+
# One row per (episode, router, step, tracked flow).
|
| 66 |
+
"flow_telemetry": pa.schema([
|
| 67 |
+
("episode_id", pa.int32()), ("router", pa.string()), ("step", pa.int32()), ("flow", pa.int16()),
|
| 68 |
+
("mmpp_state", pa.int8()), ("offered", pa.int32()), ("admitted", pa.int32()),
|
| 69 |
+
("delivered", pa.int32()), ("dropped", pa.int32()), ("queued", pa.int32()), ("in_transit", pa.int32()),
|
| 70 |
+
("mean_delay", pa.float32()), ("route_changes", pa.int32()),
|
| 71 |
+
]),
|
| 72 |
+
# One row per (episode, router, step): network totals plus occupancy and drops of every node.
|
| 73 |
+
"network_telemetry": pa.schema([
|
| 74 |
+
("episode_id", pa.int32()), ("router", pa.string()), ("step", pa.int32()),
|
| 75 |
+
("offered", pa.int32()), ("admitted", pa.int32()), ("delivered", pa.int32()), ("dropped", pa.int32()),
|
| 76 |
+
("queued", pa.int32()), ("in_transit", pa.int32()), ("mean_delay", pa.float32()), ("route_changes", pa.int32()),
|
| 77 |
+
("queue_depth", pa.list_(pa.int16())), ("node_dropped", pa.list_(pa.int16())),
|
| 78 |
+
]),
|
| 79 |
+
# One row per (episode, router, step): packets forwarded over every link, per direction.
|
| 80 |
+
"link_telemetry": pa.schema([
|
| 81 |
+
("episode_id", pa.int32()), ("router", pa.string()), ("step", pa.int32()),
|
| 82 |
+
("load_uv", pa.list_(pa.int16())), ("load_vu", pa.list_(pa.int16())),
|
| 83 |
+
]),
|
| 84 |
+
# One row per logged step of the potential router: φ of the tracked flows, flattened (tracked × N).
|
| 85 |
+
"potential_field": pa.schema([
|
| 86 |
+
("episode_id", pa.int32()), ("step", pa.int32()), ("potential", pa.list_(pa.float32())),
|
| 87 |
+
]),
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def table_names(routers: Sequence[str]) -> List[str]:
|
| 92 |
+
return [t for t in SCHEMAS if t != "potential_field" or "potential" in routers]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def list_column(matrix: np.ndarray, value_type: pa.DataType) -> pa.ListArray:
|
| 96 |
+
"""A (rows, width) array as a list<value_type> column with one fixed-width list per row."""
|
| 97 |
+
rows, width = matrix.shape
|
| 98 |
+
offsets = np.arange(0, (rows + 1) * width, width, dtype=np.int32)
|
| 99 |
+
return pa.ListArray.from_arrays(pa.array(offsets), pa.array(np.ascontiguousarray(matrix).ravel(), type=value_type))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def shard_path(data_dir: Path, table: str, shard: int) -> Path:
|
| 103 |
+
return data_dir / table / f"part-{shard:05d}.parquet"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def shard_files(data_dir: Path, table: str) -> List[Path]:
|
| 107 |
+
return sorted((data_dir / table).glob("part-*.parquet"))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def completed_shards(data_dir: Path, n_shards: int, routers: Sequence[str]) -> List[int]:
|
| 111 |
+
for stale in data_dir.glob("*/*.tmp"):
|
| 112 |
+
stale.unlink()
|
| 113 |
+
return [s for s in range(n_shards)
|
| 114 |
+
if all(shard_path(data_dir, t, s).exists() for t in table_names(routers))]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def write_shard(data_dir: Path, shard: int, episodes: List[Dict[str, pa.Table]]) -> None:
|
| 118 |
+
for table in episodes[0]:
|
| 119 |
+
final = shard_path(data_dir, table, shard)
|
| 120 |
+
final.parent.mkdir(parents=True, exist_ok=True)
|
| 121 |
+
tmp = final.with_name(final.name + ".tmp")
|
| 122 |
+
pq.write_table(pa.concat_tables([e[table] for e in episodes]), tmp,
|
| 123 |
+
compression="zstd", row_group_size=ROW_GROUP_SIZE)
|
| 124 |
+
tmp.replace(final)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def read_table(data_dir: Path, table: str, columns=None, filters=None) -> pa.Table:
|
| 128 |
+
return pq.read_table(shard_files(data_dir, table), columns=columns, filters=filters)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def table_stats(data_dir: Path, table: str) -> Dict[str, int]:
|
| 132 |
+
files = shard_files(data_dir, table)
|
| 133 |
+
return {"files": len(files),
|
| 134 |
+
"rows": sum(pq.read_metadata(f).num_rows for f in files),
|
| 135 |
+
"bytes": sum(f.stat().st_size for f in files)}
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def write_manifest(data_dir: Path, cfg, dataset_version: str) -> Dict:
|
| 139 |
+
"""Provenance, design coverage and table statistics of the shards present in `data_dir`."""
|
| 140 |
+
import networkx, pandas, scipy # noqa: E401 (versions only)
|
| 141 |
+
|
| 142 |
+
episodes = read_table(data_dir, "episodes",
|
| 143 |
+
columns=["episode_id", "cell_id", "split", "topology", "size",
|
| 144 |
+
"traffic_profile", "load_level", "dynamics_level"]).to_pandas()
|
| 145 |
+
coverage = {name: episodes[name].value_counts().sort_index().to_dict()
|
| 146 |
+
for name in ("topology", "size", "traffic_profile", "load_level", "dynamics_level", "split")}
|
| 147 |
+
per_cell = episodes.cell_id.value_counts()
|
| 148 |
+
manifest = {
|
| 149 |
+
"dataset_version": dataset_version,
|
| 150 |
+
"created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
| 151 |
+
"provenance": {
|
| 152 |
+
"python": sys.version.split()[0], "platform": platform.platform(),
|
| 153 |
+
"numpy": np.__version__, "scipy": scipy.__version__, "pyarrow": pa.__version__,
|
| 154 |
+
"pandas": pandas.__version__, "networkx": networkx.__version__,
|
| 155 |
+
},
|
| 156 |
+
"config": json.loads(cfg.to_json()),
|
| 157 |
+
"design": {"cells": len(cfg.cells), "episodes_planned": cfg.episodes,
|
| 158 |
+
"episodes_present": int(len(episodes)),
|
| 159 |
+
"episodes_per_cell_min": int(per_cell.min()), "episodes_per_cell_max": int(per_cell.max())},
|
| 160 |
+
"coverage": {k: {str(kk): int(vv) for kk, vv in v.items()} for k, v in coverage.items()},
|
| 161 |
+
"tables": {name: table_stats(data_dir, name) for name in table_names(cfg.routers)},
|
| 162 |
+
}
|
| 163 |
+
(data_dir / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
| 164 |
+
return manifest
|
terminal_logs.txt
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PS C:\Users\g28630518\Documents\SemanticPotentialRoutingTelemetryDataset> python .\scripts\run_local_sweep.py --smoke
|
| 2 |
+
Smoke test in C:\Users\G28630~1\AppData\Local\Temp\sprt-smoke-scvkh98l
|
| 3 |
+
Simulating 15 episodes x 6 routers (15 design cells) on 12 workers ...
|
| 4 |
+
shard 1/3 episodes 5/15 elapsed 0.00 h eta 0.00 h
|
| 5 |
+
shard 2/3 episodes 10/15 elapsed 0.00 h eta 0.00 h
|
| 6 |
+
shard 3/3 episodes 15/15 elapsed 0.00 h eta 0.00 h
|
| 7 |
+
Done in 0.00 h.
|
| 8 |
+
|
| 9 |
+
Router benchmark (means over episodes):
|
| 10 |
+
loss_ratio mean_delay p99_delay link_utilisation route_changes
|
| 11 |
+
router
|
| 12 |
+
adaptive_shortest_path 0.037 9.524 24.333000 0.117 39109.533
|
| 13 |
+
ecmp 0.263 11.356 50.390999 0.094 72.600
|
| 14 |
+
potential 0.074 10.387 28.132999 0.112 18638.000
|
| 15 |
+
potential_split 0.024 11.443 29.933001 0.131 10474.333
|
| 16 |
+
potential_static 0.179 11.519 33.266998 0.118 330.467
|
| 17 |
+
shortest_path 0.264 11.205 42.466999 0.093 72.600
|
| 18 |
+
|
| 19 |
+
Design coverage (episodes per level):
|
| 20 |
+
topology barabasi_albert=3 erdos_renyi=3 fat_tree=3 watts_strogatz=3 waxman=3
|
| 21 |
+
size 32=15
|
| 22 |
+
traffic_profile microburst=5 poisson=5 sustained=5
|
| 23 |
+
load_level heavy=15
|
| 24 |
+
dynamics_level severe=15
|
| 25 |
+
split train=15
|
| 26 |
+
cells 15, episodes 15/15, per cell 1-1
|
| 27 |
+
|
| 28 |
+
Tables:
|
| 29 |
+
episodes 3 files 15 rows 0.00 GB
|
| 30 |
+
events 3 files 65 rows 0.00 GB
|
| 31 |
+
router_summary 3 files 90 rows 0.00 GB
|
| 32 |
+
flow_summary 3 files 5,184 rows 0.00 GB
|
| 33 |
+
flow_telemetry 3 files 144,000 rows 0.00 GB
|
| 34 |
+
network_telemetry 3 files 18,000 rows 0.00 GB
|
| 35 |
+
link_telemetry 3 files 18,000 rows 0.00 GB
|
| 36 |
+
potential_field 3 files 3,000 rows 0.00 GB
|
| 37 |
+
total 0.01 GB
|
| 38 |
+
|
| 39 |
+
Smoke test passed.
|
| 40 |
+
PS C:\Users\g28630518\Documents\SemanticPotentialRoutingTelemetryDataset> python .\scripts\run_local_sweep.py
|
| 41 |
+
Simulating 5400 episodes x 6 routers (540 design cells) on 12 workers ...
|
| 42 |
+
shard 1/135 episodes 40/5400 elapsed 0.01 h eta 1.56 h
|
| 43 |
+
shard 2/135 episodes 80/5400 elapsed 0.06 h eta 4.22 h
|
| 44 |
+
shard 3/135 episodes 120/5400 elapsed 0.27 h eta 11.80 h
|
| 45 |
+
shard 4/135 episodes 160/5400 elapsed 0.27 h eta 8.92 h
|
| 46 |
+
shard 5/135 episodes 200/5400 elapsed 0.37 h eta 9.60 h
|
| 47 |
+
shard 6/135 episodes 240/5400 elapsed 0.49 h eta 10.58 h
|
| 48 |
+
shard 7/135 episodes 280/5400 elapsed 0.50 h eta 9.10 h
|
| 49 |
+
shard 8/135 episodes 320/5400 elapsed 0.69 h eta 10.94 h
|
| 50 |
+
shard 9/135 episodes 360/5400 elapsed 0.76 h eta 10.66 h
|
| 51 |
+
shard 10/135 episodes 400/5400 elapsed 0.78 h eta 9.79 h
|
| 52 |
+
shard 11/135 episodes 440/5400 elapsed 1.07 h eta 12.04 h
|
| 53 |
+
shard 12/135 episodes 480/5400 elapsed 1.07 h eta 11.00 h
|
| 54 |
+
shard 13/135 episodes 520/5400 elapsed 1.17 h eta 10.98 h
|
| 55 |
+
shard 14/135 episodes 560/5400 elapsed 1.34 h eta 11.58 h
|
| 56 |
+
shard 15/135 episodes 600/5400 elapsed 1.35 h eta 10.77 h
|
| 57 |
+
shard 16/135 episodes 640/5400 elapsed 1.58 h eta 11.74 h
|
| 58 |
+
shard 17/135 episodes 680/5400 elapsed 1.66 h eta 11.50 h
|
| 59 |
+
shard 18/135 episodes 720/5400 elapsed 1.68 h eta 10.93 h
|
| 60 |
+
shard 19/135 episodes 760/5400 elapsed 1.97 h eta 12.05 h
|
| 61 |
+
shard 20/135 episodes 800/5400 elapsed 1.98 h eta 11.38 h
|
| 62 |
+
shard 21/135 episodes 840/5400 elapsed 2.09 h eta 11.34 h
|
| 63 |
+
shard 22/135 episodes 880/5400 elapsed 2.31 h eta 11.87 h
|
| 64 |
+
shard 23/135 episodes 920/5400 elapsed 2.32 h eta 11.28 h
|
| 65 |
+
shard 24/135 episodes 960/5400 elapsed 2.50 h eta 11.59 h
|
| 66 |
+
shard 25/135 episodes 1000/5400 elapsed 2.60 h eta 11.45 h
|
| 67 |
+
shard 26/135 episodes 1040/5400 elapsed 2.61 h eta 10.94 h
|
| 68 |
+
shard 27/135 episodes 1080/5400 elapsed 2.88 h eta 11.52 h
|
| 69 |
+
shard 28/135 episodes 1120/5400 elapsed 2.88 h eta 11.02 h
|
| 70 |
+
shard 29/135 episodes 1160/5400 elapsed 2.92 h eta 10.69 h
|
| 71 |
+
shard 30/135 episodes 1200/5400 elapsed 3.23 h eta 11.31 h
|
| 72 |
+
shard 31/135 episodes 1240/5400 elapsed 3.24 h eta 10.87 h
|
| 73 |
+
shard 32/135 episodes 1280/5400 elapsed 3.38 h eta 10.90 h
|
| 74 |
+
shard 33/135 episodes 1320/5400 elapsed 3.58 h eta 11.05 h
|
| 75 |
+
shard 34/135 episodes 1360/5400 elapsed 3.58 h eta 10.64 h
|
| 76 |
+
shard 35/135 episodes 1400/5400 elapsed 3.83 h eta 10.95 h
|
| 77 |
+
shard 36/135 episodes 1440/5400 elapsed 3.91 h eta 10.76 h
|
| 78 |
+
shard 37/135 episodes 1480/5400 elapsed 3.95 h eta 10.45 h
|
| 79 |
+
shard 38/135 episodes 1520/5400 elapsed 4.26 h eta 10.88 h
|
| 80 |
+
shard 39/135 episodes 1560/5400 elapsed 4.27 h eta 10.50 h
|
| 81 |
+
shard 40/135 episodes 1600/5400 elapsed 4.38 h eta 10.39 h
|
| 82 |
+
shard 41/135 episodes 1640/5400 elapsed 4.56 h eta 10.46 h
|
| 83 |
+
shard 42/135 episodes 1680/5400 elapsed 4.57 h eta 10.12 h
|
| 84 |
+
shard 43/135 episodes 1720/5400 elapsed 4.82 h eta 10.32 h
|
| 85 |
+
shard 44/135 episodes 1760/5400 elapsed 4.89 h eta 10.12 h
|
| 86 |
+
shard 45/135 episodes 1800/5400 elapsed 4.92 h eta 9.84 h
|
| 87 |
+
shard 46/135 episodes 1840/5400 elapsed 5.18 h eta 10.03 h
|
| 88 |
+
shard 47/135 episodes 1880/5400 elapsed 5.19 h eta 9.71 h
|
| 89 |
+
shard 48/135 episodes 1920/5400 elapsed 5.28 h eta 9.57 h
|
| 90 |
+
shard 49/135 episodes 1960/5400 elapsed 5.47 h eta 9.60 h
|
| 91 |
+
shard 50/135 episodes 2000/5400 elapsed 5.47 h eta 9.31 h
|
| 92 |
+
shard 51/135 episodes 2040/5400 elapsed 5.65 h eta 9.31 h
|
| 93 |
+
shard 52/135 episodes 2080/5400 elapsed 5.74 h eta 9.16 h
|
| 94 |
+
shard 53/135 episodes 2120/5400 elapsed 5.75 h eta 8.89 h
|
| 95 |
+
shard 54/135 episodes 2160/5400 elapsed 6.00 h eta 9.00 h
|
| 96 |
+
shard 55/135 episodes 2200/5400 elapsed 6.00 h eta 8.73 h
|
| 97 |
+
shard 56/135 episodes 2240/5400 elapsed 6.03 h eta 8.51 h
|
| 98 |
+
shard 57/135 episodes 2280/5400 elapsed 6.29 h eta 8.61 h
|
| 99 |
+
shard 58/135 episodes 2320/5400 elapsed 6.30 h eta 8.36 h
|
| 100 |
+
shard 59/135 episodes 2360/5400 elapsed 6.42 h eta 8.27 h
|
| 101 |
+
shard 60/135 episodes 2400/5400 elapsed 6.58 h eta 8.22 h
|
| 102 |
+
shard 61/135 episodes 2440/5400 elapsed 6.58 h eta 7.98 h
|
| 103 |
+
shard 62/135 episodes 2480/5400 elapsed 6.79 h eta 8.00 h
|
| 104 |
+
shard 63/135 episodes 2520/5400 elapsed 6.87 h eta 7.86 h
|
| 105 |
+
shard 64/135 episodes 2560/5400 elapsed 6.89 h eta 7.65 h
|
| 106 |
+
shard 65/135 episodes 2600/5400 elapsed 7.20 h eta 7.75 h
|
| 107 |
+
shard 66/135 episodes 2640/5400 elapsed 7.20 h eta 7.53 h
|
| 108 |
+
shard 67/135 episodes 2680/5400 elapsed 7.30 h eta 7.41 h
|
| 109 |
+
shard 68/135 episodes 2720/5400 elapsed 7.47 h eta 7.36 h
|
| 110 |
+
shard 69/135 episodes 2760/5400 elapsed 7.48 h eta 7.15 h
|
| 111 |
+
shard 70/135 episodes 2800/5400 elapsed 7.72 h eta 7.17 h
|
| 112 |
+
shard 71/135 episodes 2840/5400 elapsed 7.80 h eta 7.03 h
|
| 113 |
+
shard 72/135 episodes 2880/5400 elapsed 7.83 h eta 6.85 h
|
| 114 |
+
shard 73/135 episodes 2920/5400 elapsed 8.14 h eta 6.91 h
|
| 115 |
+
shard 74/135 episodes 2960/5400 elapsed 8.14 h eta 6.71 h
|
| 116 |
+
shard 75/135 episodes 3000/5400 elapsed 8.25 h eta 6.60 h
|
| 117 |
+
shard 76/135 episodes 3040/5400 elapsed 8.48 h eta 6.59 h
|
| 118 |
+
shard 77/135 episodes 3080/5400 elapsed 8.49 h eta 6.39 h
|
| 119 |
+
shard 78/135 episodes 3120/5400 elapsed 8.74 h eta 6.39 h
|
| 120 |
+
shard 79/135 episodes 3160/5400 elapsed 8.84 h eta 6.27 h
|
| 121 |
+
shard 80/135 episodes 3200/5400 elapsed 8.85 h eta 6.09 h
|
| 122 |
+
shard 81/135 episodes 3240/5400 elapsed 9.14 h eta 6.09 h
|
| 123 |
+
shard 82/135 episodes 3280/5400 elapsed 9.14 h eta 5.91 h
|
| 124 |
+
shard 83/135 episodes 3320/5400 elapsed 9.18 h eta 5.75 h
|
| 125 |
+
shard 84/135 episodes 3360/5400 elapsed 9.47 h eta 5.75 h
|
| 126 |
+
shard 85/135 episodes 3400/5400 elapsed 9.48 h eta 5.57 h
|
| 127 |
+
shard 86/135 episodes 3440/5400 elapsed 9.61 h eta 5.48 h
|
| 128 |
+
shard 87/135 episodes 3480/5400 elapsed 9.78 h eta 5.40 h
|
| 129 |
+
shard 88/135 episodes 3520/5400 elapsed 9.79 h eta 5.23 h
|
| 130 |
+
shard 89/135 episodes 3560/5400 elapsed 10.03 h eta 5.18 h
|
| 131 |
+
shard 90/135 episodes 3600/5400 elapsed 10.10 h eta 5.05 h
|
| 132 |
+
shard 91/135 episodes 3640/5400 elapsed 10.13 h eta 4.90 h
|
| 133 |
+
shard 92/135 episodes 3680/5400 elapsed 10.42 h eta 4.87 h
|
| 134 |
+
shard 93/135 episodes 3720/5400 elapsed 10.43 h eta 4.71 h
|
| 135 |
+
shard 94/135 episodes 3760/5400 elapsed 10.55 h eta 4.60 h
|
| 136 |
+
shard 95/135 episodes 3800/5400 elapsed 10.78 h eta 4.54 h
|
| 137 |
+
shard 96/135 episodes 3840/5400 elapsed 10.79 h eta 4.38 h
|
| 138 |
+
shard 97/135 episodes 3880/5400 elapsed 11.03 h eta 4.32 h
|
| 139 |
+
shard 98/135 episodes 3920/5400 elapsed 11.12 h eta 4.20 h
|
| 140 |
+
shard 99/135 episodes 3960/5400 elapsed 11.14 h eta 4.05 h
|
| 141 |
+
shard 100/135 episodes 4000/5400 elapsed 11.44 h eta 4.00 h
|
| 142 |
+
shard 101/135 episodes 4040/5400 elapsed 11.44 h eta 3.85 h
|
| 143 |
+
shard 102/135 episodes 4080/5400 elapsed 11.55 h eta 3.74 h
|
| 144 |
+
shard 103/135 episodes 4120/5400 elapsed 11.75 h eta 3.65 h
|
| 145 |
+
shard 104/135 episodes 4160/5400 elapsed 11.76 h eta 3.51 h
|
| 146 |
+
shard 105/135 episodes 4200/5400 elapsed 11.96 h eta 3.42 h
|
| 147 |
+
shard 106/135 episodes 4240/5400 elapsed 12.06 h eta 3.30 h
|
| 148 |
+
shard 107/135 episodes 4280/5400 elapsed 12.07 h eta 3.16 h
|
| 149 |
+
shard 108/135 episodes 4320/5400 elapsed 12.35 h eta 3.09 h
|
| 150 |
+
shard 109/135 episodes 4360/5400 elapsed 12.36 h eta 2.95 h
|
| 151 |
+
shard 110/135 episodes 4400/5400 elapsed 12.39 h eta 2.82 h
|
| 152 |
+
shard 111/135 episodes 4440/5400 elapsed 12.67 h eta 2.74 h
|
| 153 |
+
shard 112/135 episodes 4480/5400 elapsed 12.68 h eta 2.60 h
|
| 154 |
+
shard 113/135 episodes 4520/5400 elapsed 12.81 h eta 2.49 h
|
| 155 |
+
shard 114/135 episodes 4560/5400 elapsed 12.97 h eta 2.39 h
|
| 156 |
+
shard 115/135 episodes 4600/5400 elapsed 12.98 h eta 2.26 h
|
| 157 |
+
shard 116/135 episodes 4640/5400 elapsed 13.21 h eta 2.16 h
|
| 158 |
+
shard 117/135 episodes 4680/5400 elapsed 13.29 h eta 2.04 h
|
| 159 |
+
shard 118/135 episodes 4720/5400 elapsed 13.31 h eta 1.92 h
|
| 160 |
+
shard 119/135 episodes 4760/5400 elapsed 13.58 h eta 1.83 h
|
| 161 |
+
shard 120/135 episodes 4800/5400 elapsed 13.59 h eta 1.70 h
|
| 162 |
+
shard 121/135 episodes 4840/5400 elapsed 13.68 h eta 1.58 h
|
| 163 |
+
shard 122/135 episodes 4880/5400 elapsed 13.83 h eta 1.47 h
|
| 164 |
+
shard 123/135 episodes 4920/5400 elapsed 13.83 h eta 1.35 h
|
| 165 |
+
shard 124/135 episodes 4960/5400 elapsed 14.05 h eta 1.25 h
|
| 166 |
+
shard 125/135 episodes 5000/5400 elapsed 14.12 h eta 1.13 h
|
| 167 |
+
shard 126/135 episodes 5040/5400 elapsed 14.14 h eta 1.01 h
|
| 168 |
+
shard 127/135 episodes 5080/5400 elapsed 14.41 h eta 0.91 h
|
| 169 |
+
shard 128/135 episodes 5120/5400 elapsed 14.41 h eta 0.79 h
|
| 170 |
+
shard 129/135 episodes 5160/5400 elapsed 14.50 h eta 0.67 h
|
| 171 |
+
shard 130/135 episodes 5200/5400 elapsed 14.69 h eta 0.56 h
|
| 172 |
+
shard 131/135 episodes 5240/5400 elapsed 14.69 h eta 0.45 h
|
| 173 |
+
shard 132/135 episodes 5280/5400 elapsed 14.87 h eta 0.34 h
|
| 174 |
+
shard 133/135 episodes 5320/5400 elapsed 14.96 h eta 0.22 h
|
| 175 |
+
shard 134/135 episodes 5360/5400 elapsed 14.97 h eta 0.11 h
|
| 176 |
+
shard 135/135 episodes 5400/5400 elapsed 15.16 h eta 0.00 h
|
| 177 |
+
Done in 15.17 h.
|
| 178 |
+
|
| 179 |
+
Router benchmark (means over episodes):
|
| 180 |
+
loss_ratio mean_delay p99_delay link_utilisation route_changes
|
| 181 |
+
router
|
| 182 |
+
adaptive_shortest_path 0.016 10.344 20.948000 0.054 5268980.419
|
| 183 |
+
ecmp 0.118 11.639 34.861000 0.047 1284.729
|
| 184 |
+
potential 0.034 12.297 27.170000 0.054 5176894.254
|
| 185 |
+
potential_split 0.011 15.048 36.096001 0.062 3228916.197
|
| 186 |
+
potential_static 0.102 14.229 32.320000 0.059 12504.789
|
| 187 |
+
shortest_path 0.161 12.115 36.713001 0.044 1284.729
|
| 188 |
+
|
| 189 |
+
Design coverage (episodes per level):
|
| 190 |
+
topology barabasi_albert=1080 erdos_renyi=1080 fat_tree=1080 watts_strogatz=1080 waxman=1080
|
| 191 |
+
size 32=1350 64=1350 128=1350 256=1350
|
| 192 |
+
traffic_profile microburst=1800 poisson=1800 sustained=1800
|
| 193 |
+
load_level heavy=1800 light=1800 moderate=1800
|
| 194 |
+
dynamics_level moderate=1800 severe=1800 static=1800
|
| 195 |
+
split test=1080 train=3240 validation=1080
|
| 196 |
+
cells 540, episodes 5400/5400, per cell 10-10
|
| 197 |
+
|
| 198 |
+
Tables:
|
| 199 |
+
episodes 135 files 5,400 rows 0.03 GB
|
| 200 |
+
events 135 files 43,246 rows 0.00 GB
|
| 201 |
+
router_summary 135 files 32,400 rows 0.00 GB
|
| 202 |
+
flow_summary 135 files 7,672,320 rows 0.19 GB
|
| 203 |
+
flow_telemetry 135 files 259,200,000 rows 0.96 GB
|
| 204 |
+
network_telemetry 135 files 32,400,000 rows 3.69 GB
|
| 205 |
+
link_telemetry 135 files 32,400,000 rows 9.27 GB
|
| 206 |
+
potential_field 135 files 1,501,470 rows 3.48 GB
|
| 207 |
+
total 17.62 GB
|
| 208 |
+
PS C:\Users\g28630518\Documents\SemanticPotentialRoutingTelemetryDataset> python .\scripts\validate_dataset.py
|