1 # -*- coding: utf-8 -*-
2 """This module contain functions to ease graph plots."""
4 from matplotlib import pyplot as plt
6 from sys import argv, exit
8 import scipy.stats as ss
10 # ed - euclidean distance
11 # rs - reeds and shepp path length
12 # sh - reeds and shepp, same heading
14 # ad - optimize with dijkstra, all nodes
15 # as - optimize with smart, all nodes
16 # ar - optimize with remove redundant points, all nodes
17 # cd - optimize with dijkstra, cusp nodes
18 # cs - optimize with smart, cusp nodes
19 # cr - optimize with remove redundant points, cusp nodes
23 {"f": "T2", "c": "orange", "l": "T2"},
28 def load_trajectory(fname):
29 """Load trajectory from file.
32 fname -- The file name.
35 raise ValueError("File name as argument needed")
36 with open(fname, "r") as f:
37 trajectory = loads(f.read())
40 def load_trajectories(dname):
41 """Load trajectories from directory.
44 dname -- The directory name.
47 raise ValueError("Directory name as argument needed")
49 for f in listdir(dname):
50 trajectories.append(load_trajectory("{}/{}".format(dname, f)))
54 """Plot graph. Template."""
55 plt.rcParams["font.size"] = 24
57 ax = fig.add_subplot(111)
58 #ax.set_aspect("equal")
60 #ax.set_title("TITLE")
61 #ax.set_xlabel("Time [s]")
62 #ax.set_ylabel("YLABEL")
66 #plt.plot(xcoords, ycoords, color="blue", label="LABEL")
67 #plt.hist(vals) # log=?, range=[?], bins=?
68 #ax.bar(xvals, yvals) # width=?
69 #ax.set_xticklabels(xvals, rotation=90)
72 #plt.savefig("WHATEVER")
74 def mean_conf_int(data, conf=0.95):
75 """Return (mean, lower, uppper) of data.
77 see https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data
80 data -- A list of data.
81 conf -- Confidence interval.
87 h = se * ss.t.ppf((1 + conf) / 2, n - 1)
88 return (m, m - h, m + h)
90 def count_if_exist(trajectories, what):
91 """From multiple trajectories compute the number of occurences.
94 trajectories -- The list of trajectories.
95 what -- Number of occurences of what to compute.
98 for t in trajectories:
106 def get_lasts_if_exist(trajectories, what):
107 """From multiple trajectories get the list of last values.
110 trajectories -- The list of trajectories.
111 what -- The last values of what to take.
114 for t in trajectories:
116 val.append(t[what][-1])
121 def get_maxs_if_exist(trajectories, what):
122 """From multiple trajectories get the list of maximum values.
125 trajectories -- The list of trajectories.
126 what -- The maximum values of what to take.
129 for t in trajectories:
131 val.append(max(t[what]))
136 def get_val_if_exist(trajectories, what):
137 """From m ultiple trajectories get value.
140 trajectories -- The list of trajectories.
141 what -- What to take.
144 for t in trajectories:
152 """Plot distribution of last costs across measured tests."""
155 v[a] = get_lasts_if_exist(r[a], "cost")
158 ax = fig.add_subplot(111)
159 ax.set_title("Path cost histogram")
161 ax.set_ylabel("Number of paths with given cost [-]")
162 ax.set_xlabel("Path cost [m]")
174 X_WHERE = np.percentile(v[a["f"]], [95])
175 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
183 """Plot time of the last traj (the maximum time)."""
186 v[a] = get_lasts_if_exist(r[a], "secs")
189 ax = fig.add_subplot(111)
190 ax.set_title("Histogram of time to find the path")
192 ax.set_ylabel("Number of paths found [-]")
193 ax.set_xlabel("Algorithm computation time [s]")
201 bins = np.arange(0, 10, 0.1),
205 X_WHERE = np.percentile(v[a["f"]], [95])
206 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
213 def plot_nothingdone():
214 """Plot *nothing done* time of ``overlaptrees`` procedure."""
217 v[a] = get_lasts_if_exist(r[a], "nodo")
220 ax = fig.add_subplot(111)
221 ax.set_title("Histogram of nothing-done-time")
223 ax.set_ylabel("Occurences [-]")
224 ax.set_xlabel("Nothing-done-time percentage [-]")
231 bins = np.arange(0, 1, 0.1),
235 X_WHERE = np.percentile(v[a["f"]], [95])
236 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
243 def print_nofnodes():
244 """Print average number of nodes."""
247 lasts = get_lasts_if_exist(r[a], "node")
248 v[a] = np.average(lasts)
250 print("Average number of nodes:")
252 print("{}: {}".format(a["f"], v[a["f"]]))
254 def print_successrate():
255 """Print success rate of implementations."""
258 v[a] = (100.0 * count_if_exist(r[a], "traj") /
259 count_if_exist(r[a], "elap"))
261 print("Success rate:")
263 print("{}: {}".format(a["f"], v[a["f"]]))
265 if __name__ == "__main__":
266 plt.rcParams["font.size"] = 29
268 LOGF = "log-slotplanner"
269 for d in listdir(LOGF):
271 for sf in [i["f"] for i in LOG]:
272 r[sf] = load_trajectories("{}/{}/{}".format(LOGF, d, sf))
275 "elap": get_val_if_exist(r["T2"], "elap"),
276 "rrte": get_val_if_exist(r["T2"], "rrte"),
277 "ppse": get_val_if_exist(r["T2"], "ppse"),
279 count_if_exist(r["T2"], "traj") /
280 count_if_exist(r["T2"], "elap")
285 for d in listdir(LOGF):
287 for sf in [i["f"] for i in LOG]:
288 r[sf] = load_trajectories("{}/{}/{}".format(LOGF, d, sf))
291 "elap": get_val_if_exist(r["T2"], "elap"),
292 "rrte": get_val_if_exist(r["T2"], "rrte"),
293 "ppse": get_val_if_exist(r["T2"], "ppse"),
295 count_if_exist(r["T2"], "traj") /
296 count_if_exist(r["T2"], "elap")
302 # see https://github.com/vega/vega/wiki/Scales#scale-range-literals
303 ax = fig.add_subplot(111)
304 ax.set_title("""Elapsed time for different lengths
305 of parallel parking slot""")
307 ax.set_ylabel("Time [s]")
308 ax.set_xlabel("Parking slot length [m]")
311 coord = [float(r["f"].split("_")[1]) for r in res]
313 #val = [sum(r["ppse"])/len(r["ppse"]) for r in res]
314 #fin = [(x, y) for (x, y) in zip(coord, val)]
317 # [x for (x, y) in fin],
318 # [y for (x, y) in fin],
320 # label = "Slot Planner",
323 val = [max(r["elap"]) for r in res]
324 fin = [(x, y) for (x, y) in zip(coord, val)]
327 [x for (x, y) in fin],
328 [y for (x, y) in fin],
331 label = "Elapsed worst",
334 #val = [sum(r["rrte"])/len(r["rrte"]) for r in res]
335 #fin = [(x, y) for (x, y) in zip(coord, val)]
338 # [x for (x, y) in fin],
339 # [y for (x, y) in fin],
344 val = [sum(r["elap"])/len(r["elap"]) for r in res]
345 fin = [(x, y) for (x, y) in zip(coord, val)]
348 [x for (x, y) in fin],
349 [y for (x, y) in fin],
351 label = "Elapsed average",
354 val = [r["succ"] for r in res]
355 fin = [(x, y) for (x, y) in zip(coord, val)]
358 [x for (x, y) in fin],
359 [y for (x, y) in fin],
362 label = "Success rate",
366 coord = [float(r["f"].split("_")[1]) for r in res2]
368 val = [max(r["elap"]) for r in res2]
369 fin = [(x, y) for (x, y) in zip(coord, val)]
372 [x for (x, y) in fin],
373 [y for (x, y) in fin],
376 label = "Elapsed worst",
379 val = [sum(r["elap"])/len(r["elap"]) for r in res2]
380 fin = [(x, y) for (x, y) in zip(coord, val)]
383 [x for (x, y) in fin],
384 [y for (x, y) in fin],
386 label = "Elapsed average",
389 val = [r["succ"] for r in res2]
390 fin = [(x, y) for (x, y) in zip(coord, val)]
393 [x for (x, y) in fin],
394 [y for (x, y) in fin],
397 label = "Success rate",
400 plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0)