File size: 12,345 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
"""Training-free potential-field routing on the graph Laplacian, and the classical baselines.



For flow *f* with source *s* and sink *t* the potential φ solves the discrete Poisson equation



    L_g φ = b,      L = D − W,      w_ij = capacity_ij / latency_ij   (live links only)



where L_g is the Laplacian with the sink's row and column removed, i.e. the Dirichlet boundary

condition φ_t = 0: the sink is the grounded, attractive well of the field. The right-hand side

injects a unit current at the source, a small positive background at every node and a repulsive

current proportional to each node's buffer occupancy.



The grounded inverse is available in closed form from the Laplacian pseudo-inverse L⁺:

(L_g⁻¹)_ij = L⁺_ij − L⁺_it − L⁺_tj + L⁺_tt. Because the background and congestion injections are

the same for every flow, the fields of all F flows follow from one matrix–vector product with L⁺

plus O(N) work per flow, so L⁺ is formed once per topology change (dense, N ≤ 375) and every step

costs O(N·F) instead of F sparse solves. ``grounded_solve`` keeps the sparse SuperLU reference

solution for validation.



Packets follow the routing gradient. On every live directed link the current is

I_ij = w_ij (φ_i − φ_j); the *steepest* rule forwards along the largest current out of a node and

the *split* rule sprays packets over the outgoing links in proportion to their positive currents,

exactly how electrical current divides. Because b_i > 0 at every non-sink node, Σ_j I_ij = b_i > 0,

so at least one current is positive and every positive-current link leads strictly downhill:

both rules are loop-free and reach the sink in at most N − 1 hops for any congestion pattern.



The baselines — static shortest path, equal-cost multipath and queue-aware adaptive shortest

path — share one Dijkstra helper (``scipy.sparse.csgraph.dijkstra`` on the reversed graph, whose

predecessor tree is exactly the next-hop table towards each sink).

"""
from __future__ import annotations

from dataclasses import dataclass

import numpy as np
import scipy.sparse as sp
from scipy.sparse.csgraph import dijkstra, laplacian
from scipy.sparse.linalg import splu

GOLDEN = 0.6180339887498949  # low-discrepancy per-packet coordinate for multipath spraying


@dataclass(frozen=True)
class LiveGraph:
    """Directed view of the links with positive capacity at one point in time, sorted by tail node."""
    n: int
    n_edges: int               # E of the base topology
    src: np.ndarray            # (M,) int32 tail of every live directed link
    dst: np.ndarray            # (M,) int32 head
    base: np.ndarray           # (M,) int32 index into the 2E directed base links: edge + E * direction
    capacity: np.ndarray       # (M,) int32
    latency: np.ndarray        # (M,) int32
    conductance: np.ndarray    # (M,) float64
    indptr: np.ndarray         # (n + 1,) segment boundaries of each tail node
    dir_edge: np.ndarray       # (n, n) int32 live directed link index, −1 where there is none

    @property
    def degree(self) -> np.ndarray:
        return np.diff(self.indptr)

    @property
    def max_degree(self) -> int:
        return int(self.degree.max())

    def laplacian(self) -> np.ndarray:
        weights = sp.csr_matrix((self.conductance, (self.src, self.dst)), shape=(self.n, self.n))
        return laplacian(weights).toarray()


def live_graph(n: int, edges: np.ndarray, capacity: np.ndarray, latency: np.ndarray) -> LiveGraph:
    n_edges = len(edges)
    live = np.flatnonzero(capacity > 0)
    u, v = edges[live, 0].astype(np.int32), edges[live, 1].astype(np.int32)
    src = np.concatenate([u, v])
    dst = np.concatenate([v, u])
    base = np.concatenate([live, live + n_edges]).astype(np.int32)
    order = np.lexsort((dst, src))
    src, dst, base = src[order], dst[order], base[order]
    cap = capacity[base % n_edges].astype(np.int32)
    lat = latency[base % n_edges].astype(np.int32)
    indptr = np.searchsorted(src, np.arange(n + 1))
    dir_edge = np.full((n, n), -1, np.int32)
    dir_edge[src, dst] = np.arange(len(src))
    return LiveGraph(n, n_edges, src, dst, base, cap, lat, cap / lat, indptr, dir_edge)


