| """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
|
|
|
|
|
| @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
|
| src: np.ndarray
|
| dst: np.ndarray
|
| base: np.ndarray
|
| capacity: np.ndarray
|
| latency: np.ndarray
|
| conductance: np.ndarray
|
| indptr: np.ndarray
|
| dir_edge: np.ndarray
|
|
|
| @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
|
| self.pinv = 0.5 * (pinv + pinv.T)
|
| 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]
|
| self.diag_t = self.pinv[t, t]
|
|
|
| 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()
|
|
|
| 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
|
| 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
|
|
|
|
|
| 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)
|
| 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)
|
| 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]
|
| 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)
|
| 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
|
|
|
|
|
| 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))
|
| dist = dijkstra(reverse, directed=True, indices=np.asarray(sinks, np.intp))
|
| starts = g.indptr[:-1]
|
| through = np.take(dist, g.dst, axis=1) + cost
|
| 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)
|
| 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)
|
| self.count = np.add.reduceat(equal.astype(np.int32), starts, axis=1)
|
| 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)]
|
|
|
|
|
| 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)
|
|
|