| """Topology families and dynamic-topology timelines.
|
|
|
| Five families span the structures routing research cares about: Barabási–Albert scale-free
|
| graphs (router-level Internet), Watts–Strogatz small worlds, Erdős–Rényi random graphs, Waxman
|
| geometric graphs (ISP-like, with distance-proportional latencies and node coordinates) and k-ary
|
| fat-trees (data-centre fabrics whose hosts are the only traffic endpoints; host links carry twice
|
| the fabric capacity, i.e. a 2:1 oversubscribed edge, so bursts contend inside the fabric). Random families are
|
| generated at a common mean degree so that size is the only structural factor that changes with
|
| the nominal network size; any rare disconnected sample is stitched into one component instead of
|
| being resampled, so the node count is always exactly the nominal one.
|
|
|
| A pre-sampled timeline of link failures and node degradations makes the graph time-varying.
|
| Failures are drawn only from non-bridge links of the currently live graph, so the network never
|
| partitions and traffic can always be routed around the damage.
|
| """
|
| from __future__ import annotations
|
|
|
| from dataclasses import dataclass
|
| from typing import List, Tuple
|
|
|
| import networkx as nx
|
| import numpy as np
|
|
|
| from .config import SimConfig
|
| from .design import Cell, Dynamics
|
|
|
| ROLE_ROUTER, ROLE_CORE, ROLE_AGGREGATION, ROLE_EDGE, ROLE_HOST = 0, 1, 2, 3, 4
|
|
|
|
|
| @dataclass(frozen=True)
|
| class Topology:
|
| n_nodes: int
|
| edges: np.ndarray
|
| capacity: np.ndarray
|
| latency: np.ndarray
|
| endpoints: np.ndarray
|
| node_role: np.ndarray
|
| node_xy: np.ndarray
|
|
|
|
|
| @dataclass(frozen=True)
|
| class TopologyEvent:
|
| kind: str
|
| start: int
|
| end: int
|
| edge: int = -1
|
| node: int = -1
|
| factor: float = 0.0
|
|
|
|
|
| def _stitch(graph: nx.Graph, xy: np.ndarray = None, rng: np.random.Generator = None) -> None:
|
| """Connect a disconnected graph by joining every component to the largest one (rare)."""
|
| components = sorted(nx.connected_components(graph), key=len, reverse=True)
|
| main = np.array(sorted(components[0]))
|
| for comp in components[1:]:
|
| comp = np.array(sorted(comp))
|
| if xy is not None:
|
| d = np.linalg.norm(xy[comp][:, None, :] - xy[main][None, :, :], axis=2)
|
| a, b = np.unravel_index(int(d.argmin()), d.shape)
|
| graph.add_edge(int(comp[a]), int(main[b]))
|
| else:
|
| graph.add_edge(int(rng.choice(comp)), int(rng.choice(main)))
|
| main = np.concatenate([main, comp])
|
|
|
|
|
| def _random_family(cfg: SimConfig, family: str, n: int, rng: np.random.Generator):
|
| seed = int(rng.integers(2**31 - 1))
|
| xy = np.zeros((0, 2), np.float32)
|
| if family == "barabasi_albert":
|
| graph = nx.barabasi_albert_graph(n, cfg.mean_degree // 2, seed=seed)
|
| elif family == "watts_strogatz":
|
| graph = nx.connected_watts_strogatz_graph(n, cfg.mean_degree, 0.1, tries=1000, seed=seed)
|
| elif family == "erdos_renyi":
|
| graph = nx.gnp_random_graph(n, cfg.mean_degree / (n - 1), seed=seed)
|
| _stitch(graph, rng=rng)
|
| elif family == "waxman":
|
| xy = rng.random((n, 2)).astype(np.float32)
|
| iu, iv = np.triu_indices(n, 1)
|
| d = np.linalg.norm(xy[iu] - xy[iv], axis=1)
|
| kernel = np.exp(-d / (0.15 * np.sqrt(2.0)))
|
| n_edges = round(0.5 * cfg.mean_degree * n)
|
| chosen = rng.choice(len(iu), n_edges, replace=False, p=kernel / kernel.sum())
|
| graph = nx.Graph()
|
| graph.add_nodes_from(range(n))
|
| graph.add_edges_from(zip(iu[chosen].tolist(), iv[chosen].tolist()))
|
| _stitch(graph, xy=xy)
|
| else:
|
| raise ValueError(family)
|
| edges = np.sort(np.array(graph.edges(), dtype=np.int16), axis=1)
|
| edges = edges[np.lexsort((edges[:, 1], edges[:, 0]))]
|
| lo, hi = cfg.capacity_range
|
| capacity = rng.integers(lo, hi + 1, len(edges)).astype(np.int16)
|
| if family == "waxman":
|
| lo_l, hi_l = cfg.latency_range
|
| dist = np.linalg.norm(xy[edges[:, 0]] - xy[edges[:, 1]], axis=1) / np.sqrt(2.0)
|
| latency = np.round(lo_l + (hi_l - lo_l) * dist).astype(np.int16)
|
| else:
|
| lo_l, hi_l = cfg.latency_range
|
| latency = rng.integers(lo_l, hi_l + 1, len(edges)).astype(np.int16)
|
| return Topology(n, edges, capacity, latency, np.arange(n, dtype=np.int16),
|
| np.zeros(n, np.int8), xy)
|
|
|
|
|
| def fat_tree_k(nominal_size: int) -> int:
|
| """Fat-tree arity for a nominal size: k = 4, 6, 8, 10 give 36, 99, 208, 375 nodes."""
|
| return {32: 4, 64: 6, 128: 8, 256: 10}.get(nominal_size, 2 * max(2, round((nominal_size / 4) ** (1 / 3))))
|
|
|
|
|
| def _fat_tree(cfg: SimConfig, nominal_size: int) -> Topology:
|
| k = fat_tree_k(nominal_size)
|
| half = k // 2
|
| n_core = half * half
|
|
|
| def core(i, j):
|
| return i * half + j
|
|
|
| def agg(pod, i):
|
| return n_core + pod * k + i
|
|
|
| def edge(pod, i):
|
| return n_core + pod * k + half + i
|
|
|
| def host(pod, i, h):
|
| return n_core + k * k + (pod * half + i) * half + h
|
|
|
| links = []
|
| for pod in range(k):
|
| for i in range(half):
|
| for j in range(half):
|
| links.append((core(i, j), agg(pod, i)))
|
| links.append((agg(pod, i), edge(pod, j)))
|
| for h in range(half):
|
| links.append((edge(pod, i), host(pod, i, h)))
|
| n = n_core + k * k + k * half * half
|
| edges = np.sort(np.array(links, dtype=np.int16), axis=1)
|
| edges = edges[np.lexsort((edges[:, 1], edges[:, 0]))]
|
| role = np.full(n, ROLE_HOST, np.int8)
|
| role[:n_core] = ROLE_CORE
|
| for pod in range(k):
|
| role[agg(pod, 0):agg(pod, 0) + half] = ROLE_AGGREGATION
|
| role[edge(pod, 0):edge(pod, 0) + half] = ROLE_EDGE
|
| hosts = np.flatnonzero(role == ROLE_HOST).astype(np.int16)
|
| host_link = (role[edges[:, 0]] == ROLE_HOST) | (role[edges[:, 1]] == ROLE_HOST)
|
| capacity = np.where(host_link, 2 * cfg.fat_tree_capacity, cfg.fat_tree_capacity).astype(np.int16)
|
| return Topology(n, edges, capacity, np.ones(len(edges), np.int16), hosts, role, np.zeros((0, 2), np.float32))
|
|
|
|
|
| def generate_topology(cfg: SimConfig, cell: Cell, rng: np.random.Generator) -> Topology:
|
| if cell.topology == "fat_tree":
|
| return _fat_tree(cfg, cell.size)
|
| return _random_family(cfg, cell.topology, cell.size, rng)
|
|
|
|
|
| def effective_capacity(topo: Topology, events: List[TopologyEvent], step: int) -> np.ndarray:
|
| """Per-link capacity in force at `step`: base × degradation factors of both endpoints, 0 if failed."""
|
| failed = np.zeros(len(topo.edges), bool)
|
| factor = np.ones(topo.n_nodes)
|
| for ev in events:
|
| if ev.start <= step < ev.end:
|
| if ev.kind == "link_failure":
|
| failed[ev.edge] = True
|
| else:
|
| factor[ev.node] *= ev.factor
|
| u, v = topo.edges.T
|
| cap = np.maximum(1, np.floor(topo.capacity * factor[u] * factor[v])).astype(np.int16)
|
| cap[failed] = 0
|
| return cap
|
|
|
|
|
| def generate_timeline(cfg: SimConfig, topo: Topology, dyn: Dynamics, rng: np.random.Generator
|
| ) -> Tuple[List[TopologyEvent], List[Tuple[int, np.ndarray]]]:
|
| """Pre-sample every topology event of an episode.
|
|
|
| Returns ``(events, changes)`` where ``changes`` lists the ``(step, effective_capacity)`` pairs
|
| at which link capacities change, starting with ``(0, base capacities)``.
|
| """
|
| fail_at = rng.random(cfg.steps) < dyn.link_failure_rate
|
| degrade_at = rng.random(cfg.steps) < dyn.node_degradation_rate
|
| lo_d, hi_d = dyn.duration_range
|
| lo_f, hi_f = dyn.factor_range
|
| events: List[TopologyEvent] = []
|
| all_edges = [tuple(e) for e in topo.edges.tolist()]
|
|
|
| for t in range(cfg.steps):
|
| if fail_at[t]:
|
| down = {ev.edge for ev in events if ev.kind == "link_failure" and ev.start <= t < ev.end}
|
| live = nx.Graph()
|
| live.add_nodes_from(range(topo.n_nodes))
|
| live.add_edges_from(e for i, e in enumerate(all_edges) if i not in down)
|
| bridges = {tuple(sorted(b)) for b in nx.bridges(live)}
|
| candidates = [i for i, e in enumerate(all_edges) if i not in down and e not in bridges]
|
| if candidates:
|
| end = min(t + int(rng.integers(lo_d, hi_d + 1)), cfg.steps)
|
| events.append(TopologyEvent("link_failure", t, end, edge=int(rng.choice(candidates))))
|
| if degrade_at[t]:
|
| end = min(t + int(rng.integers(lo_d, hi_d + 1)), cfg.steps)
|
| events.append(TopologyEvent("node_degradation", t, end,
|
| node=int(rng.integers(topo.n_nodes)),
|
| factor=float(rng.uniform(lo_f, hi_f))))
|
|
|
| steps = {0} | {ev.start for ev in events} | {ev.end for ev in events if ev.end < cfg.steps}
|
| changes = [(t, effective_capacity(topo, events, t)) for t in sorted(steps)]
|
| return events, changes
|
|
|