class PotentialField:
    """Grounded-Laplacian Green's functions of every flow, from one dense pseudo-inverse."""

    def __init__(self, g: LiveGraph, sources: np.ndarray, sinks: np.ndarray, source_injection: float):
        n = g.n
        pinv = np.linalg.inv(g.laplacian() + 1.0 / n) - 1.0 / n        # L⁺ = (L + J/N)⁻¹ − J/N
        self.pinv = 0.5 * (pinv + pinv.T)                                # exactly symmetric, like L⁺ itself
        self.sinks = np.asarray(sinks, np.intp)
        self.flow_ids = np.arange(len(self.sinks))
        s, t = np.asarray(sources, np.intp), self.sinks
        self.row_t = self.pinv[t]                                        # (F, N) rows L⁺_t·
        self.diag_t = self.pinv[t, t]                                    # (F,)
        # Response to the unit source injection, G^(t) e_s, zero at the sink by construction.
        self.source_term = source_injection * (self.pinv[s] - self.row_t
                                               - self.pinv[t, s][:, None] + self.diag_t[:, None])

    def solve(self, injection: np.ndarray) -> np.ndarray:
        """Per-node injection shared by all flows (N,) → potentials φ (F, N) with φ[f, sink_f] = 0."""
        p = self.pinv @ injection
        total = injection.sum()
        # (G^(t) c)_i = p_i − L⁺_it·Σc − (p_t − L⁺_tt·Σc); the injection at the grounded sink cancels.
        phi = p[None, :] - self.row_t * total - (p[self.sinks] - self.diag_t * total)[:, None] + self.source_term
        phi[self.flow_ids, self.sinks] = 0.0                            # exact ground, free of rounding residue
        return phi


def grounded_solve(g: LiveGraph, sink: int, b: np.ndarray) -> np.ndarray:
    """Reference sparse solution of L_g φ = b for one sink (SuperLU); used for validation."""
    keep = np.delete(np.arange(g.n), sink)
    lap = sp.csr_matrix(g.laplacian())
    phi = np.zeros(g.n)
    phi[keep] = splu(lap[keep][:, keep].tocsc()).solve(b[keep])
    return phi


def currents(phi: np.ndarray, g: LiveGraph) -> np.ndarray:
    """I_ij = w_ij (φ_i − φ_j) on every live directed link, shape (F, M)."""
    return (np.take(phi, g.src, axis=1) - np.take(phi, g.dst, axis=1)) * g.conductance


TIE_TOLERANCE = 1e-9  # currents within this relative margin of a node's largest current count as tied


def steepest_next_hops(cur: np.ndarray, g: LiveGraph) -> np.ndarray:
    """Next hop per (flow, node): the link carrying the largest current; −1 if none is positive.



    Symmetric topologies produce mathematically equal currents on parallel links; ties are resolved

    towards the first link in tail-node order within a relative tolerance far above rounding noise,

    so the choice does not depend on the last bits of the linear algebra on a given platform.

    """
    starts = g.indptr[:-1]
    best = np.maximum.reduceat(cur, starts, axis=1)                                # (F, N)
    tied = cur >= np.take(best, g.src, axis=1) * (1.0 - TIE_TOLERANCE)
    first = np.where(tied, np.arange(len(g.src)), len(g.src))
    k = np.minimum.reduceat(first, starts, axis=1)                                 # (F, N)
    return np.where(best > 0, g.dst[np.minimum(k, len(g.src) - 1)], -1).astype(np.int16)


