Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
Latest commit
251 lines (181 loc) · 6.92 KB
/
Copy pathplot.py
File metadata and controls
251 lines (181 loc) · 6.92 KB
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
# SPDX-FileCopyrightText: 2024 Steffen Vogel <steffen.vogel@opal-rt.com>, OPAL-RT Germany GmbH
# SPDX-License-Identifier: Apache-2.0
importmatplotlib.pyplotasplt
importpandasaspd
importglob
importre
importos
importjson
frompprintimportpprint
fromfunctoolsimportcached_property
fromitertoolsimportgroupby
fromdatetimeimportdatetime
frompathlibimportPosixPath
fromdataclassesimportdataclass
results_dir=PosixPath("./results")
regex=re.compile(r"")
@dataclass
classResultFile:
filename: PosixPath
test: str
date: datetime
rate: int
values: int
@classmethod
deffrom_path(cls, path: PosixPath) ->"ResultFile":
pattern=r"test-rtt_(\d{4}-\d{2}-\d{2})_(\d{2}-\d{2}-\d{2})_([_a-z]+?)_values(\d+)_rate(\d+)"
# Search for the pattern in the filename
match=re.search(pattern, path.as_posix())
ifmatch:
date_str=match.group(1)
time_str=match.group(2)
test=match.group(3)
values=match.group(4)
rate=match.group(5)
datetime_str=f"{date_str}{time_str.replace('-', ':')}"
date_time=datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
returncls(path, test, date_time, int(rate), int(values))
else:
raiseValueError("Filename does not match the expected format")
@property
deftitle(self):
ifself.test=="webrtc":
return"WebRTC (UDP)"
elifself.test=="webrtc_relayed_udp":
return"WebRTC (UDP, relayed)"
elifself.test=="webrtc_relayed_tcp":
return"WebRTC (TCP, relayed)"
elifself.test=="webrtc_tcp":
return"WebRTC (TCP)"
elifself.test=="sampled_values":
return"Sampled Values"
elifself.test=="websocket":
return"WebSockets"
elifself.test=="websocket_relayed":
return"WebSockets (relayed)"
elifself.test=="mqtt":
return"MQTT"
elifself.test=="loopback":
return"Loopback"
elifself.test=="udp":
return"UDP"
else:
returnself.test
@cached_property
defdata(self):
returnpd.read_csv(
self.filename,
names=["seconds", "nanoseconds", "offset", "sequence"],
comment="#",
)
@cached_property
defmetadata(self):
withopen(self.filename, "rb") asf:
try: # catch OSError in case of a one line file
f.seek(-2, os.SEEK_END)
whilef.read(1) !=b"\n":
f.seek(-2, os.SEEK_CUR)
exceptOSError:
f.seek(0)
last_line=f.readline().decode()
iflast_line.startswith("# "):
metadata_json=last_line.removeprefix("# ")
returnjson.loads(metadata_json)
def__getattr__(self, name: str):
returnself.data[name]
deffind_results(pattern: PosixPath) ->list[ResultFile]:
return [
ResultFile.from_path(PosixPath(path)) forpathinglob.glob(pattern.as_posix())
]
defplot_boxplot(results, fn):
fig=plt.figure(figsize=(10, 6))
files=results[0] # Use newest
data=pd.DataFrame(
{file.rate: file.offset*1e3forfileinsorted(files, key=lambdaf: f.rate)}
)
data.boxplot(showmeans=False, showfliers=False)
plt.xlabel("Rate [samples/s]", fontsize=18)
plt.ylabel("RTT [ms]", fontsize=18)
plt.grid(True)
plt.xticks(rotation=-45, fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
fig.savefig(fn, format="svg")
defplot_medians_for_rates(results, fn):
fig, ax1=plt.subplots(figsize=(10, 6))
fortest, filesinresults.items():
files=files[0] # Use newest
files=sorted(files, key=lambdaf: f.rate)
x= [f"{file.rate}"forfileinfiles]
y= [1e3*file.offset.median() forfileinfiles]
ax1.plot(x, y, marker="o", linestyle="-", label=files[0].title)
plt.xlabel("Rate [samples/s]", fontsize=20)
plt.ylabel("RTT [ms]", fontsize=20)
plt.legend(fontsize=13, ncol=2, fancybox=True, loc="lower left", bbox_to_anchor=(0, 0.06))
plt.grid(True)
plt.xticks(rotation=-45, fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
fig.savefig(fn, format="svg")
defplot_medians_for_values(results, fn):
fig=plt.figure(figsize=(10, 6))
fortest, filesinresults.items():
files=files[0] # Use newest
files=sorted(files, key=lambdaf: f.values)
x= [f"{file.values}"forfileinfiles]
y= [1e3*file.offset.median() forfileinfiles]
plt.plot(x, y, marker="o", linestyle="-", label=files[0].title)
plt.xlabel("Values per sample", fontsize=20)
plt.ylabel("RTT [ms]", fontsize=20)
plt.legend(fontsize=13, ncol=2, fancybox=True, loc="lower left", bbox_to_anchor=(0, 0.06))
plt.grid(True)
plt.xticks(rotation=-45, fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
fig.savefig(fn, format="svg")
defgroup_results(results):
grouped= {}
# Group by test
by_test=sorted(results, key=lambdaf: f.test)
by_test=groupby(by_test, key=lambdaf: f.test)
fortest, resultsinby_test:
# Group by date
by_date=sorted(results, key=lambdaf: f.date, reverse=True)
by_date=groupby(by_date, key=lambdaf: f.date)
fordate, resultsinby_date:
files= [resultforresultinresults]
mode="rates"iflen({file.rateforfileinfiles}) >1else"values"
m=grouped.setdefault(mode, {})
t=m.setdefault(test, [])
t.append(files)
returngrouped
defcalc_stats(results):
stats= {}
fortest, filesinresults.items():
files=files[0] # Use newest
iftest=="loopback":
continue
all=pd.concat([file.offsetforfileinfiles])
print()
print(test)
print(all.describe())
print(f"median {all.median()}")
pprint(all)
break
defmain():
pattern=results_dir/"*"
results=find_results(pattern)
results=group_results(results)
formode, testsinresults.items():
print(f"For mode: {mode}")
fortest, filesintests.items():
files=files[0] # Use newest
print(f" using {len(files)} datasets from {files[0].date} for {files[0].test} with {files[0].values} values at {files[0].rate} smps/s")
# data = pd.concat([f.offset.rename(f.rate) for f in results], axis=1)
os.makedirs("plots", exist_ok=True)
plot_boxplot(results.get("rates").get("webrtc"), f"plots/boxplot_webrtc.svg")
plot_medians_for_rates(results.get("rates"), "plots/plot_medians_by_rate.svg")
plot_medians_for_values(results.get("values"), "plots/plot_medians_by_values.svg")
calc_stats(results.get("rates", {}))
if__name__=="__main__":
main()