-
Notifications
You must be signed in to change notification settings - Fork 75
/
analyze.py
174 lines (153 loc) · 4.75 KB
/
analyze.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This script analyzes the JSON results in a given directory."""
import os
import re
import json
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime
from argparse import ArgumentParser
def colors_from_values(values, palette_name):
# normalize the values to range [0, 1]
normalized = (values - min(values)) / (max(values) - min(values))
# convert to indices
indices = np.round(normalized * (len(values) - 1)).astype(np.int32)
# use the indices to get the colors
palette = sns.color_palette(palette_name, len(values))
return np.array(palette).take(indices, axis=0)
def plot(df, rounds, to_file):
# Theme
sns.set(style="dark", context="paper")
sns.set_color_codes("pastel")
plt.style.use("dark_background")
df["name-with-version"] = df["name"].astype(str) + " v" + df["version"]
# Plot
# TODO: Find a way to display the platte scale to highly accuracy better.
bar = sns.barplot(
x="min",
y="name-with-version",
data=df,
width=1,
edgecolor="black",
linewidth=2,
errwidth=0,
log=True,
# TODO: Improve color palette.
# https://seaborn.pydata.org/tutorial/color_palettes.html
palette=colors_from_values(df["accuracy"], "light:seagreen"),
)
bar.bar_label(
bar.containers[0],
fontsize=10,
padding=3,
)
plt.xlabel("Minimum time (ms) in log scale", fontweight="bold")
plt.ylabel(None)
# Title
plt.suptitle(
"Speed comparison of various programming languages\n",
fontweight="bold",
fontsize=20,
y=1.02,
)
plt.title(
f"Method: calculating π through the Leibniz formula {rounds} times",
style="italic",
fontsize=16,
y=1.02,
)
# Caption
url = f"https://github.com/niklas-heer/speed-comparison"
plt.figtext(
0.75, -0.05, url, wrap=True, horizontalalignment="left", fontsize=8
)
timestamp = f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}"
plt.figtext(
0.1,
-0.05,
timestamp,
wrap=True,
horizontalalignment="right",
fontsize=8,
)
sns.despine()
plt.autoscale()
plt.savefig(to_file, pad_inches=0.2, bbox_inches="tight", dpi=200)
def main():
parser = ArgumentParser()
parser.add_argument(
"--folder",
dest="folder",
help="Path to folder which contains JSON files.",
)
parser.add_argument(
"--out",
dest="out",
help="Path to generate output file to.",
)
parser.add_argument(
"--rounds",
dest="rounds",
help="Path to the rounds.txt file.",
)
args = parser.parse_args()
data = {
"name": [],
"version": [],
"median": [],
"min": [],
"max": [],
"accuracy": [],
}
# r=root, d=directories, f = files
for r, d, f in os.walk(args.folder):
for file in f:
if file.endswith(".json"):
with open(os.path.join(r, file), "r") as reader:
# TODO: Add check if the file is formatted correctly
json_data = json.load(reader)
data["name"].append(json_data["Language"])
data["version"].append(json_data["Version"])
data["median"].append(
# We want milliseconds (ms) in the end
round(
pd.Timedelta(json_data["Median"]).total_seconds()
* 1000,
2,
)
)
data["max"].append(
round(
pd.Timedelta(json_data["Max"]).total_seconds()
* 1000,
2,
)
)
data["min"].append(
round(
pd.Timedelta(json_data["Min"]).total_seconds()
* 1000,
2,
)
)
data["accuracy"].append(round(json_data["Accuracy"], 4))
df = pd.DataFrame(data)
df.sort_values(by=["min"], inplace=True)
file_base = f"combined_results"
png = f"{file_base}.png"
csv = f"{file_base}.csv"
df.to_csv(
csv,
index=False,
encoding="utf-8",
)
# Visualize
rounds = 0
with open(args.rounds, "r") as reader:
rounds = reader.read().strip()
plot(df, rounds, png)
print(f"Successful. Files generated:\n {csv}\n {png}")
main()