File size: 7,870 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
"""Forecast near-term packet loss from step-level telemetry: a learning example on the splits.



    python examples/forecast_congestion.py                             # data/, potential router

    python examples/forecast_congestion.py --router shortest_path --window 20 --horizon 20 --stride 10



Task: at step t, predict the network's loss ratio over the next `horizon` steps (dropped / offered)

from the last `window` steps of the network totals in ``network_telemetry`` (offered, delivered,

dropped, queued, in transit), normalised by the episode's total capacity so that networks of

different sizes share one feature scale, plus the recent loss ratio itself. A ridge regression (closed form, NumPy only) is fitted

on the train split, its penalty chosen on the validation split, and reported on the test split

against a persistence baseline (the loss ratio of the preceding `horizon` steps). The script

asserts that the splits are disjoint by episode and that no feature is undefined.

"""
import argparse
import sys
from pathlib import Path

import numpy as np
import pandas as pd
from numpy.lib.stride_tricks import sliding_window_view

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.dataset import Dataset  # noqa: E402

CHANNELS = ("offered", "delivered", "dropped", "queued", "in_transit")


def windows(frame: pd.DataFrame, capacity: float, n_nodes: int, window: int, horizon: int, stride: int):
    """Feature matrix, target, baseline and step index for one episode's step series."""
    series = frame[list(CHANNELS)].to_numpy(np.float64)
    steps = len(series)
    t = np.arange(max(window, horizon), steps - horizon + 1, stride)
    if len(t) == 0:
        return None
    past = sliding_window_view(series, window, axis=0)[t - window]                # (samples, channels, window)
    future = sliding_window_view(series[:, :3], horizon, axis=0)[t]                # offered, delivered, dropped
    offered_next, dropped_next = future[:, 0].sum(1), future[:, 2].sum(1)
    recent = sliding_window_view(series[:, :3], horizon, axis=0)[t - horizon]
    keep = offered_next > 0                                                         # loss ratio well defined
    with np.errstate(invalid="ignore", divide="ignore"):
        baseline = np.where(recent[:, 0].sum(1) > 0, recent[:, 2].sum(1) / recent[:, 0].sum(1), 0.0)
    features = np.concatenate([past.reshape(len(t), -1) / capacity, baseline[:, None],
                               np.full((len(t), 1), np.log10(n_nodes))], axis=1)
    target = dropped_next / np.maximum(offered_next, 1)
    return features[keep], target[keep], baseline[keep], t[keep]


def ridge_fit(x: np.ndarray, y: np.ndarray, lam: float) -> np.ndarray:
    n, d = x.shape
    return np.linalg.solve(x.T @ x / n + lam * np.eye(d), x.T @ y / n)


