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