File size: 10,399 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
"""Read access to a generated dataset.



``Dataset`` opens a data folder (or any folder of shards) and returns tables as pandas

DataFrames; ``Episode`` bundles everything about one episode — the static graph, its event

timeline, the flows, the telemetry of any router — and rebuilds the physical state at any step:

the live graph with the capacities in force and the potential field of any flow, recomputed

exactly with the same engine that generated the data. The example scripts are written against

this API.

"""
from __future__ import annotations

import json
from functools import cached_property
from pathlib import Path
from typing import Dict, List, Optional, Sequence

import numpy as np
import pandas as pd

from .config import SimConfig
from .graph_generator import Topology, TopologyEvent, effective_capacity
from .physics_engine import LiveGraph, PotentialField, currents, live_graph, steepest_next_hops
from .telemetry_logger import read_table, shard_files, table_names

FACTORS = ("topology", "size", "traffic_profile", "load_level", "dynamics_level")


class Dataset:
    def __init__(self, path):
        self.path = Path(path)
        self.config = SimConfig.load(self.path / "config.json")
        manifest = self.path / "manifest.json"
        self.manifest: Optional[Dict] = json.loads(manifest.read_text(encoding="utf-8")) if manifest.exists() else None

    @property
    def tables(self) -> List[str]:
        return [t for t in table_names(self.config.routers) if shard_files(self.path, t)]

    @property
    def routers(self) -> Sequence[str]:
        return self.config.routers

    def table(self, name: str, columns=None, filters=None) -> pd.DataFrame:
        return read_table(self.path, name, columns=columns, filters=filters).to_pandas()

    @cached_property
    def episodes(self) -> pd.DataFrame:
        """The ``episodes`` table indexed by ``episode_id`` (list columns included)."""
        return self.table("episodes").set_index("episode_id").sort_index()

    def summary(self, name: str = "router_summary") -> pd.DataFrame:
        """A summary table joined with the design factors and the split of its episode."""
        keys = list(FACTORS) + ["split", "replicate", "n_nodes", "n_flows", "total_capacity"]
        return self.table(name).join(self.episodes[keys], on="episode_id")

    def episode(self, episode_id: int) -> "Episode":
        return Episode(self, int(episode_id))


