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