def spray_next_hops(cur: np.ndarray, g: LiveGraph, node: np.ndarray, flow: np.ndarray,

                    packet_id: np.ndarray) -> np.ndarray:
    """Per-packet next hop drawn in proportion to the positive currents leaving the packet's node.



    Packets are grouped by (flow, node); each group's outgoing shares form a cumulative

    distribution, all groups are laid out as one monotone array (group index doubled plus CDF),

    and every packet's low-discrepancy coordinate is placed with a single ``searchsorted``.

    """
    key = flow.astype(np.int64) * g.n + node
    order = np.argsort(key, kind="stable")
    sorted_key = key[order]
    starts = np.flatnonzero(np.r_[True, sorted_key[1:] != sorted_key[:-1]])
    group = np.repeat(np.arange(len(starts)), np.diff(np.r_[starts, len(order)]))
    g_flow, g_node = flow[order][starts].astype(np.int64), node[order][starts].astype(np.int64)
    degree = g.degree[g_node]
    width = int(degree.max())
    slot = np.arange(width)
    valid = slot[None, :] < degree[:, None]                                         # (G, width)
    link = np.minimum(g.indptr[g_node][:, None] + slot[None, :], len(g.src) - 1)
    share = np.where(valid, np.maximum(cur[g_flow[:, None], link], 0.0), 0.0)
    cdf = np.cumsum(share, axis=1)
    total = cdf[:, -1]
    ok = total > 0
    cdf = np.where(valid & ok[:, None], cdf / np.where(ok, total, 1.0)[:, None], 1.0)  # exact 1.0 at the last link
    augmented = (cdf + 2.0 * np.arange(len(starts))[:, None]).ravel()
    u = (packet_id[order] * GOLDEN) % 1.0
    pick = np.searchsorted(augmented, 2.0 * group + u, side="right") - group * width
    hop = np.where(ok[group], g.dst[g.indptr[g_node[group]] + pick], -1)
    out = np.empty(len(order), np.int16)
    out[order] = hop
    return out


COST_QUANTUM = 1e-6  # adaptive link costs are rounded to this many steps so that path sums are exact integers


def dijkstra_next_hops(cost: np.ndarray, g: LiveGraph, sinks: np.ndarray):
    """Shortest paths to each sink under per-directed-link costs: (next_hop (D, N), dist (D, N)).



    Costs must be integer-valued floats (latencies, or quantised adaptive costs) so that every

    path sum is exact. Distances then do not depend on the solver's tie-breaking, and the next hop

    is derived from them here — the first link, in tail-node order, that lies on a shortest path —

    which keeps the tables identical across SciPy versions and platforms.

    """
    reverse = sp.csr_matrix((cost, (g.dst, g.src)), shape=(g.n, g.n))  # reverse[j, i] = cost(i → j)
    dist = dijkstra(reverse, directed=True, indices=np.asarray(sinks, np.intp))
    starts = g.indptr[:-1]
    through = np.take(dist, g.dst, axis=1) + cost                                # (D, M)
    first = np.where(through == np.take(dist, g.src, axis=1), np.arange(len(g.src)), len(g.src))
    k = np.minimum.reduceat(first, starts, axis=1)                                # (D, N)
    next_hop = g.dst[np.minimum(k, len(g.src) - 1)].astype(np.int16)
    next_hop[np.arange(len(sinks)), np.asarray(sinks, np.intp)] = -1
    return next_hop, dist


class EcmpTable:
    """All equal-latency next hops per (sink, node); packets are sprayed round-robin over them."""

    def __init__(self, dist: np.ndarray, g: LiveGraph):
        starts = g.indptr[:-1]
        equal = np.take(dist, g.dst, axis=1) + g.latency == np.take(dist, g.src, axis=1)   # (D, M)
        self.count = np.add.reduceat(equal.astype(np.int32), starts, axis=1)             # (D, N)
        csum = np.cumsum(equal, axis=1)
        pos = csum - np.take(csum[:, starts] - equal[:, starts], g.src, axis=1) - 1
        self.table = np.full((dist.shape[0], g.n, g.max_degree), -1, np.int16)
        rows, cols = np.nonzero(equal)
        self.table[rows, g.src[cols], pos[rows, cols]] = g.dst[cols]

    def hops(self, sink_index: np.ndarray, node: np.ndarray, packet_id: np.ndarray) -> np.ndarray:
        count = self.count[sink_index, node]
        return self.table[sink_index, node, packet_id % np.maximum(count, 1)]  # −1 where count is 0


def path_metrics(g: LiveGraph, sources: np.ndarray, sinks: np.ndarray):
    """Minimum hop count and minimum latency from every flow's source to its sink."""
    origins, index = np.unique(np.asarray(sources, np.intp), return_inverse=True)
    hops = dijkstra(sp.csr_matrix((np.ones(len(g.src)), (g.src, g.dst)), shape=(g.n, g.n)),
                    directed=True, indices=origins)
    lat = dijkstra(sp.csr_matrix((g.latency.astype(np.float64), (g.src, g.dst)), shape=(g.n, g.n)),
                   directed=True, indices=origins)
    return hops[index, sinks].astype(np.int16), lat[index, sinks].astype(np.int16)