-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_graphs.py
382 lines (301 loc) · 15.8 KB
/
make_graphs.py
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import matplotlib.pyplot as plt
import pandas as pd
import os
import seaborn as sns
import numpy as np
from simple_term_menu import TerminalMenu
pd.options.mode.chained_assignment = None
class StatisticsFileLoader:
def __init__(self, stats_path = '/var/lib/sparse/stats'):
self.stats_path = stats_path
def select_from_options(self, options, title) -> str:
terminal_menu = TerminalMenu(options, title=title)
menu_entry_index = terminal_menu.show()
if menu_entry_index is None:
return None
print(f"{title} {options[menu_entry_index]}")
return options[menu_entry_index]
def load_dataframe(self, dataframe_type = None):
if dataframe_type is None:
dataframe_type = plotter.file_loader.select_from_options(["ClientRequestStatisticsRecord", "ServerRequestStatisticsRecord"], "Data frame type:")
data_files = [path for path in os.listdir(self.stats_path) if path.startswith(dataframe_type) and path.endswith(".csv")]
data_files.sort()
filename = self.select_from_options(data_files, "Dataframe file name:")
if filename is None:
return None, None
filepath = os.path.join(self.stats_path, filename)
try:
return dataframe_type, pd.read_csv(filepath)
except FileNotFoundError:
print(f"File '{filename}' was not found in directory '{STATS_PATH}'. Make sure that it exists and is readable.")
def parse_boxplot_frame(self):
dataframe_type = "ClientRequestStatisticsRecord"
_, df = self.load_dataframe(dataframe_type)
if df is None:
return None
no_datasources = input("Number of data sources in experiment: ")
used_scheduling = self.select_from_options(["FCFS", "B-FCFS", "PS", "B-PS"], "Scheduling method:")
df = df.assign(Connections=int(no_datasources), Scheduling=used_scheduling)
# Statistics only for offloaded tasks
df = df.loc[df['request_op']=='offload_task']
return df
def parse_scales(self):
title = input("Plot title: ")
try:
start_at = float(input("Start at timestamp: "))
except ValueError:
start_at = 0.0
try:
period_length = float(input("Period length: "))
except ValueError:
period_length = -1.0
try:
y_min = float(input("Min y: "))
except ValueError:
y_min = -1
try:
y_max = float(input("Max y: "))
except ValueError:
y_max = -1
return title, start_at, period_length, y_min, y_max
class StatisticsGraphPlotter:
def __init__(self, write_path = '/var/lib/sparse/stats'):
self.file_loader = StatisticsFileLoader()
self.write_path = write_path
def count_offload_task_client_statistics_legacy(self, df, start_at = 0.0, period_length = -1.0):
df = df.rename(columns={ 'processing_started':'request_sent_at',
'latency': 'Latency (ms)',
'node_id': 'connection_id',
'offload_latency': 'Offload latency (ms)' })
# Scale latencies to milliseconds
df['Latency (ms)'] = df['Latency (ms)'].apply(lambda x: 1000.0*x)
df['Offload latency (ms)'] = df['Offload latency (ms)'].apply(lambda x: 1000.0*x)
# Drop first rows to ignore 'slow start'
# (See e.g: https://stackoverflow.com/questions/64420777/opencv-cuda-api-very-slow-at-the-first-call)
df = df[df["request_sent_at"] >= start_at]
if period_length > 0.0:
df = df[df["request_sent_at"] <= start_at + period_length]
df["request_sent_at"] = df["request_sent_at"].apply(lambda x: x-start_at)
return df.set_index("request_sent_at")
def count_offload_task_client_statistics(self, df, start_at = 0.0, period_length = -1.0):
"""Calculates latencies from a Dataframe with time stamps, and returns a new DataFrame with the results.
Result DataFrame uses 'request_sent_at' timestamp as the index.
"""
df = df.loc[df['request_op']=='offload_task']
df['e2e_latency'] = df['response_received_at'] - df['processing_started_at']
df['offload_latency'] = df['response_received_at'] - df['request_sent_at']
df = df.rename(columns={ 'e2e_latency': 'Latency (ms)',
'offload_latency': 'Offload latency (ms)',
'node_id': 'connection_id' })
# Scale latencies to milliseconds
df['Latency (ms)'] = df['Latency (ms)'].apply(lambda x: 1000.0*x)
df['Offload latency (ms)'] = df['Offload latency (ms)'].apply(lambda x: 1000.0*x)
# Drop first rows to ignore 'slow start'
# (See e.g: https://stackoverflow.com/questions/64420777/opencv-cuda-api-very-slow-at-the-first-call)
df = df[df["request_sent_at"] >= start_at]
if period_length > 0.0:
df = df[df["request_sent_at"] <= start_at + period_length]
df["request_sent_at"] = df["request_sent_at"].apply(lambda x: x-start_at)
return df.set_index("request_sent_at")
def count_offload_task_server_statistics(self, df, start_at = 0.0, period_length = -1.0):
df = df.loc[df['request_op']=='offload_task']
df['e2e_latency'] = df['response_sent_at'] - df['request_received_at']
df['rx_latency'] = df['task_queued_at'] - df['request_received_at']
df['queueing_time'] = df['task_started_at'] - df['task_queued_at']
df['task_latency'] = df['task_completed_at'] - df['task_started_at']
df['tx_latency'] = df['response_sent_at'] - df['task_completed_at']
# Scale latencies to milliseconds
for column in ['e2e_latency', 'rx_latency', 'queueing_time', 'task_latency', 'tx_latency']:
df[column] = df[column].apply(lambda x: 1000.0*x)
# Rename columns
df = df.rename(columns={ 'e2e_latency': 'Service time (ms)',
'rx_latency': 'RX latency (ms)',
'queueing_time': 'Queueing time (ms)',
'task_latency': 'Task latency (ms)',
'tx_latency': 'TX latency (ms)' })
# Translate time axis
df = df[df["request_received_at"] >= start_at]
if period_length > 0.0:
df = df[df["request_received_at"] <= start_at + period_length]
df["request_received_at"] = df["request_received_at"].apply(lambda x: x-start_at)
return df.set_index("request_received_at")
def count_offload_task_server_batch_statistics(self, df, start_at = 0.0, period_length = -1.0):
df = df.loc[df['request_op']=='offload_task']
df = df[df["task_started_at"] >= start_at]
if period_length > 0.0:
df = df[df["task_started_at"] <= start_at + period_length]
result_df = pd.DataFrame([], columns=["Task started (s)", "Task latency (ms)", "Batch Size"])
batch_size = task_started = task_latency = 0
batch_no = -1
for i in df.index:
if df["batch_no"][i] == batch_no:
batch_size += 1
else:
if batch_size > 0:
result_df.loc[len(result_df.index)] = [task_started, task_latency, batch_size]
batch_no = df["batch_no"][i]
task_started = df["task_started_at"][i]
task_latency = 1000.0 * (df["task_completed_at"][i] - df["task_started_at"][i])
batch_size = 1
result_df["Task started (s)"] = result_df["Task started (s)"].apply(lambda x: x-start_at)
return result_df.set_index("Task started (s)")
def print_statistics(self, legacy = False):
dataframe_type, df = self.file_loader.load_dataframe()
batch_stats = self.count_offload_task_server_batch_statistics(df)
print(batch_stats)
return
if dataframe_type == "ClientRequestStatisticsRecord":
# Calculate statistics for offloaded tasks
if legacy:
stats = self.count_offload_task_client_statistics_legacy(df)
else:
stats = self.count_offload_task_client_statistics(df)
# Print statistics
print(stats[['Latency (ms)', 'Offload latency (ms)']].describe())
else:
stats = self.count_offload_task_server_statistics(df)
print(stats[['Service time (ms)', 'RX latency (ms)', 'Queueing time (ms)', 'Task latency (ms)', 'TX latency (ms)']].describe())
def plot_latency_timeline(self, latency = False):
dataframe_type, df = self.file_loader.load_dataframe()
title, start_at, period_length, y_min, y_max = self.file_loader.parse_scales()
marker = 'o' if (input("Use marker in plot points (y/N): ")) == "y" else ''
# Count analytics
if dataframe_type == "ClientRequestStatisticsRecord":
if latency:
stats = self.count_offload_task_client_statistics_legacy(df, start_at, period_length)
else:
stats = self.count_offload_task_client_statistics(df, start_at, period_length)
else:
stats = self.count_offload_task_server_statistics(df, start_at, period_length)
# Plot graph
ylabel = "Offload latency (ms)" if dataframe_type == "ClientRequestStatisticsRecord" else "Service time (ms)"
xlabel = "Request sent (s)" if dataframe_type == "ClientRequestStatisticsRecord" else "Request received (s)"
plt.rcParams.update({ 'font.size': 32 })
fig, ax = plt.subplots(figsize=(12,8))
for label, data in stats.groupby("connection_id"):
data.plot(y=ylabel, ax=ax, label=label, marker=marker)
plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.grid()
ax.get_legend().remove()
if period_length > 0:
ax.set_xlim([0, period_length])
if y_min > 0 or y_max > 0:
ax.set_ylim([y_min, y_max])
filepath = os.path.join(self.write_path, f"{dataframe_type}_latency_timeline.png")
plt.tight_layout()
plt.savefig(filepath, dpi=400)
print(f"Saved column plot to '{filepath}'")
def plot_benchmark_barplot(self):
title, start_at, period_length, y_min, y_max = self.file_loader.parse_scales()
plt.figure(figsize=(16,8))
plt.rcParams.update({ 'font.size': 18 })
barplot_data = pd.DataFrame([], columns=["Connections", "RX", 'Queueing', 'Task', "TX"])
dataframe_type = "ServerRequestStatisticsRecord"
while True:
_, df = self.file_loader.load_dataframe(dataframe_type)
if df is None:
break
no_connections = int(input("Number of connections: "))
stats = self.count_offload_task_server_statistics(df)
barplot_data.loc[len(barplot_data.index)] = [int(no_connections),
stats.loc[:, 'RX latency (ms)'].mean(),
stats.loc[:, 'Queueing time (ms)'].mean(),
stats.loc[:, 'Task latency (ms)'].mean(),
stats.loc[:, 'TX latency (ms)'].mean()]
barplot_data.Connections = barplot_data.Connections.astype(int)
barplot_data = barplot_data.set_index("Connections")
ax = barplot_data.plot.bar(rot=0, stacked=True)
plt.title(title)
plt.ylabel("Latency (ms)")
if y_max > 0:
ax.set_ylim([0, y_max])
filepath = os.path.join(self.write_path, f"{dataframe_type}_latency_barplot.png")
plt.tight_layout()
plt.savefig(filepath, dpi=400)
print(f"Saved benchmark barplot to '{filepath}'")
def plot_offload_latency_boxplot(self):
plt.rcParams.update({ 'font.size': 24 })
plt.figure(figsize=(12,8))
dataframe_type = "ClientRequestStatisticsRecord"
frames = []
title, start_at, period_length, y_min, y_max = self.file_loader.parse_scales()
while True:
df = self.file_loader.parse_boxplot_frame()
if df is None:
break
frames.append(self.count_offload_task_client_statistics(df, start_at, period_length))
ax = sns.boxplot(x="Connections",
y="Offload latency (ms)",
hue="Scheduling",
data=pd.concat(frames),
palette="dark:grey",
showfliers=False)
if y_min > 0 or y_max > 0:
ax.set_ylim([y_min, y_max])
filepath = os.path.join(self.write_path, f"{dataframe_type}_latency_boxplot.png")
plt.tight_layout()
plt.savefig(filepath, dpi=400)
print(f"Saved offload latency boxplot to '{filepath}'")
def plot_batch_distribution(self):
title, start_at, period_length, y_min, y_max = self.file_loader.parse_scales()
dataframe_type = "ServerRequestStatisticsRecord"
_, df = self.file_loader.load_dataframe(dataframe_type)
no_connections = int(input("Number of connections: "))
stats = self.count_offload_task_server_batch_statistics(df, start_at, period_length)
plt.rcParams.update({ 'font.size': 24 })
plt.figure(figsize=(24,8))
stats["Batch Size"] = stats["Batch Size"].astype(int)
stats.hist(column="Batch Size", legend=False, bins=no_connections)
plt.grid(None)
plt.xlabel("Batch size")
plt.title(title)
plt.xlim([0, no_connections + 1])
plt.tick_params(left = False, labelleft = False)
plt.tight_layout()
filepath = os.path.join(self.write_path, f"{dataframe_type}_batch_size_histogram.png")
plt.savefig(filepath, dpi=400)
print(f"Saved batch size histogram to '{filepath}'")
def plot_batch_latency_boxplot(self):
title, start_at, period_length, y_min, y_max = self.file_loader.parse_scales()
dataframe_type = "ServerRequestStatisticsRecord"
frames = []
while True:
_, df = self.file_loader.load_dataframe(dataframe_type)
if df is None:
break
frames.append(self.count_offload_task_server_batch_statistics(df, start_at, period_length))
stats = pd.concat(frames)
plt.rcParams.update({ 'font.size': 24 })
plt.figure(figsize=(24,8))
stats["Batch Size"] = stats["Batch Size"].astype(int)
max_batch_size = stats["Batch Size"].max()
plt.rcParams.update({ 'font.size': 24 })
plt.figure(figsize=(12,8))
ax = sns.boxplot(x="Batch Size",
y="Task latency (ms)",
data=stats,
showfliers=False)
plt.title(title)
plt.xticks(np.arange(max_batch_size, step=10))
plt.tight_layout()
filepath = os.path.join(self.write_path, f"{dataframe_type}_batch_size_latency_boxplot.png")
plt.savefig(filepath, dpi=400)
print(f"Saved task latency boxplot to '{filepath}'")
if __name__ == "__main__":
plotter = StatisticsGraphPlotter()
operation = plotter.file_loader.select_from_options(["Print DataFrame", "Plot timeline", "Plot barplot", "Plot boxplot", "Plot batch size distribution", "Plot batch latency variance"], "Select operation:")
legacy = bool(input("Legacy format y/N: "))
if operation == "Print DataFrame":
plotter.print_statistics(legacy)
elif operation == "Plot timeline":
plotter.plot_latency_timeline(legacy)
elif operation == "Plot barplot":
plotter.plot_benchmark_barplot()
elif operation == "Plot boxplot":
plotter.plot_offload_latency_boxplot()
elif operation == "Plot batch size distribution":
plotter.plot_batch_distribution()
else:
plotter.plot_batch_latency_boxplot()