]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - gplot.py
Widen parallel parking scenarios
[hubacji1/iamcar.git] / gplot.py
1 # -*- coding: utf-8 -*-
2 """This module contain functions to ease graph plots."""
3 from json import loads
4 from matplotlib import pyplot as plt
5 from os import listdir
6 from sys import argv, exit
7 import numpy as np
8 import scipy.stats as ss
9
10 # ed - euclidean distance
11 # rs - reeds and shepp path length
12 # sh - reeds and shepp, same heading
13
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
20
21 LOGF = "log_wo"
22 LOG = [
23     {"f": "T2", "c": "orange", "l": "T2"},
24 ]
25
26 r = {}
27
28 def load_trajectory(fname):
29     """Load trajectory from file.
30
31     Keyword arguments:
32     fname -- The file name.
33     """
34     if fname is None:
35         raise ValueError("File name as argument needed")
36     with open(fname, "r") as f:
37         trajectory = loads(f.read())
38         return trajectory
39
40 def load_trajectories(dname):
41     """Load trajectories from directory.
42
43     Keyword arguments:
44     dname -- The directory name.
45     """
46     if dname is None:
47         raise ValueError("Directory name as argument needed")
48     trajectories = []
49     for f in listdir(dname):
50         trajectories.append(load_trajectory("{}/{}".format(dname, f)))
51     return trajectories
52
53 def gplot():
54     """Plot graph. Template."""
55     plt.rcParams["font.size"] = 24
56     fig = plt.figure()
57     ax = fig.add_subplot(111)
58     #ax.set_aspect("equal")
59     #ax.set_yscale("log")
60     #ax.set_title("TITLE")
61     #ax.set_xlabel("Time [s]")
62     #ax.set_ylabel("YLABEL")
63     #ax.set_xlim(0, 100)
64     #ax.set_ylim(0, 100)
65
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)
70
71     plt.show()
72     #plt.savefig("WHATEVER")
73
74 def mean_conf_int(data, conf=0.95):
75     """Return (mean, lower, uppper) of data.
76
77     see https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data
78
79     Keyword arguments:
80     data -- A list of data.
81     conf -- Confidence interval.
82     """
83     a = np.array(data)
84     n = len(a)
85     m = np.mean(a)
86     se = ss.sem(a)
87     h = se * ss.t.ppf((1 + conf) / 2, n - 1)
88     return (m, m - h, m + h)
89
90 def count_if_exist(trajectories, what):
91     """From multiple trajectories compute the number of occurences.
92
93     Keyword arguments:
94     trajectories -- The list of trajectories.
95     what -- Number of occurences of what to compute.
96     """
97     occ = 0
98     for t in trajectories:
99         try:
100             if t[what]:
101                 occ += 1
102         except:
103             pass
104     return occ
105
106 def get_lasts_if_exist(trajectories, what):
107     """From multiple trajectories get the list of last values.
108
109     Keyword arguments:
110     trajectories -- The list of trajectories.
111     what -- The last values of what to take.
112     """
113     val = []
114     for t in trajectories:
115         try:
116             val.append(t[what][-1])
117         except:
118             pass
119     return val
120
121 def get_maxs_if_exist(trajectories, what):
122     """From multiple trajectories get the list of maximum values.
123
124     Keyword arguments:
125     trajectories -- The list of trajectories.
126     what -- The maximum values of what to take.
127     """
128     val = []
129     for t in trajectories:
130         try:
131             val.append(max(t[what]))
132         except:
133             pass
134     return val
135
136 def get_val_if_exist(trajectories, what):
137     """From m ultiple trajectories get value.
138
139     Keyword arguments:
140     trajectories -- The list of trajectories.
141     what -- What to take.
142     """
143     val = []
144     for t in trajectories:
145         try:
146             val.append(t[what])
147         except:
148             pass
149     return val
150
151 def plot_costdist():
152     """Plot distribution of last costs across measured tests."""
153     v = {}
154     for a in r.keys():
155         v[a] = get_lasts_if_exist(r[a], "cost")
156
157     fig = plt.figure()
158     ax = fig.add_subplot(111)
159     ax.set_title("Path cost histogram")
160
161     ax.set_ylabel("Number of paths with given cost [-]")
162     ax.set_xlabel("Path cost [m]")
163     ax.set_yscale("log")
164
165     for a in LOG:
166         plt.hist(
167                 v[a["f"]],
168                 alpha = 0.5,
169                 label = a["l"],
170                 bins = 100,
171                 histtype = "step",
172                 color = a["c"])
173         try:
174                 X_WHERE = np.percentile(v[a["f"]], [95])
175                 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
176         except:
177                 pass
178
179     plt.legend()
180     plt.show()
181
182 def plot_maxtime():
183     """Plot time of the last traj (the maximum time)."""
184     v = {}
185     for a in r.keys():
186         v[a] = get_lasts_if_exist(r[a], "secs")
187
188     fig = plt.figure()
189     ax = fig.add_subplot(111)
190     ax.set_title("Histogram of time to find the path")
191
192     ax.set_ylabel("Number of paths found [-]")
193     ax.set_xlabel("Algorithm computation time [s]")
194     ax.set_yscale("log")
195
196     for a in LOG:
197         plt.hist(
198                 v[a["f"]],
199                 alpha = 0.5,
200                 label = a["l"],
201                 bins = np.arange(0, 10, 0.1),
202                 histtype = "step",
203                 color = a["c"])
204         try:
205                 X_WHERE = np.percentile(v[a["f"]], [95])
206                 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
207         except:
208                 pass
209
210     plt.legend()
211     plt.show()
212
213 def plot_nothingdone():
214     """Plot *nothing done* time of ``overlaptrees`` procedure."""
215     v = {}
216     for a in r.keys():
217         v[a] = get_lasts_if_exist(r[a], "nodo")
218
219     fig = plt.figure()
220     ax = fig.add_subplot(111)
221     ax.set_title("Histogram of nothing-done-time")
222
223     ax.set_ylabel("Occurences [-]")
224     ax.set_xlabel("Nothing-done-time percentage [-]")
225
226     for a in LOG:
227         plt.hist(
228                 v[a["f"]],
229                 alpha = 0.5,
230                 label = a["l"],
231                 bins = np.arange(0, 1, 0.1),
232                 histtype = "step",
233                 color = a["c"])
234         try:
235                 X_WHERE = np.percentile(v[a["f"]], [95])
236                 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
237         except:
238                 pass
239
240     plt.legend()
241     plt.show()
242
243 def print_nofnodes():
244     """Print average number of nodes."""
245     v={}
246     for a in r.keys():
247         lasts = get_lasts_if_exist(r[a], "node")
248         v[a] = np.average(lasts)
249
250     print("Average number of nodes:")
251     for a in LOG:
252         print("{}: {}".format(a["f"], v[a["f"]]))
253
254 def print_successrate():
255     """Print success rate of implementations."""
256     v={}
257     for a in r.keys():
258         v[a] = (100.0 * count_if_exist(r[a], "traj") /
259                 count_if_exist(r[a], "elap"))
260
261     print("Success rate:")
262     for a in LOG:
263         print("{}: {}".format(a["f"], v[a["f"]]))
264
265 if __name__ == "__main__":
266     plt.rcParams["font.size"] = 29
267     res = []
268     LOGF = "log-slotplanner"
269     for d in listdir(LOGF):
270         r = {}
271         for sf in [i["f"] for i in LOG]:
272             r[sf] = load_trajectories("{}/{}/{}".format(LOGF, d, sf))
273             res.append({
274                 "f": d,
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"),
278                 "succ": (
279                     count_if_exist(r["T2"], "traj") /
280                         count_if_exist(r["T2"], "elap")
281                 ),
282             })
283     res2 = []
284     LOGF = "log-rrt"
285     for d in listdir(LOGF):
286         r = {}
287         for sf in [i["f"] for i in LOG]:
288             r[sf] = load_trajectories("{}/{}/{}".format(LOGF, d, sf))
289             res2.append({
290                 "f": d,
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"),
294                 "succ": (
295                     count_if_exist(r["T2"], "traj") /
296                         count_if_exist(r["T2"], "elap")
297                 ),
298             })
299
300     fig = plt.figure()
301     # For color scheme
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""")
306
307     ax.set_ylabel("Time [s]")
308     ax.set_xlabel("Parking slot length [m]")
309
310     # res Slot Planner
311     coord = [float(r["f"].split("_")[1]) for r in res]
312
313     #val = [sum(r["ppse"])/len(r["ppse"]) for r in res]
314     #fin = [(x, y) for (x, y) in zip(coord, val)]
315     #fin.sort()
316     #plt.plot(
317     #    [x for (x, y) in fin],
318     #    [y for (x, y) in fin],
319     #    color = "g",
320     #    label = "Slot Planner",
321     #)
322
323     val = [max(r["elap"]) for r in res]
324     fin = [(x, y) for (x, y) in zip(coord, val)]
325     fin.sort()
326     plt.plot(
327         [x for (x, y) in fin],
328         [y for (x, y) in fin],
329         color = "#e6550d",
330         linestyle = "--",
331         label = "Elapsed worst",
332     )
333
334     #val = [sum(r["rrte"])/len(r["rrte"]) for r in res]
335     #fin = [(x, y) for (x, y) in zip(coord, val)]
336     #fin.sort()
337     #plt.plot(
338     #    [x for (x, y) in fin],
339     #    [y for (x, y) in fin],
340     #    color = "#fd8d3c",
341     #    label = "RRT",
342     #)
343
344     val = [sum(r["elap"])/len(r["elap"]) for r in res]
345     fin = [(x, y) for (x, y) in zip(coord, val)]
346     fin.sort()
347     plt.plot(
348         [x for (x, y) in fin],
349         [y for (x, y) in fin],
350         color = "#e6550d",
351         label = "Elapsed average",
352     )
353
354     val = [r["succ"] for r in res]
355     fin = [(x, y) for (x, y) in zip(coord, val)]
356     fin.sort()
357     plt.plot(
358         [x for (x, y) in fin],
359         [y for (x, y) in fin],
360         #color = "#fd8d3c",
361         color = "#fdae6b",
362         label = "Success rate",
363     )
364
365     # res2 RRT
366     coord = [float(r["f"].split("_")[1]) for r in res2]
367
368     val = [max(r["elap"]) for r in res2]
369     fin = [(x, y) for (x, y) in zip(coord, val)]
370     fin.sort()
371     plt.plot(
372         [x for (x, y) in fin],
373         [y for (x, y) in fin],
374         color = "#3182bd",
375         linestyle = "--",
376         label = "Elapsed worst",
377     )
378
379     val = [sum(r["elap"])/len(r["elap"]) for r in res2]
380     fin = [(x, y) for (x, y) in zip(coord, val)]
381     fin.sort()
382     plt.plot(
383         [x for (x, y) in fin],
384         [y for (x, y) in fin],
385         color = "#3182bd",
386         label = "Elapsed average",
387     )
388
389     val = [r["succ"] for r in res2]
390     fin = [(x, y) for (x, y) in zip(coord, val)]
391     fin.sort()
392     plt.plot(
393         [x for (x, y) in fin],
394         [y for (x, y) in fin],
395         #color = "#6baed6",
396         color = "#9ecae1",
397         label = "Success rate",
398     )
399
400     plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0)
401     plt.show()