]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blob - gplot.py
Merge branch 'feature/measurement'
[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 seaborn as sns
8
9 def load_trajectory(fname):
10     """Load trajectory from file.
11
12     Keyword arguments:
13     fname -- The file name.
14     """
15     if fname is None:
16         raise ValueError("File name as argument needed")
17     with open(fname, "r") as f:
18         trajectory = loads(f.read())
19         return trajectory
20
21 def load_trajectories(dname):
22     """Load trajectories from directory.
23
24     Keyword arguments:
25     dname -- The directory name.
26     """
27     if dname is None:
28         raise ValueError("Directory name as argument needed")
29     trajectories = []
30     for f in listdir(dname):
31         trajectories.append(load_trajectory("{}/{}".format(dname, f)))
32     return trajectories
33
34 def gplot():
35     """Plot graph."""
36     plt.rcParams["font.size"] = 24
37     fig = plt.figure()
38     ax = fig.add_subplot(111)
39     #ax.set_aspect("equal")
40     #ax.set_yscale("log")
41     #ax.set_title("TITLE")
42     #ax.set_xlabel("Time [s]")
43     #ax.set_ylabel("YLABEL")
44     #ax.set_xlim(0, 100)
45     #ax.set_ylim(0, 100)
46
47     #plt.plot(xcoords, ycoords, color="blue", label="LABEL")
48     #plt.hist(vals) # log=?, range=[?], bins=?
49     #ax.bar(xvals, yvals) # width=?
50     #ax.set_xticklabels(xvals, rotation=90)
51
52     plt.show()
53     #plt.savefig("WHATEVER")
54
55 def count_if_exist(trajectories, what):
56     """From multiple trajectories compute the number of occurences.
57
58     Keyword arguments:
59     trajectories -- The list of trajectories.
60     what -- Number of occurences of what to compute.
61     """
62     occ = 0
63     for t in trajectories:
64         try:
65             if t[what]:
66                 occ += 1
67         except:
68             pass
69     return occ
70
71 def get_lasts_if_exist(trajectories, what):
72     """From multiple trajectories get the list of last values.
73
74     Keyword arguments:
75     trajectories -- The list of trajectories.
76     what -- The last values of what to take.
77     """
78     val = []
79     for t in trajectories:
80         try:
81             val.append(t[what][-1])
82         except:
83             pass
84     return val
85
86 def get_maxs_if_exist(trajectories, what):
87     """From multiple trajectories get the list of maximum values.
88
89     Keyword arguments:
90     trajectories -- The list of trajectories.
91     what -- The maximum values of what to take.
92     """
93     val = []
94     for t in trajectories:
95         try:
96             val.append(max(t[what]))
97         except:
98             val.append(9999)
99     return val
100
101 def plot_successrate():
102     """Plot success rate of single/multi-core implementations."""
103     LOGF="logs_T2st3co2_lpar"
104     LOGSF=["opt0", "opt1"]
105     LEG={
106             "opt0": "T2, st3, co2, no opt",
107             "opt1": "T2, st3, co2, with opt"}
108
109     r={}
110     for sf in LOGSF:
111         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
112
113     v={}
114     for a in r.keys():
115         v[a] = (100 * count_if_exist(r[a], "traj") /
116                 count_if_exist(r[a], "elap"))
117     vs = sorted(v.items(), key=lambda kv: kv[1])
118
119     plt.rcParams["font.size"] = 24
120     fig = plt.figure()
121     ax = fig.add_subplot(111)
122     ax.set_title("Trajectories found in 10 seconds period")
123
124     ax.set_ylabel("Framework tested [-]")
125     ax.set_xlabel("Found successfully [%]")
126     ax.set_xlim(0, 100)
127     ax.set_yticklabels([])
128     j = 0
129     for (k, i) in vs:
130         ax.barh(j, float(i), 4, label=k)
131         j += -5
132     ax.legend()
133
134     plt.show()
135
136 def plot_mintrajcost():
137     """Plot minimum trajectory cost found."""
138     LOGF="logs_inf_sq"
139     ALG=["Karaman2011", "Kuwata2008", "LaValle1998"]
140     ALGT={"Karaman2011": "RRT*",
141             "Kuwata2008": "RRT + heur",
142             "LaValle1998": "RRT"}
143     ST=["3"]
144     STT={"3": "R&S"}
145     CO=["5"]
146     COT={"5": "E2"}
147
148     r={}
149     for a in ALG:
150         for st in ST:
151             for co in CO:
152                 r["{}, {}, {}".format(ALGT[a], STT[st], COT[co])] = (
153                         load_trajectories("{}/{}st{}co{}_lpar".format(
154                             LOGF, a, st, co)))
155
156     v={}
157     for a in r.keys():
158         v[a] = get_lasts_if_exist(r[a], "cost")
159
160     #plt.rcParams["font.size"] = 24
161     fig = plt.figure()
162     for i in range(len(r.keys())):
163         ax = fig.add_subplot(3, 1, i + 1)
164         ax.set_title("Minimum trajectory cost found in 10 seconds (sequential)")
165
166         ax.set_ylabel("Framework tested [-]")
167         ax.set_xlabel("Minimum trajectory cost [m]")
168         #ax.set_yticklabels([])
169
170         plt.bar(range(len(v[r.keys()[i]])), v[r.keys()[i]], label=r.keys()[i])
171
172         ax.legend()
173     plt.show()
174     return
175
176 def plot_costdist():
177     """Plot distribution of last costs across measured tests."""
178     LOGF="logs_T2st3co2_lpar"
179     LOGSF=["opt0", "opt1"]
180     LEG={
181             "opt0": "T2, st3, co2, no opt",
182             "opt1": "T2, st3, co2, with opt"}
183
184     r={}
185     for sf in LOGSF:
186         r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
187
188     v={}
189     for a in r.keys():
190         v[a] = get_lasts_if_exist(r[a], "cost")
191
192     plt.rcParams["font.size"] = 24
193     fig = plt.figure()
194     ax = fig.add_subplot(111)
195     ax.set_title("Trajectories last costs distribution")
196
197     ax.set_ylabel("[-]")
198     ax.set_xlabel("Minimum trajectory cost [m]")
199     ax.set_yticklabels([])
200
201     for a in r.keys():
202         sns.distplot(v[a])
203
204     ax.legend()
205     plt.show()
206
207 if __name__ == "__main__":
208     plot_costdist()