]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - gplot.py
Add get val function 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 # 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 get_val_if_exist(trajectories, what):
126     """From m ultiple trajectories get value.
127
128     Keyword arguments:
129     trajectories -- The list of trajectories.
130     what -- What to take.
131     """
132     val = []
133     for t in trajectories:
134         try:
135             val.append(t[what])
136         except:
137             pass
138     return val
139
140 def plot_costdist():
141     """Plot distribution of last costs across measured tests."""
142     v = {}
143     for a in r.keys():
144         v[a] = get_lasts_if_exist(r[a], "cost")
145
146     fig = plt.figure()
147     ax = fig.add_subplot(111)
148     ax.set_title("Path cost histogram")
149
150     ax.set_ylabel("Number of paths with given cost [-]")
151     ax.set_xlabel("Path cost [m]")
152     ax.set_yscale("log")
153
154     for a in LOG:
155         plt.hist(
156                 v[a["f"]],
157                 alpha = 0.5,
158                 label = a["l"],
159                 bins = 100,
160                 histtype = "step",
161                 color = a["c"])
162         try:
163                 X_WHERE = np.percentile(v[a["f"]], [95])
164                 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
165         except:
166                 pass
167
168     plt.legend()
169     plt.show()
170
171 def plot_maxtime():
172     """Plot time of the last traj (the maximum time)."""
173     v = {}
174     for a in r.keys():
175         v[a] = get_lasts_if_exist(r[a], "secs")
176
177     fig = plt.figure()
178     ax = fig.add_subplot(111)
179     ax.set_title("Histogram of time to find the path")
180
181     ax.set_ylabel("Number of paths found [-]")
182     ax.set_xlabel("Algorithm computation time [s]")
183     ax.set_yscale("log")
184
185     for a in LOG:
186         plt.hist(
187                 v[a["f"]],
188                 alpha = 0.5,
189                 label = a["l"],
190                 bins = np.arange(0, 10, 0.1),
191                 histtype = "step",
192                 color = a["c"])
193         try:
194                 X_WHERE = np.percentile(v[a["f"]], [95])
195                 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
196         except:
197                 pass
198
199     plt.legend()
200     plt.show()
201
202 def plot_nothingdone():
203     """Plot *nothing done* time of ``overlaptrees`` procedure."""
204     v = {}
205     for a in r.keys():
206         v[a] = get_lasts_if_exist(r[a], "nodo")
207
208     fig = plt.figure()
209     ax = fig.add_subplot(111)
210     ax.set_title("Histogram of nothing-done-time")
211
212     ax.set_ylabel("Occurences [-]")
213     ax.set_xlabel("Nothing-done-time percentage [-]")
214
215     for a in LOG:
216         plt.hist(
217                 v[a["f"]],
218                 alpha = 0.5,
219                 label = a["l"],
220                 bins = np.arange(0, 1, 0.1),
221                 histtype = "step",
222                 color = a["c"])
223         try:
224                 X_WHERE = np.percentile(v[a["f"]], [95])
225                 plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
226         except:
227                 pass
228
229     plt.legend()
230     plt.show()
231
232 def print_nofnodes():
233     """Print average number of nodes."""
234     v={}
235     for a in r.keys():
236         lasts = get_lasts_if_exist(r[a], "node")
237         v[a] = np.average(lasts)
238
239     print("Average number of nodes:")
240     for a in LOG:
241         print("{}: {}".format(a["f"], v[a["f"]]))
242
243 def print_successrate():
244     """Print success rate of implementations."""
245     v={}
246     for a in r.keys():
247         v[a] = (100.0 * count_if_exist(r[a], "traj") /
248                 count_if_exist(r[a], "elap"))
249
250     print("Success rate:")
251     for a in LOG:
252         print("{}: {}".format(a["f"], v[a["f"]]))
253
254 if __name__ == "__main__":
255     plt.rcParams["font.size"] = 29
256     r = {}
257     for sf in [i["f"] for i in LOG]:
258         r[sf] = load_trajectories("{}/{}".format(LOGF, sf))
259     print_successrate()
260     plot_maxtime()
261     plot_costdist()