class Episode:
    def __init__(self, dataset: Dataset, episode_id: int):
        self.dataset = dataset
        self.id = episode_id
        self.row = dataset.episodes.loc[episode_id]
        self.config = dataset.config
        self.events = dataset.table("events", filters=[("episode_id", "=", episode_id)]).sort_values("start")
        self.n_nodes, self.n_edges = int(self.row.n_nodes), int(self.row.n_edges)
        self.n_flows, self.tracked_flows = int(self.row.n_flows), int(self.row.tracked_flows)
        self.steps, self.field_stride = int(self.row.steps), int(self.row.field_stride)
        self.edges = np.stack([self.row.edge_u, self.row.edge_v], 1).astype(np.int16)
        self.capacity = np.asarray(self.row.capacity, np.int16)
        self.latency = np.asarray(self.row.latency, np.int16)
        self.node_role = np.asarray(self.row.node_role, np.int8)
        self.node_xy = (np.stack([self.row.node_x, self.row.node_y], 1).astype(np.float32)
                        if len(self.row.node_x) else np.zeros((0, 2), np.float32))
        self.source = np.asarray(self.row.flow_source, np.int16)
        self.sink = np.asarray(self.row.flow_sink, np.int16)

    def __repr__(self) -> str:
        cell = "/".join(str(self.row[f]) for f in FACTORS)
        return (f"Episode {self.id} [{cell}] {self.n_nodes} nodes, {self.n_edges} links, "
                f"{self.n_flows} flows, {self.steps} steps, split={self.row.split}")

    @property
    def cell(self) -> Dict[str, object]:
        return {f: self.row[f] for f in FACTORS}

    @cached_property
    def topology(self) -> Topology:
        return Topology(self.n_nodes, self.edges, self.capacity, self.latency,
                        np.flatnonzero(self.node_role == self.node_role.max()).astype(np.int16)
                        if self.node_role.max() > 0 else np.arange(self.n_nodes, dtype=np.int16),
                        self.node_role, self.node_xy)

    @cached_property
    def timeline(self) -> List[TopologyEvent]:
        """The event table as generator objects (link failures resolved to edge indices)."""
        edge_index = {(int(u), int(v)): i for i, (u, v) in enumerate(self.edges)}
        return [TopologyEvent(e.kind, int(e.start), int(e.end),
                              edge=edge_index[(int(e.edge_u), int(e.edge_v))] if e.kind == "link_failure" else -1,
                              node=int(e.node), factor=float(e.factor))
                for e in self.events.itertuples()]

    @cached_property
    def change_steps(self) -> List[int]:
        steps = {0} | {e.start for e in self.timeline} | {e.end for e in self.timeline if e.end < self.steps}
        return sorted(steps)

    def capacity_at(self, step: int) -> np.ndarray:
        """Effective capacity of every link at `step` (0 while failed)."""
        return effective_capacity(self.topology, self.timeline, step)

    def live_graph(self, step: int = 0) -> LiveGraph:
        return live_graph(self.n_nodes, self.edges, self.capacity_at(step), self.latency)

    def capacity_matrix(self, step: int) -> np.ndarray:
        """Dense symmetric N × N matrix of the capacities in force at `step` (the graph state)."""
        cap = self.capacity_at(step)
        matrix = np.zeros((self.n_nodes, self.n_nodes), np.int32)
        matrix[self.edges[:, 0], self.edges[:, 1]] = cap
        matrix[self.edges[:, 1], self.edges[:, 0]] = cap
        return matrix

    def telemetry(self, table: str, router: Optional[str] = None, columns=None) -> pd.DataFrame:
        """Rows of a telemetry table for this episode (and router), sorted by step."""
        filters = [("episode_id", "=", self.id)] + ([("router", "=", router)] if router else [])
        frame = self.dataset.table(table, columns=columns, filters=filters)
        keys = [c for c in ("router", "step", "flow") if c in frame.columns]
        return frame.sort_values(keys).reset_index(drop=True)

    def queue_depth(self, router: str) -> np.ndarray:
        """(steps, n_nodes) buffer occupancy after admission, before forwarding."""
        return np.stack(self.telemetry("network_telemetry", router, ["episode_id", "router", "step", "queue_depth"]).queue_depth)

    def node_dropped(self, router: str) -> np.ndarray:
        return np.stack(self.telemetry("network_telemetry", router, ["episode_id", "router", "step", "node_dropped"]).node_dropped)

    def link_load(self, router: str) -> np.ndarray:
        """(steps, n_edges, 2) packets forwarded per link and direction (u→v, v→u)."""
        frame = self.telemetry("link_telemetry", router)
        return np.stack([np.stack(frame.load_uv), np.stack(frame.load_vu)], axis=2)

    def link_utilisation(self, router: str) -> np.ndarray:
        """(steps, n_edges, 2) load divided by the capacity in force; NaN while a link is failed."""
        load = self.link_load(router).astype(np.float64)
        bounds = np.zeros((self.steps, self.n_edges), np.float64)
        for start, end in zip(self.change_steps, self.change_steps[1:] + [self.steps]):
            bounds[start:end] = self.capacity_at(start)
        with np.errstate(invalid="ignore", divide="ignore"):
            return np.where(bounds[:, :, None] > 0, load / bounds[:, :, None], np.nan)

    @cached_property
    def field_snapshots(self) -> pd.DataFrame:
        return self.telemetry("potential_field")

    def field(self, step: int) -> np.ndarray:
        """Stored potential of the tracked flows at a logged step: (tracked_flows, n_nodes)."""
        row = self.field_snapshots[self.field_snapshots.step == step]
        if row.empty:
            raise KeyError(f"step {step} is not logged; logged steps are multiples of {self.field_stride}")
        return np.asarray(row.potential.iloc[0], np.float64).reshape(self.tracked_flows, self.n_nodes)

    def nearest_logged_step(self, step: int) -> int:
        return int(min(self.field_snapshots.step, key=lambda s: abs(s - step)))

    def solve_field(self, step: int, queue: Optional[np.ndarray] = None, flows: Optional[Sequence[int]] = None) -> np.ndarray:
        """Recompute the potential of any flows at any step from the graph state and queue depths.



        Uses the generator's own engine (grounded Laplacian via the pseudo-inverse); with the

        potential router's queue depths at `step` this reproduces ``field(step)`` to floating-point

        precision. Returns (len(flows), n_nodes); flows default to the tracked ones.

        """
        if queue is None:
            queue = self.queue_depth("potential")[step]
        flows = np.arange(self.tracked_flows) if flows is None else np.asarray(flows)
        cfg = self.config
        field = PotentialField(self.live_graph(step), self.source[flows], self.sink[flows], cfg.source_injection)
        injection = cfg.background_injection / (self.n_nodes - 1) + cfg.congestion_gain * np.asarray(queue, np.float64) / cfg.buffer_size
        return field.solve(injection)

    def next_hops(self, step: int, phi: np.ndarray) -> np.ndarray:
        """Steepest-current next hop of every node for the given potentials (flows, n_nodes); −1 at the sink."""
        g = self.live_graph(step)
        return steepest_next_hops(currents(phi, g), g)

    def descent_path(self, step: int, phi: np.ndarray, source: int, sink: int) -> List[int]:
        """Follow the steepest-current next hops of one potential vector (n_nodes,) from source to sink."""
        hops = self.next_hops(step, np.asarray(phi, np.float64)[None, :])[0]
        node, path = int(source), [int(source)]
        while node != int(sink):
            node = int(hops[node])
            if node < 0 or len(path) > self.n_nodes:
                raise RuntimeError("descent did not reach the sink")
            path.append(node)
        return path