def metrics(y: np.ndarray, pred: np.ndarray) -> dict:
    pred = np.clip(pred, 0.0, 1.0)
    sse = np.sum((y - pred) ** 2)
    return {"MAE": np.mean(np.abs(y - pred)), "RMSE": np.sqrt(sse / len(y)),
            "R2": 1.0 - sse / max(np.sum((y - y.mean()) ** 2), 1e-12)}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--data", type=Path, default=ROOT / "data", help="dataset folder (default: data/)")
    parser.add_argument("--router", default="potential")
    parser.add_argument("--window", type=int, default=10, help="steps of history used as features")
    parser.add_argument("--horizon", type=int, default=10, help="steps ahead over which loss is predicted")
    parser.add_argument("--stride", type=int, default=5, help="steps between consecutive samples")
    parser.add_argument("--max-episodes", type=int, default=0, help="cap on episodes (0 = all)")
    args = parser.parse_args()
    pd.set_option("display.width", 160)
    pd.set_option("display.precision", 4)

    ds = Dataset(args.data)
    episodes = ds.episodes
    if args.max_episodes:
        episodes = episodes.iloc[: args.max_episodes]
    if episodes.split.nunique() < 3:   # fewer than five replicates: fall back to a split by episode id
        fallback = np.array(["train", "train", "train", "validation", "test"])[episodes.index % 5]
        episodes = episodes.assign(split=fallback)
        print("note: the dataset has no validation/test replicates; splitting by episode id modulo 5 instead")
    net = ds.table("network_telemetry", columns=["episode_id", "step"] + list(CHANNELS),
                   filters=[("router", "=", args.router)])
    net = net[net.episode_id.isin(episodes.index)].sort_values(["episode_id", "step"])

    parts = {"train": [], "validation": [], "test": []}
    seen = {s: set() for s in parts}
    for eid, frame in net.groupby("episode_id", sort=False):
        row = episodes.loc[eid]
        sample = windows(frame, float(row.total_capacity), int(row.n_nodes), args.window, args.horizon, args.stride)
        if sample is not None:
            parts[row.split].append((eid, *sample))
            seen[row.split].add(eid)
    assert not (seen["train"] & seen["test"]) and not (seen["train"] & seen["validation"]), "splits overlap"
    assert all(parts.values()), "every split needs episodes: " + ", ".join(f"{k} {len(v)}" for k, v in parts.items())

    def stack(split):
        x = np.concatenate([p[1] for p in parts[split]])
        y = np.concatenate([p[2] for p in parts[split]])
        b = np.concatenate([p[3] for p in parts[split]])
        eids = np.concatenate([np.full(len(p[2]), p[0]) for p in parts[split]])
        return x, y, b, eids

    x_tr, y_tr, _, _ = stack("train")
    x_va, y_va, b_va, _ = stack("validation")
    x_te, y_te, b_te, e_te = stack("test")
    assert np.isfinite(x_tr).all() and np.isfinite(x_va).all() and np.isfinite(x_te).all()
    mean, std = x_tr.mean(0), x_tr.std(0) + 1e-12
    z = lambda x: np.hstack([(x - mean) / std, np.ones((len(x), 1))])  # noqa: E731  standardise + intercept
    print(f"{ds.path}: router {args.router}, window {args.window}, horizon {args.horizon}, stride {args.stride}")
    print(f"  samples: train {len(y_tr):,} ({len(seen['train'])} episodes), validation {len(y_va):,} "
          f"({len(seen['validation'])}), test {len(y_te):,} ({len(seen['test'])}); features {x_tr.shape[1]}")
    print(f"  target: loss ratio over the next {args.horizon} steps; mean {y_tr.mean():.4f}, "
          f"share of samples with loss {np.mean(y_tr > 0):.3f}")

    grid = [10 ** k for k in range(-6, 3)]
    scores = {lam: metrics(y_va, z(x_va) @ ridge_fit(z(x_tr), y_tr, lam))["RMSE"] for lam in grid}
    lam = min(scores, key=scores.get)
    w = ridge_fit(z(x_tr), y_tr, lam)
    print(f"\nRidge penalty chosen on validation: lambda = {lam:g} (validation RMSE {scores[lam]:.4f})")
    report = pd.DataFrame({"ridge (validation)": metrics(y_va, z(x_va) @ w),
                           "persistence (validation)": metrics(y_va, b_va),
                           "ridge (test)": metrics(y_te, z(x_te) @ w),
                           "persistence (test)": metrics(y_te, b_te)}).T
    print(report.to_string())

    test_pred = np.clip(z(x_te) @ w, 0, 1)
    by_load = pd.DataFrame({"episode_id": e_te, "ridge_error": np.abs(y_te - test_pred),
                            "persistence_error": np.abs(y_te - b_te), "target": y_te})
    by_load = by_load.join(episodes[["load_level", "traffic_profile"]], on="episode_id")
    print("\nTest MAE by load level and traffic profile:")
    print(by_load.groupby(["load_level", "traffic_profile"])[["target", "ridge_error", "persistence_error"]]
          .mean().rename(columns={"target": "mean_loss"}).to_string())
    print("\nAll checks passed.")


if __name__ == "__main__":
    main()