File size: 21,101 Bytes
6fbb45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""Figure gallery for a generated dataset (matplotlib, PNG).



    python examples/visualize.py                                   # every figure from data/ into figures/

    python examples/visualize.py --data data_small --figures potential_field,timeline --episode 12 --step 400



Figures: `topologies` (one graph per family, links scaled by capacity), `benchmark` (loss and

delay per router by offered load, with 95 % bootstrap intervals), `timeline` (one episode step by

step under two routers, with bursts and topology events), `queue_heatmap` (buffer occupancy of

every node over time, same episode, two routers), `link_utilisation` (how often links run near

saturation, per router), `potential_field` (the field of one flow on the graph with the

steepest-current next hops and the descent path), `delays` (flow-level p99 delay and path stretch

per router) and `traffic_profiles` (offered packets of one flow under each profile). Colours

follow one fixed palette: every router keeps its hue in every figure.

"""
import argparse
import sys
from pathlib import Path

import matplotlib
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap, Normalize
from matplotlib.ticker import FuncFormatter, MaxNLocator

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.config import ROUTERS  # noqa: E402
from src.dataset import Dataset, Episode  # noqa: E402
from src.design import LOAD_LEVELS, TRAFFIC_PROFILES  # noqa: E402

matplotlib.use("Agg")

SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"]   # categorical slots 1-6
ROUTER_COLOR = dict(zip(ROUTERS, SERIES))
BLUES = LinearSegmentedColormap.from_list("sequential", ["#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5",
                                                          "#256abf", "#184f95", "#0d366b"])
ACCENT, SURFACE, INK, INK2, MUTED, GRID, ALERT = "#eb6834", "#fcfcfb", "#0b0b0b", "#52514e", "#a09f9a", "#e6e5e1", "#e34948"
FIGURES = ("topologies", "benchmark", "timeline", "queue_heatmap", "link_utilisation",
           "potential_field", "delays", "traffic_profiles")
LABEL = {"potential": "potential", "potential_split": "potential split", "potential_static": "potential static",
         "shortest_path": "shortest path", "ecmp": "ECMP", "adaptive_shortest_path": "adaptive shortest path"}


def style() -> None:
    plt.rcParams.update({
        "figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE,
        "font.size": 9, "axes.titlesize": 10, "axes.labelsize": 9, "axes.titleweight": "medium",
        "text.color": INK, "axes.labelcolor": INK2, "xtick.color": INK2, "ytick.color": INK2,
        "axes.edgecolor": GRID, "axes.spines.top": False, "axes.spines.right": False,
        "axes.grid": True, "grid.color": GRID, "grid.linewidth": 0.6, "axes.axisbelow": True,
        "xtick.major.size": 0, "ytick.major.size": 0, "legend.frameon": False, "legend.fontsize": 8,
        "lines.linewidth": 1.6,
    })


def save(fig, out: Path, name: str, dpi: int) -> None:
    out.mkdir(parents=True, exist_ok=True)
    path = out / f"{name}.png"
    fig.savefig(path, dpi=dpi, bbox_inches="tight")
    plt.close(fig)
    print(f"  wrote {path}")


def bootstrap_ci(values: np.ndarray, rng: np.random.Generator, samples: int = 2000):
    means = rng.choice(values, size=(samples, len(values)), replace=True).mean(axis=1)
    return np.percentile(means, [2.5, 97.5])


def layout(ep: Episode) -> np.ndarray:
    """Node positions: true coordinates (Waxman), tiers (fat-tree) or a seeded spring layout."""
    if len(ep.node_xy):
        return ep.node_xy.astype(float)
    if ep.node_role.max() > 0:
        tier = {1: 3.0, 2: 2.0, 3: 1.0, 4: 0.0}
        pos = np.zeros((ep.n_nodes, 2))
        for role, y in tier.items():
            members = np.flatnonzero(ep.node_role == role)
            pos[members, 0] = (np.arange(len(members)) + 0.5) / len(members)
            pos[members, 1] = y / 3.0
        return pos
    graph = nx.Graph()
    graph.add_nodes_from(range(ep.n_nodes))
    graph.add_edges_from(ep.edges.tolist())
    spring = nx.spring_layout(graph, seed=0)
    return np.array([spring[i] for i in range(ep.n_nodes)])


def draw_links(ax, ep: Episode, pos: np.ndarray, capacity: np.ndarray, base: np.ndarray) -> None:
    live = capacity > 0
    width = 0.3 + 1.7 * base[live] / base.max()
    ax.add_collection(LineCollection(pos[ep.edges[live]], linewidths=width, colors=MUTED, alpha=0.55, zorder=1))
    if (~live).any():
        ax.add_collection(LineCollection(pos[ep.edges[~live]], linewidths=1.0, colors=ALERT,
                                         linestyles=(0, (2, 2)), zorder=1, label="failed link"))


def clean_axes(ax) -> None:
    ax.set_xticks([])
    ax.set_yticks([])
    ax.grid(False)
    for side in ("left", "bottom"):
        ax.spines[side].set_visible(False)
    ax.set_aspect("equal", adjustable="datalim")
    ax.set_box_aspect(1)
    ax.margins(0.05)


def fig_topologies(ds: Dataset, out: Path, dpi: int, **_) -> None:
    episodes = ds.episodes
    picks = episodes.sort_values("n_nodes").groupby("topology", sort=False).head(1)
    fig, axes = plt.subplots(1, len(picks), figsize=(3.4 * len(picks), 3.4))
    for ax, (eid, row) in zip(np.atleast_1d(axes), picks.iterrows()):
        ep = ds.episode(eid)
        pos = layout(ep)
        draw_links(ax, ep, pos, ep.capacity, ep.capacity)
        if ep.node_role.max() > 0:
            colours = [BLUES(0.85 - 0.22 * (r - 1)) for r in ep.node_role]
        else:
            colours = SERIES[0]
        ax.scatter(pos[:, 0], pos[:, 1], s=16, c=colours, edgecolors=SURFACE, linewidths=0.6, zorder=3)
        clean_axes(ax)
        ax.set_title(f"{row.topology.replace('_', ' ')}\n{ep.n_nodes} nodes, {ep.n_edges} links, "
                     f"mean degree {2 * ep.n_edges / ep.n_nodes:.1f}")
    fig.suptitle("Topology families (link width proportional to capacity; fat-tree tiers core to hosts, dark to light)", y=1.02)
    save(fig, out, "topologies", dpi)


def fig_benchmark(ds: Dataset, out: Path, dpi: int, seed: int, **_) -> None:
    summary = ds.summary("router_summary")
    loads = [l for l in LOAD_LEVELS if l in set(summary.load_level)]
    routers = [r for r in ROUTERS if r in set(summary.router)]
    rng = np.random.default_rng(seed)
    metrics = [("loss_ratio", "loss ratio"), ("mean_delay", "mean end-to-end delay (steps)")]
    fig, axes = plt.subplots(len(metrics), len(loads), figsize=(3.6 * len(loads), 2.6 * len(metrics)),
                             sharey=True, squeeze=False)
    for i, (metric, label) in enumerate(metrics):
        for j, load in enumerate(loads):
            ax = axes[i, j]
            sub = summary[summary.load_level == load]
            for k, router in enumerate(routers):
                values = sub[sub.router == router][metric].dropna().to_numpy()
                mean = values.mean()
                lo, hi = bootstrap_ci(values, rng)
                y = len(routers) - 1 - k                                   # first router on top
                ax.barh(y, mean, height=0.72, color=ROUTER_COLOR[router], zorder=2)
                ax.errorbar(mean, y, xerr=[[mean - lo], [hi - mean]], fmt="none", ecolor=INK2, elinewidth=0.8, capsize=2, zorder=3)
            ax.set_yticks(range(len(routers)))
            ax.set_yticklabels([LABEL[r] for r in reversed(routers)])
            ax.grid(axis="y", visible=False)
            if i == 0:
                ax.set_title(f"{load} load ({sub.episode_id.nunique()} episodes)")
            ax.set_xlabel(label)
            ax.set_xlim(left=0)
            ax.xaxis.set_major_locator(MaxNLocator(4))
            if metric == "loss_ratio":
                ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: f"{100 * x:g}%"))
    fig.suptitle("Router benchmark by offered load: mean over episodes with 95 % bootstrap intervals", y=1.01)
    fig.tight_layout()
    save(fig, out, "benchmark", dpi)


def bursting_flows(ep: Episode) -> np.ndarray:
    """Number of tracked flows in the burst state at every step."""
    flows = ep.telemetry("flow_telemetry", ep.dataset.routers[0], ["episode_id", "router", "step", "flow", "mmpp_state"])
    return flows.groupby("step").mmpp_state.sum().reindex(range(ep.steps), fill_value=0).to_numpy()


def shade_bursts(ax, mask: np.ndarray) -> None:
    edges = np.flatnonzero(np.diff(np.r_[0, mask.astype(int), 0]))
    for start, end in zip(edges[::2], edges[1::2]):
        ax.axvspan(start, end, color=INK2, alpha=0.08, linewidth=0, zorder=0)


def mark_events(ax, ep: Episode) -> None:
    for e in ep.events.itertuples():
        ax.axvline(e.start, color=ALERT if e.kind == "link_failure" else MUTED, linewidth=0.8, zorder=1)


def fig_timeline(ds: Dataset, out: Path, dpi: int, episode: int, routers, **_) -> None:
    ep = ds.episode(episode)
    frames = {r: ep.telemetry("network_telemetry", r, ["episode_id", "router", "step", "offered", "delivered",
                                                       "dropped", "queued", "route_changes"]) for r in routers}
    bursts = bursting_flows(ep)
    fig, axes = plt.subplots(5, 1, figsize=(10, 8.2), sharex=True, gridspec_kw={"height_ratios": [1, 3, 3, 3, 3]})
    axes[0].fill_between(np.arange(ep.steps), bursts, step="mid", color=INK2, alpha=0.35, linewidth=0)
    axes[0].set_ylabel(f"tracked flows\nin burst (of {ep.tracked_flows})", fontsize=8)
    axes[0].set_ylim(0, max(1, bursts.max()))
    axes[0].yaxis.set_major_locator(MaxNLocator(integer=True, nbins=3))
    panels = [("delivered", "delivered\n(packets / step)"), ("dropped", "dropped\n(packets / step)"),
              ("queued", "waiting in buffers\n(packets)"), ("route_changes", "next-hop changes\n(per step)")]
    for ax, (column, label) in zip(axes[1:], panels):
        if column == "delivered":
            ax.plot(frames[routers[0]].step, frames[routers[0]].offered, color=MUTED, linewidth=1.0, label="offered")
        for r in routers:
            ax.plot(frames[r].step, frames[r][column], color=ROUTER_COLOR[r], label=LABEL[r])
        ax.set_ylabel(label, fontsize=8)
        ax.set_ylim(bottom=0)
    for ax in axes:
        mark_events(ax, ep)
    axes[4].set_yscale("symlog", linthresh=10)
    axes[4].set_xlabel("step (1 step = 1 ms)")
    axes[1].legend(loc="upper right", ncol=3)
    summary = ep.telemetry("router_summary").set_index("router")
    losses = ", ".join(f"{LABEL[r]} loss {summary.loss_ratio[r]:.1%}" for r in routers)
    fig.suptitle(f"Episode {ep.id} ({'/'.join(str(v) for v in ep.cell.values())}): {losses}\n"
                 f"vertical lines: link failure (red) or node degradation (grey) begins", fontsize=9)
    fig.align_ylabels(axes)
    save(fig, out, "timeline", dpi)


def fig_queue_heatmap(ds: Dataset, out: Path, dpi: int, episode: int, routers, **_) -> None:
    ep = ds.episode(episode)
    queues = {r: ep.queue_depth(r) for r in routers}
    order = np.argsort(-queues[routers[-1]].mean(0))                      # same node order in every panel
    vmax = max(q.max() for q in queues.values())
    fig, axes = plt.subplots(1, len(routers), figsize=(5.2 * len(routers), 4.2), sharey=True)
    summary = ep.telemetry("router_summary").set_index("router")
    for ax, r in zip(np.atleast_1d(axes), routers):
        image = ax.imshow(queues[r][:, order].T, aspect="auto", cmap=BLUES, vmin=0, vmax=vmax,
                          interpolation="nearest", origin="upper")
        ax.set_title(f"{LABEL[r]}: loss {summary.loss_ratio[r]:.1%}, mean occupancy {summary.mean_queue[r]:.1f}")
        ax.set_xlabel("step (1 step = 1 ms)")
        ax.grid(False)
    np.atleast_1d(axes)[0].set_ylabel(f"node rank by mean occupancy under {LABEL[routers[-1]]} (busiest first)")
    fig.colorbar(image, ax=list(np.atleast_1d(axes)), label=f"packets in buffer (capacity {ds.config.buffer_size})", shrink=0.9)
    fig.suptitle(f"Buffer occupancy, episode {ep.id} ({'/'.join(str(v) for v in ep.cell.values())})", y=0.98)
    save(fig, out, "queue_heatmap", dpi)


def fig_link_utilisation(ds: Dataset, out: Path, dpi: int, episode: int, **_) -> None:
    ep = ds.episode(episode)
    fig, ax = plt.subplots(figsize=(6.4, 4))
    grid = np.linspace(0, 1, 101)
    for r in [r for r in ROUTERS if r in ds.routers]:
        util = ep.link_utilisation(r)
        util = util[np.isfinite(util)]
        ccdf = [(util >= x).mean() for x in grid]
        ax.plot(grid, ccdf, color=ROUTER_COLOR[r], label=LABEL[r])
    ax.set_yscale("log")
    ax.set_xlabel("utilisation of a directed link in one step (packets forwarded / capacity in force)")
    ax.set_ylabel("share of link-steps at or above this utilisation")
    ax.set_xlim(0, 1)
    ax.legend(loc="lower left")
    ax.set_title(f"How often links run near saturation, episode {ep.id} ({'/'.join(str(v) for v in ep.cell.values())})")
    save(fig, out, "link_utilisation", dpi)


def fig_potential_field(ds: Dataset, out: Path, dpi: int, episode: int, step: int, flow: int, **_) -> None:
    ep = ds.episode(episode)
    step = ep.nearest_logged_step(step)
    phi = ep.field(step)[flow]
    queue = ep.queue_depth("potential")[step].astype(np.float64)   # int16 telemetry: widen before scaling
    pos = layout(ep)
    source, sink = int(ep.source[flow]), int(ep.sink[flow])
    hops = ep.next_hops(step, phi[None, :])[0]
    path = ep.descent_path(step, phi, source, sink)
    fig, ax = plt.subplots(figsize=(8.5, 7))
    draw_links(ax, ep, pos, ep.capacity_at(step), ep.capacity)
    ax.add_collection(LineCollection(pos[np.stack([path[:-1], path[1:]], 1)], linewidths=3.2, colors=ACCENT,
                                     zorder=2, label="descent path of the flow"))
    valid = hops >= 0
    start, end = pos[valid], pos[hops[valid]]
    thin = min(1.0, (100 / ep.n_nodes) ** 0.5)                              # lighter arrows on large graphs
    ax.quiver(start[:, 0], start[:, 1], (end - start)[:, 0] * 0.55, (end - start)[:, 1] * 0.55,
              angles="xy", scale_units="xy", scale=1, width=0.0035 * thin, color=INK2, alpha=0.8, zorder=2,
              headwidth=5, headlength=6, label="steepest-current next hop")
    norm = Normalize(vmin=0, vmax=phi.max())
    scatter = ax.scatter(pos[:, 0], pos[:, 1], s=18 + 160 * queue / ds.config.buffer_size, c=phi, cmap=BLUES, norm=norm,
                         edgecolors=SURFACE, linewidths=0.8, zorder=3)
    ax.scatter(*pos[source], s=170, marker="s", facecolors="none", edgecolors=ACCENT, linewidths=2, zorder=4, label="source")
    ax.scatter(*pos[sink], s=260, marker="*", facecolors="none", edgecolors=ACCENT, linewidths=2, zorder=4, label="sink")
    clean_axes(ax)
    fig.colorbar(scatter, ax=ax, label="potential of the flow (0 at its sink)", shrink=0.75)
    ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.01), ncol=4, fontsize=8)
    ax.set_title(f"Potential field of tracked flow {flow} ({source} to {sink}), episode {ep.id}, step {step}\n"
                 f"node size: buffer occupancy under the potential router; link width: base capacity")
    save(fig, out, "potential_field", dpi)


def fig_delays(ds: Dataset, out: Path, dpi: int, **_) -> None:
    flows = ds.summary("flow_summary")
    flows = flows[flows.delivered > 0].copy()
    flows["path_stretch"] = flows.mean_hops / flows.min_hops
    routers = [r for r in ROUTERS if r in set(flows.router)]
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
    for ax, (column, label, log) in zip(axes, [("p99_delay", "flow p99 end-to-end delay (steps)", True),
                                               ("path_stretch", "flow path stretch (mean hops / shortest hops)", False)]):
        data = [flows[flows.router == r][column].to_numpy() for r in routers]
        boxes = ax.boxplot(data, vert=False, widths=0.6, showfliers=False, patch_artist=True,
                           medianprops={"color": INK, "linewidth": 1.2},
                           whiskerprops={"color": INK2, "linewidth": 0.8}, capprops={"color": INK2, "linewidth": 0.8})
        for patch, r in zip(boxes["boxes"], routers):
            patch.set(facecolor=ROUTER_COLOR[r], edgecolor=SURFACE, alpha=0.9)
        ax.set_yticks(range(1, len(routers) + 1))
        ax.set_yticklabels([LABEL[r] for r in routers])
        ax.invert_yaxis()
        ax.grid(axis="y", visible=False)
        if log:
            ax.set_xscale("log")
        ax.set_xlabel(label)
    fig.suptitle(f"Flow-level delay and path stretch per router ({flows.episode_id.nunique()} episodes, "
                 f"{len(flows) // len(routers):,} delivered flows each; boxes: quartiles, whiskers: 1.5 IQR)", y=1.02)
    fig.tight_layout()
    save(fig, out, "delays", dpi)


def fig_traffic_profiles(ds: Dataset, out: Path, dpi: int, **_) -> None:
    episodes = ds.episodes
    profiles = [p for p in TRAFFIC_PROFILES if p in set(episodes.traffic_profile)]
    fig, axes = plt.subplots(len(profiles), 1, figsize=(10, 1.9 * len(profiles) + 0.6), sharex=True, squeeze=False)
    order = {"heavy": 0, "moderate": 1, "light": 2}
    for ax, profile in zip(axes[:, 0], profiles):
        candidates = episodes[episodes.traffic_profile == profile]
        eid = candidates.index[np.argsort(candidates.load_level.map(order).to_numpy(), kind="stable")[0]]
        ep = ds.episode(eid)
        f = int(np.argmax(np.asarray(ep.row.flow_mean_rate)[: ep.tracked_flows]))   # largest tracked flow
        flow = ep.telemetry("flow_telemetry", ds.routers[0], ["episode_id", "router", "step", "flow", "offered", "mmpp_state"])
        flow = flow[flow.flow == f]
        shade_bursts(ax, flow.mmpp_state.to_numpy() > 0)
        ax.plot(flow.step, flow.offered, color=SERIES[0], linewidth=1.0)
        ax.set_ylabel("packets / step", fontsize=8)
        ax.set_ylim(bottom=0)
        ax.set_title(f"{profile}: flow {f} of episode {eid} ({ep.row.load_level} load), mean rate "
                     f"{ep.row.flow_mean_rate[f]:.2f} packets/step (idle {ep.row.flow_idle_rate[f]:.2f}, "
                     f"burst {ep.row.flow_burst_rate[f]:.2f})", loc="left")
    axes[-1, 0].set_xlabel("step (1 step = 1 ms)")
    fig.suptitle("Traffic profiles: offered packets of one flow (grey bands: burst state)", y=1.0)
    fig.tight_layout()
    save(fig, out, "traffic_profiles", dpi)


def choose_episode(ds: Dataset) -> int:
    """A busy episode: heaviest load, burstiest profile and most dynamic level present."""
    episodes = ds.episodes.reset_index()
    rank = {"heavy": 0, "moderate": 1, "light": 2}, {"microburst": 0, "sustained": 1, "poisson": 2}, {"severe": 0, "moderate": 1, "static": 2}
    key = (episodes.load_level.map(rank[0]) * 100 + episodes.traffic_profile.map(rank[1]) * 10
           + episodes.dynamics_level.map(rank[2]))
    return int(episodes.episode_id[key.idxmin()])


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--data", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
    parser.add_argument("--out", type=Path, default=ROOT / "figures", help="output folder (default: figures/)")
    parser.add_argument("--figures", default="all", help="comma-separated subset of " + ",".join(FIGURES))
    parser.add_argument("--episode", type=int, default=None, help="episode for the single-episode figures (default: a busy one)")
    parser.add_argument("--step", type=int, default=500, help="step for the potential-field figure")
    parser.add_argument("--flow", type=int, default=0, help="tracked flow for the potential-field figure")
    parser.add_argument("--routers", default="potential,shortest_path", help="two routers for the timeline and heatmap")
    parser.add_argument("--dpi", type=int, default=150)
    parser.add_argument("--seed", type=int, default=0, help="bootstrap seed")
    args = parser.parse_args()

    style()
    ds = Dataset(args.data)
    wanted = FIGURES if args.figures == "all" else tuple(args.figures.split(","))
    unknown = set(wanted) - set(FIGURES)
    assert not unknown, f"unknown figures {unknown}; choose from {FIGURES}"
    routers = tuple(args.routers.split(","))
    assert all(r in ds.routers for r in routers), f"routers must be among {ds.routers}"
    episode = choose_episode(ds) if args.episode is None else args.episode
    print(f"{ds.path}: {len(ds.episodes)} episodes; single-episode figures use episode {episode}")
    for name in wanted:
        globals()[f"fig_{name}"](ds, args.out, args.dpi, seed=args.seed, episode=episode,
                                 step=args.step, flow=args.flow, routers=routers)


if __name__ == "__main__":
    main()