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