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