File size: 5,945 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 | """Walk through one episode with the ``Dataset`` API and check it against the physics.
python examples/inspect_episode.py # episode 0 of data/
python examples/inspect_episode.py --data data_small --episode 7 --step 500 --router potential
Prints the design cell, the graph, the flows, the event timeline and the router summary; then,
at one step, the capacities in force, the busiest buffers and links; recomputes the potential
field of the tracked flows from the graph state and queue depths and compares it with the stored
snapshot; and follows the steepest-current descent of a tracked flow from its source to its sink.
Every comparison is asserted, so the script is also a test of the relational tables.
"""
import argparse
import sys
from pathlib import Path
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from src.dataset import Dataset # noqa: E402
from src.physics_engine import grounded_solve # noqa: E402
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("--episode", type=int, default=0)
parser.add_argument("--step", type=int, default=500, help="step to inspect (snapped to a logged field step)")
parser.add_argument("--router", default="potential", help="router whose telemetry is shown")
args = parser.parse_args()
pd.set_option("display.width", 160)
ds = Dataset(args.data)
ep = ds.episode(args.episode)
print(ep)
degree = np.bincount(ep.edges.ravel(), minlength=ep.n_nodes)
print(f" degree min/mean/max {degree.min()}/{degree.mean():.2f}/{degree.max()}, "
f"capacity {ep.capacity.min()}-{ep.capacity.max()} pkt/step, latency {ep.latency.min()}-{ep.latency.max()} steps, "
f"total directed capacity {ep.row.total_capacity:.0f} pkt/step")
rates = np.asarray(ep.row.flow_mean_rate)
print(f" flows: {ep.n_flows} between {len(ep.topology.endpoints)} endpoints, offered load rho = {ep.row.offered_load:.3f}, "
f"mean rate min/median/max {rates.min():.2f}/{np.median(rates):.2f}/{rates.max():.2f} pkt/step, "
f"tracked flows {ep.tracked_flows}, field stride {ep.field_stride}")
print(f"\nTopology events ({len(ep.events)}):")
if len(ep.events):
print(ep.events[["kind", "start", "end", "node", "edge_u", "edge_v", "factor"]].to_string(index=False))
else:
print(" none (static dynamics level)")
print("\nRouter summary:")
summary = ep.telemetry("router_summary").set_index("router")
print(summary[["loss_ratio", "mean_delay", "p99_delay", "mean_queue", "max_queue",
"link_utilisation", "link_saturation", "route_changes"]].to_string())
flows = ep.telemetry("flow_summary")
assert (flows.offered == flows.delivered + flows.dropped + flows.in_flight).all()
print(" [ok] packet conservation holds for every flow and router")
step = ep.nearest_logged_step(args.step)
cap = ep.capacity_at(step)
failed, degraded = int((cap == 0).sum()), int((cap < ep.capacity).sum() - (cap == 0).sum())
print(f"\nStep {step} (nearest logged field step to {args.step}): {failed} failed links, "
f"{degraded} links with reduced capacity, {len(ep.live_graph(step).src) // 2} live links")
queue = ep.queue_depth(args.router)[step]
busiest = np.argsort(-queue)[:5]
print(f" busiest buffers under {args.router}: " + ", ".join(f"node {i}: {queue[i]}" for i in busiest))
util = ep.link_utilisation(args.router)[step]
flat = np.nan_to_num(util, nan=-1).ravel()
top = np.argsort(-flat)[:5]
print(" most utilised directed links: " + ", ".join(
f"{ep.edges[k // 2, k % 2]}->{ep.edges[k // 2, 1 - k % 2]}: {flat[k]:.0%}" for k in top))
stored = ep.field(step)
queue_potential = ep.queue_depth("potential")[step] # the field responds to its own router's buffers
recomputed = ep.solve_field(step, queue_potential)
rel = np.abs(recomputed - stored).max() / np.abs(stored).max()
assert rel < 1e-5, rel
print(f" [ok] potential field of the {ep.tracked_flows} tracked flows recomputed from graph state + queues "
f"(max relative deviation from the stored float32 snapshot {rel:.1e})")
g = ep.live_graph(step)
b = (ep.config.background_injection / (ep.n_nodes - 1)
+ ep.config.congestion_gain * queue_potential.astype(np.float64) / ep.config.buffer_size)
b[ep.source[0]] += ep.config.source_injection
reference = grounded_solve(g, int(ep.sink[0]), b)
assert np.abs(reference - recomputed[0]).max() < 1e-9 * max(1.0, np.abs(reference).max())
print(" [ok] pseudo-inverse solution agrees with the sparse SuperLU solve for flow 0")
s, t = int(ep.source[0]), int(ep.sink[0])
path = ep.descent_path(step, recomputed[0], s, t)
phi = recomputed[0][path]
assert path[0] == s and path[-1] == t and np.all(np.diff(phi) < 0) and len(path) <= ep.n_nodes
print(f" [ok] steepest-current descent of flow 0 reaches its sink: {' -> '.join(map(str, path))} "
f"({len(path) - 1} hops, shortest possible {int(flows.min_hops.iloc[0])}); potentials "
+ " > ".join(f"{p:.4f}" for p in phi))
tracked = flows[(flows.router == args.router) & (flows.flow < ep.tracked_flows)]
print(f"\nTracked flows under {args.router}:")
print(tracked[["flow", "source", "sink", "mean_rate", "min_hops", "offered", "delivered", "dropped",
"loss_ratio", "mean_delay", "mean_queueing_delay", "mean_hops", "route_changes"]].to_string(index=False))
print("\nAll checks passed.")
if __name__ == "__main__":
main()
|