File size: 9,807 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
"""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      # (E, 2) int16, each row (u, v) with u < v, lexicographically sorted
    capacity: np.ndarray   # (E,) int16 packets/step per direction
    latency: np.ndarray    # (E,) int16 steps
    endpoints: np.ndarray  # (K,) int16 nodes eligible as flow sources and sinks
    node_role: np.ndarray  # (N,) int8, ROLE_* constants
    node_xy: np.ndarray    # (N, 2) float32 coordinates, or shape (0, 2) for non-geometric families


@dataclass(frozen=True)
class TopologyEvent:
    kind: str            # "link_failure" | "node_degradation"
    start: int           # first step the event is active
    end: int             # first step it is no longer active (exclusive)
    edge: int = -1       # index into Topology.edges for a link failure
    node: int = -1       # degraded node
    factor: float = 0.0  # capacity multiplier applied to the degraded node's links


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:  # geometric: closest pair of nodes
            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)))   # Waxman link preference, alpha = 0.15 of the diagonal
        n_edges = round(0.5 * cfg.mean_degree * n)     # fixed edge count: exact mean degree at every size
        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":  # latency proportional to Euclidean distance, spanning latency_range
        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