Skip to content

Commit 193ad4b

Browse files
committed
use plotly to visualize
1 parent 2cfdf70 commit 193ad4b

1 file changed

Lines changed: 225 additions & 0 deletions

File tree

scripts/viz.py

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
"""
2+
pulsebeam_viz.py
3+
----------------
4+
Lightning-Fast Interactive WebRTC SFU Analytics (Plotly Engine)
5+
Manually windowed via --offset-ms to skip warmup phases instantly.
6+
"""
7+
8+
import argparse
9+
import numpy as np
10+
import pandas as pd
11+
import plotly.graph_objects as go
12+
from plotly.subplots import make_subplots
13+
14+
# --- Target Aesthetic Colors ---
15+
BG_COLOR = "#0b0f19"
16+
GRID_COLOR = "#1e293b"
17+
TEXT_MUTED = "#94a3b8"
18+
TEXT_MAIN = "#f8fafc"
19+
20+
COLOR_P999 = "#0ea5e9"
21+
COLOR_P99 = "#d946ef"
22+
COLOR_P50 = "#64748b"
23+
COLOR_TPUT = "#3b82f6"
24+
25+
26+
def process_data(lat_csv: str, snap_csv: str, window_secs: float, offset_ms: float, duration_ms: float):
27+
end_ms = offset_ms + duration_ms if duration_ms else float('inf')
28+
29+
# ---------------------------------------------------------
30+
# 1. PROCESS LATENCY (Lightning Fast Filtering)
31+
# ---------------------------------------------------------
32+
lat_df = pd.read_csv(lat_csv)
33+
lat_df.columns = lat_df.columns.str.strip()
34+
35+
# Filter immediately to save CPU cycles
36+
lat_df = lat_df[(lat_df["elapsed_ms"] >= offset_ms) & (lat_df["elapsed_ms"] <= end_ms)].copy()
37+
if lat_df.empty:
38+
raise ValueError("No latency data found in the specified --offset-ms and --duration-ms window.")
39+
40+
lat_df["delay_ms"] = lat_df["delay_us"] / 1000.0
41+
lat_df["plot_time"] = (lat_df["elapsed_ms"] - offset_ms) / 1000.0
42+
lat_df["window_rel"] = (lat_df["plot_time"] // window_secs) * window_secs
43+
44+
active_agents = lat_df.groupby("window_rel")["agent_id"].nunique().reset_index()
45+
active_agents.rename(columns={"agent_id": "agents"}, inplace=True)
46+
47+
# ---------------------------------------------------------
48+
# 2. PROCESS SNAPSHOTS (O(N) Fast Smearing)
49+
# ---------------------------------------------------------
50+
snap_df = pd.read_csv(snap_csv)
51+
snap_df.columns = snap_df.columns.str.strip()
52+
snap_df = snap_df.sort_values(['agent_id', 'elapsed_ms'])
53+
54+
# We must calculate diffs BEFORE filtering, so the first snapshot in our window knows its history
55+
snap_df['tx_diff'] = snap_df.groupby('agent_id')['tx_bytes'].diff().clip(lower=0)
56+
snap_df['rx_diff'] = snap_df.groupby('agent_id')['rx_bytes'].diff().clip(lower=0)
57+
snap_df['dt_sec'] = snap_df.groupby('agent_id')['elapsed_ms'].diff() / 1000.0
58+
59+
# Now filter to our window
60+
snap_df = snap_df[(snap_df["elapsed_ms"] >= offset_ms) & (snap_df["elapsed_ms"] <= end_ms)].copy()
61+
62+
valid_snaps = snap_df[snap_df['dt_sec'] > 0].copy()
63+
valid_snaps['bytes_total'] = valid_snaps['tx_diff'] + valid_snaps['rx_diff']
64+
valid_snaps['rate_mbps'] = (valid_snaps['bytes_total'] * 8) / (valid_snaps['dt_sec'] * 1_000_000.0)
65+
66+
valid_snaps['end_rel'] = (valid_snaps['elapsed_ms'] - offset_ms) / 1000.0
67+
valid_snaps['start_rel'] = valid_snaps['end_rel'] - valid_snaps['dt_sec']
68+
69+
# O(N) Fast Accumulation (No more slow boolean masks!)
70+
max_t = lat_df["window_rel"].max()
71+
num_bins = int((max_t // window_secs) + 2)
72+
mbps_totals = np.zeros(num_bins, dtype=float)
73+
74+
for row in valid_snaps.itertuples(index=False):
75+
start_idx = max(0, int(row.start_rel // window_secs))
76+
end_idx = min(num_bins, int(row.end_rel // window_secs) + 1)
77+
# Smear the mbps rate across the bins it touches
78+
mbps_totals[start_idx:end_idx] += row.rate_mbps
79+
80+
times = np.arange(0, num_bins * window_secs, window_secs)
81+
tput = pd.DataFrame({'window_rel': times, 'mbps_raw': mbps_totals})
82+
83+
tput = pd.merge(tput, active_agents, on="window_rel", how="left").fillna({'agents': 0})
84+
# Smooth throughput display
85+
tput['mbps'] = tput['mbps_raw'].rolling(window=3, center=True, min_periods=1).median()
86+
87+
# Crop to actual data bounds
88+
tput = tput[tput['window_rel'] <= max_t].copy()
89+
90+
return lat_df, tput
91+
92+
93+
def plot_benchmark(lat_csv: str, snap_csv: str, label: str, window_secs: float, offset_ms: float, duration_ms: float):
94+
lat_df, tput = process_data(lat_csv, snap_csv, window_secs, offset_ms, duration_ms)
95+
96+
# Calculate Percentiles
97+
percentiles = lat_df.groupby("window_rel")["delay_ms"].agg(
98+
p50=lambda x: np.percentile(x, 50),
99+
p99=lambda x: np.percentile(x, 99),
100+
p999=lambda x: np.percentile(x, 99.9),
101+
pmax=lambda x: np.max(x)
102+
).reset_index()
103+
104+
# Calculate Summary Stats for the Subtitle
105+
max_agents = int(tput["agents"].max())
106+
p50_med = percentiles["p50"].median()
107+
p99_med = percentiles["p99"].median()
108+
p999_med = percentiles["p999"].median()
109+
max_lat = percentiles["pmax"].max()
110+
tput_avg = tput["mbps"].mean()
111+
tput_max = tput["mbps"].max()
112+
duration_s = int(tput["window_rel"].max())
113+
114+
# Build the rich HTML title
115+
title_html = f"""
116+
<span style="font-size: 22px; font-weight: bold; color: {TEXT_MAIN};">SFU Runtime Jitter Benchmark — {label}</span><br>
117+
<span style="font-size: 13px; color: {TEXT_MUTED};">
118+
Peak Concurrency: {max_agents} Agents • Window: {window_secs}s • Sliced Duration: {duration_s}s (Offset: {offset_ms}ms)<br>
119+
Transit Latency • Med: {p50_med:.2f} ms • P99: {p99_med:.2f} ms • P99.9: {p999_med:.2f} ms • Max: {max_lat:.2f} ms<br>
120+
Edge Throughput • Avg: {tput_avg:.2f} Mbps • Peak: {tput_max:.2f} Mbps
121+
</span>
122+
"""
123+
124+
# --- PLOTLY FIGURE SETUP ---
125+
fig = make_subplots(
126+
rows=2, cols=1,
127+
shared_xaxes=True,
128+
row_heights=[0.75, 0.25],
129+
vertical_spacing=0.08
130+
)
131+
132+
# 1. P99.9 Line
133+
fig.add_trace(go.Scatter(
134+
x=percentiles["window_rel"], y=percentiles["p999"],
135+
name="P99.9 (Extreme Tail)",
136+
line=dict(color=COLOR_P999, width=1.5),
137+
opacity=0.8
138+
), row=1, col=1)
139+
140+
# 2. P99 Line (Glowing)
141+
fig.add_trace(go.Scatter(
142+
x=percentiles["window_rel"], y=percentiles["p99"],
143+
showlegend=False, hoverinfo='skip',
144+
line=dict(color=COLOR_P99, width=8),
145+
opacity=0.15
146+
), row=1, col=1)
147+
148+
fig.add_trace(go.Scatter(
149+
x=percentiles["window_rel"], y=percentiles["p99"],
150+
name="P99 (Tail)",
151+
line=dict(color=COLOR_P99, width=2.5)
152+
), row=1, col=1)
153+
154+
# 3. P50 Line
155+
fig.add_trace(go.Scatter(
156+
x=percentiles["window_rel"], y=percentiles["p50"],
157+
name="P50 (Median)",
158+
line=dict(color=COLOR_P50, width=1.5, dash='dot')
159+
), row=1, col=1)
160+
161+
# 4. Throughput Fill
162+
fig.add_trace(go.Scatter(
163+
x=tput["window_rel"], y=tput["mbps"],
164+
name="Throughput (Mbps)",
165+
fill='tozeroy',
166+
line=dict(color=COLOR_TPUT, width=2),
167+
fillcolor=f"rgba(59, 130, 246, 0.15)"
168+
), row=2, col=1)
169+
170+
# --- LAYOUT & STYLING ---
171+
fig.update_layout(
172+
title=dict(text=title_html, x=0.5, xanchor='center', y=0.96),
173+
margin=dict(t=120, b=40, l=60, r=40),
174+
paper_bgcolor=BG_COLOR,
175+
plot_bgcolor=BG_COLOR,
176+
font=dict(family="Inter, -apple-system, sans-serif", color=TEXT_MAIN),
177+
hovermode="x unified",
178+
hoverlabel=dict(bgcolor="#1e293b", font_size=13, font_family="monospace"),
179+
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1, bgcolor="rgba(0,0,0,0)"),
180+
)
181+
182+
lat_max = min(percentiles["p999"].max() * 1.2, 150.0)
183+
fig.update_yaxes(
184+
title_text="Latency [ms]", title_font=dict(color=TEXT_MUTED, size=12),
185+
range=[0, lat_max],
186+
showgrid=True, gridwidth=1, gridcolor=GRID_COLOR, zerolinecolor=GRID_COLOR,
187+
showspikes=True, spikemode="across", spikethickness=1, spikedash="dash", spikecolor=TEXT_MUTED,
188+
row=1, col=1
189+
)
190+
191+
fig.update_yaxes(
192+
title_text="Traffic [Mbps]", title_font=dict(color=TEXT_MUTED, size=12),
193+
range=[max(0, tput_avg * 0.5), tput_max * 1.2],
194+
showgrid=True, gridwidth=1, gridcolor=GRID_COLOR, zerolinecolor=GRID_COLOR,
195+
showspikes=True, spikemode="across", spikethickness=1, spikedash="dash", spikecolor=TEXT_MUTED,
196+
row=2, col=1
197+
)
198+
199+
fig.update_xaxes(
200+
showgrid=True, gridwidth=1, gridcolor=GRID_COLOR, zerolinecolor=GRID_COLOR,
201+
showspikes=True, spikemode="across", spikethickness=1, spikedash="dash", spikecolor=TEXT_MUTED,
202+
)
203+
204+
fig.update_xaxes(
205+
title_text="Time since offset [s]", title_font=dict(color=TEXT_MUTED, size=12),
206+
rangeslider=dict(visible=True, thickness=0.06, bgcolor="#1e293b"),
207+
row=2, col=1
208+
)
209+
210+
print(f"✅ Loaded window instantly. Plotting {max_agents} peak concurrent agents...")
211+
fig.show()
212+
213+
if __name__ == "__main__":
214+
parser = argparse.ArgumentParser(description="Interactive SFU Analytics Plotter")
215+
parser.add_argument("--latency-csv", required=True)
216+
parser.add_argument("--snapshots-csv", required=True)
217+
parser.add_argument("--label", required=True, help="e.g., 'Thread-per-Core'")
218+
parser.add_argument("--window", type=float, default=1.0, help="Bin resolution in seconds")
219+
220+
# User-defined overrides
221+
parser.add_argument("--offset-ms", type=float, required=True, help="Skip this many milliseconds of warmup data")
222+
parser.add_argument("--duration-ms", type=float, default=None, help="Stop plotting after this many milliseconds")
223+
224+
args = parser.parse_args()
225+
plot_benchmark(args.latency_csv, args.snapshots_csv, args.label, args.window, args.offset_ms, args.duration_ms)

0 commit comments

Comments
 (0)