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