]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - gplot.py
Add percentiles and colors to gplot
[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
9 def load_trajectory(fname):
10     """Load trajectory from file.
11
12     Keyword arguments:
13     fname -- The file name.
14     """
15     if fname is None:
16         raise ValueError("File name as argument needed")
17     with open(fname, "r") as f:
18         trajectory = loads(f.read())
19         return trajectory
20
21 def load_trajectories(dname):
22     """Load trajectories from directory.
23
24     Keyword arguments:
25     dname -- The directory name.
26     """
27     if dname is None:
28         raise ValueError("Directory name as argument needed")
29     trajectories = []
30     for f in listdir(dname):
31         trajectories.append(load_trajectory("{}/{}".format(dname, f)))
32     return trajectories
33
34 def gplot():
35     """Plot graph."""
36     plt.rcParams["font.size"] = 24
37     fig = plt.figure()
38     ax = fig.add_subplot(111)
39     #ax.set_aspect("equal")
40     #ax.set_yscale("log")
41     #ax.set_title("TITLE")
42     #ax.set_xlabel("Time [s]")
43     #ax.set_ylabel("YLABEL")
44     #ax.set_xlim(0, 100)
45     #ax.set_ylim(0, 100)
46
47     #plt.plot(xcoords, ycoords, color="blue", label="LABEL")
48     #plt.hist(vals) # log=?, range=[?], bins=?
49     #ax.bar(xvals, yvals) # width=?
50     #ax.set_xticklabels(xvals, rotation=90)
51
52     plt.show()
53     #plt.savefig("WHATEVER")
54
55 def count_if_exist(trajectories, what):
56     """From multiple trajectories compute the number of occurences.
57
58     Keyword arguments:
59     trajectories -- The list of trajectories.
60     what -- Number of occurences of what to compute.
61     """
62     occ = 0
63     for t in trajectories:
64         try:
65             if t[what]:
66                 occ += 1
67         except:
68             pass
69     return occ
70
71 def get_lasts_if_exist(trajectories, what):
72     """From multiple trajectories get the list of last values.
73
74     Keyword arguments:
75     trajectories -- The list of trajectories.
76     what -- The last values of what to take.
77     """
78     val = []
79     for t in trajectories:
80         try:
81             val.append(t[what][-1])
82         except:
83             pass
84     return val
85
86 def get_maxs_if_exist(trajectories, what):
87     """From multiple trajectories get the list of maximum values.
88
89     Keyword arguments:
90     trajectories -- The list of trajectories.
91     what -- The maximum values of what to take.
92     """
93     val = []
94     for t in trajectories:
95         try:
96             val.append(max(t[what]))
97         except:
98             pass
99     return val
100
101 def plot_successrate():
102     """Plot success rate of single/multi-core implementations."""
103     LOGF="logs_T2st3co2_lpar"
104     LOGSF=["opt1_nn3", "opt1_nn4", "opt1_nn4_save-heading"]
105     LEG={
106             LOGSF[0]: "RRT* nearest neighbour",
107             LOGSF[1]: "Nearest neighbour heuristics (same heading)",
108             LOGSF[2]: "Nearest neighbour heuristics (save same heading)"}
109
110     r={}
111     for sf in LOGSF:
112         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
113
114     v={}
115     for a in r.keys():
116         v[a] = (100 * count_if_exist(r[a], "traj") /
117                 count_if_exist(r[a], "elap"))
118     vs = sorted(v.items(), key=lambda kv: kv[1])
119
120     plt.rcParams["font.size"] = 24
121     fig = plt.figure()
122     ax = fig.add_subplot(111)
123     ax.set_title("Success rate of trajectories found within 10 seconds limit")
124
125     ax.set_ylabel("Framework tested [-]")
126     ax.set_xlabel("Found successfully [%]")
127     ax.set_xlim(0, 100)
128     ax.set_yticklabels([])
129     j = 0
130     for (k, i) in vs:
131         print("{}: {}%".format(k, i))
132         ax.barh(j, float(i), 4, label=k)
133         j += -5
134     ax.legend()
135
136     plt.show()
137
138 def plot_mintrajcost():
139     """Plot minimum trajectory cost found."""
140     LOGF="logs_inf_sq"
141     ALG=["Karaman2011", "Kuwata2008", "LaValle1998"]
142     ALGT={"Karaman2011": "RRT*",
143             "Kuwata2008": "RRT + heur",
144             "LaValle1998": "RRT"}
145     ST=["3"]
146     STT={"3": "R&S"}
147     CO=["5"]
148     COT={"5": "E2"}
149
150     r={}
151     for a in ALG:
152         for st in ST:
153             for co in CO:
154                 r["{}, {}, {}".format(ALGT[a], STT[st], COT[co])] = (
155                         load_trajectories("{}/{}st{}co{}_lpar".format(
156                             LOGF, a, st, co)))
157
158     v={}
159     for a in r.keys():
160         v[a] = get_lasts_if_exist(r[a], "cost")
161
162     #plt.rcParams["font.size"] = 24
163     fig = plt.figure()
164     for i in range(len(r.keys())):
165         ax = fig.add_subplot(3, 1, i + 1)
166         ax.set_title("Minimum trajectory cost found in 10 seconds (sequential)")
167
168         ax.set_ylabel("Framework tested [-]")
169         ax.set_xlabel("Minimum trajectory cost [m]")
170         #ax.set_yticklabels([])
171
172         plt.bar(range(len(v[r.keys()[i]])), v[r.keys()[i]], label=r.keys()[i])
173
174         ax.legend()
175     plt.show()
176     return
177
178 def plot_costdist():
179     """Plot distribution of last costs across measured tests."""
180     LOGF="logs_T2st3co2_lpar"
181     LOGSF=["opt0_nnedist", "opt2_nnsh", "opt1_nnedist"]
182     LEG={
183             LOGSF[0]: "No path optimization",
184             LOGSF[1]: "RRT*-Smart optimization",
185             LOGSF[2]: "Dijkstra optimization"}
186     COLS={
187             LEG[LOGSF[0]]: "orange",
188             LEG[LOGSF[1]]: "blue",
189             LEG[LOGSF[2]]: "red"}
190
191     r={}
192     for sf in LOGSF:
193         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
194
195     v={}
196     for a in r.keys():
197         v[a] = get_lasts_if_exist(r[a], "cost")
198
199     plt.rcParams["font.size"] = 24
200     fig = plt.figure()
201     ax = fig.add_subplot(111)
202     ax.set_title("Path cost histogram")
203
204     ax.set_ylabel("Number of paths with given cost [-]")
205     ax.set_xlabel("Path cost [m]")
206     ax.set_yscale("log")
207     ax.set_aspect("equal")
208
209     for a in r.keys():
210         plt.hist(v[a], alpha=0.5, label=a, bins=100, histtype="step",
211                 color=COLS[a])
212         X_WHERE = np.percentile(v[a], [95])
213         plt.axvline(X_WHERE, lw=1, color=COLS[a], linestyle="--")
214
215     plt.legend()
216     plt.show()
217
218 def plot_maxtime():
219     """Plot time of the last traj (the maximum time)."""
220     LOGF="logs_T2st3co2_lpar"
221     LOGSF=["opt1_nn3_with-approximate-goal", "opt1_nn4", "opt1_nnedist"]
222     LEG={
223             LOGSF[0]: "RRT* nearest neighbour",
224             LOGSF[1]: "Nearest neighbour with same heading",
225             LOGSF[2]: "Nearest neighbour Euclidean distance"}
226     COLS={
227             LEG[LOGSF[0]]: "orange",
228             LEG[LOGSF[1]]: "blue",
229             LEG[LOGSF[2]]: "red"}
230
231     r={}
232     for sf in LOGSF:
233         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
234
235     v={}
236     for a in r.keys():
237         v[a] = get_lasts_if_exist(r[a], "secs")
238
239     plt.rcParams["font.size"] = 24
240     fig = plt.figure()
241     ax = fig.add_subplot(111)
242     ax.set_title("Path found time histogram")
243
244     ax.set_ylabel("Number of paths found [-]")
245     ax.set_xlabel("Algorithm elapsed time [s]")
246     ax.set_yscale("log")
247     ax.set_aspect("equal")
248
249     for a in r.keys():
250         plt.hist(v[a], alpha=0.5, label=a, bins=np.arange(0, 10, 0.1),
251                 histtype="step", color=COLS[a])
252         X_WHERE = np.percentile(v[a], [95])
253         plt.axvline(X_WHERE, lw=1, color=COLS[a], linestyle="--")
254
255     plt.legend()
256     plt.show()
257
258 def print_nofnodes():
259     """Print average number of nodes."""
260     LOGF="logs_T2st3co2_lpar"
261     LOGSF=["opt1_nn3_with-approximate-goal", "opt1_nn4", "opt1_nnedist"]
262     LEG={
263             LOGSF[0]: "RRT* nearest neighbour",
264             LOGSF[1]: "Nearest neighbour with same heading",
265             LOGSF[2]: "Nearest neighbour Euclidean distance"}
266
267     r={}
268     for sf in LOGSF:
269         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
270
271     v={}
272     for a in r.keys():
273         lasts = get_lasts_if_exist(r[a], "node")
274         v[a] = np.average(lasts)
275
276     print("Average number of points:")
277     for a in r.keys():
278         print("{}: {}".format(a, v[a]))
279
280 def print_successrate():
281     """Print success rate of implementations."""
282     LOGF="logs_T2st3co2_lpar"
283     LOGSF=["opt0_nnedist", "opt2_nnsh", "opt1_nnedist", "opt1_nn4"]
284     LEG={
285             LOGSF[0]: "opt0 nn edist",
286             LOGSF[1]: "opt2 nn same heading",
287             LOGSF[2]: "opt1 nn edist",
288             LOGSF[3]: "opt1 nn same heading"}
289
290     r={}
291     for sf in LOGSF:
292         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
293
294     v={}
295     for a in r.keys():
296         v[a] = (100.0 * count_if_exist(r[a], "traj") /
297                 count_if_exist(r[a], "elap"))
298
299     print("Success rate:")
300     for a in r.keys():
301         print("{}: {}".format(a, v[a]))
302
303 if __name__ == "__main__":
304     plot_costdist()