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