]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/plot.py
Fix init in plot json scenario script
[hubacji1/iamcar2.git] / scripts / plot.py
1 """Procedures for plotting graphs."""
2 import sys
3 import matplotlib.pyplot as plt
4 import numpy as np
5
6 import scenario
7
8 def boxplot(w={}, t="", yl=None, lx="Elapsed time [s]", ly=""):
9     """Plot boxplot graph.
10
11     Keyword arguments:
12     w -- What to plot.
13     t -- Graph title.
14     yl -- Y axis limit [min, max].
15     """
16     f, ax = plt.subplots()
17
18     if False: # is the y axis log scale?
19         ax.set_title("{} -- {} (log yscale)".format(scenario.SNAME, t))
20         ax.set_yscale("log")
21     else:
22         ax.set_title("{} -- {}".format(scenario.SNAME, t))
23
24     ax.set_xlabel(lx)
25     ax.set_ylabel(ly)
26
27     ax.boxplot([v for k, v in w.items()], labels=[k for k, v in w.items()])
28     ax.minorticks_on()
29     ax.grid(
30         which="major",
31         axis="y",
32         linestyle="-",
33         linewidth="0.5",
34         color="gray",
35     )
36     ax.grid(
37         which="minor",
38         axis="y",
39         linestyle=":",
40         linewidth="0.5",
41         color="gray",
42     )
43     if yl:
44         ax.set_ylim(yl)
45     plt.xticks(rotation=45)
46     plt.savefig("out.eps", bbox_inches="tight")
47     plt.close()
48
49 def boxplots(w2=[]):
50     """Plot boxplot for multiple times.
51
52     Keyword arguments:
53     w -- What to plot. It is extracted from `w2`.
54     """
55     f, ax = plt.subplots()
56
57     [w, no_opt] = w2
58
59     key = tuple(w.keys())[0]
60     ax.set_title("Final path cost, Out-of-Slot Planner, scenario 5-1".format(key))
61     ax.set_xlabel("Elapsed time [s]")
62     ax.set_ylabel("Cost [m]")
63
64     err_hist = [0 for i in range(19)]
65     val_list = [[] for i in range(19)]
66     m = len(w[key][0])
67     mi = 999999999999
68     ma = -1
69     for i in range(len(w[key])):
70         for j in range(m):
71             if w[key][i][j] == 0:
72                 err_hist[j] += 1
73             else:
74                 v = w[key][i][j]
75                 val_list[j].append(v)
76                 if v < mi: mi = v
77                 if v > ma: ma = v
78     print("min: {}, max: {}".format(mi, ma))
79
80     maxes = [max(val_list[i]) for i in range(19)]
81     mins = [min(val_list[i]) for i in range(19)]
82     average = [np.average(val_list[i]) for i in range(19)]
83     # 95 and 5 are not used
84     perct_95 = [np.percentile(val_list[i], [95])[0] for i in range(19)]
85     perct_5 = [np.percentile(val_list[i], [5])[0] for i in range(19)]
86     # percentiles by 10 %
87     perct_10 = [np.percentile(val_list[i], [10])[0] for i in range(19)]
88     perct_20 = [np.percentile(val_list[i], [20])[0] for i in range(19)]
89     perct_30 = [np.percentile(val_list[i], [30])[0] for i in range(19)]
90     perct_40 = [np.percentile(val_list[i], [40])[0] for i in range(19)]
91     perct_50 = [np.percentile(val_list[i], [50])[0] for i in range(19)]
92     perct_60 = [np.percentile(val_list[i], [60])[0] for i in range(19)]
93     perct_70 = [np.percentile(val_list[i], [70])[0] for i in range(19)]
94     perct_80 = [np.percentile(val_list[i], [80])[0] for i in range(19)]
95     perct_90 = [np.percentile(val_list[i], [90])[0] for i in range(19)]
96
97     # find index of the closest to average path
98     average_i = [
99         (i, w[key][i][-1])
100         for i in range(len(w[key]))
101     ]
102     average_i = sorted(average_i, key=lambda i: i[1])
103     # this is for figures to the paper
104     print("min: {}".format(average_i[0]))
105     print("max: {}".format(average_i[-1]))
106     print("diff: {}".format(abs(average_i[0][1] - average_i[-1][1])))
107
108     # plot percentiles
109     ax.fill_between(
110         range(1, 20),
111         mins,
112         maxes,
113         color="tab:orange",
114         alpha=0.2,
115         label="Minimum and maximum, optimized",
116     )
117     ax.fill_between(
118         range(1, 20),
119         perct_10,
120         perct_90,
121         color="tab:orange",
122         alpha=0.25,
123         label="10 % and 90 % percentile, optimized",
124     )
125     ax.fill_between(
126         range(1, 20),
127         perct_20,
128         perct_80,
129         color="tab:orange",
130         alpha=0.3,
131         label="20 % and 80 % percentile, optimized",
132     )
133     ax.fill_between(
134         range(1, 20),
135         perct_30,
136         perct_70,
137         color="tab:orange",
138         alpha=0.35,
139         label="30 % and 70 % percentile, optimized",
140     )
141     ax.fill_between(
142         range(1, 20),
143         perct_40,
144         perct_60,
145         color="tab:orange",
146         alpha=0.4,
147         label="40 % and 60 % percentile, optimized",
148     )
149     # plot median and average
150     ax.plot(
151         range(1, 20),
152         perct_50,
153         color="tab:orange",
154         alpha=1,
155         label="50 % percentile (median), optimized",
156     )
157     ax.plot(
158         range(1, 20),
159         average,
160         color="tab:red",
161         alpha=1,
162         label="Average cost after optimization",
163     )
164     # plot average before path optimization
165     ax.plot(
166         range(1, 20),
167         [np.average([i for i in no_opt[key].values()]) for i in range(1, 20)],
168         label="Average cost before optimization",
169         color="tab:blue",
170         linestyle="--",
171     )
172
173     plt.xticks(range(1, 20), ["{:.2f}".format(0.1 * (k+1)) for k in range(m)])
174     ax.minorticks_on()
175
176     plt.rcParams["font.size"] = 21
177     plt.rcParams['hatch.linewidth'] = 1.0
178     plt.rcParams['lines.linewidth'] = 1.0
179     plt.legend()
180     plt.xticks(rotation=45)
181     plt.savefig("out.pdf", bbox_inches="tight")
182     plt.close()
183
184 def barplot(wl=[], t="", yl=None, lx="Entry Point Planner variant [-]", ly=""):
185     """Plot barplot graph.
186
187     Keyword arguments:
188     wl -- What to plot list.
189     t -- Graph title.
190     yl -- Y axis limit [min, max].
191     """
192     if len(wl) < 1:
193         raise ValueError
194     elif len(wl) == 1:
195         wl.append([])
196     f, ax = plt.subplots()
197     ax.set_title(t)
198     ax.set_xlabel(lx)
199     ax.set_ylabel(ly)
200     w = wl[0]
201     ax.bar(
202         range(len(w)),
203         [v for k, v in w.items()],
204         tick_label=[k for k, v in w.items()],
205         width=1 / (len(wl) + 1),
206     )
207     for i in range(1, len(wl) - 1):
208         w = wl[i]
209         ax.bar(
210             [j + i * 1/len(wl) for j in range(len(w))],
211             [v for k, v in w.items()],
212             width=1 / (len(wl) + 1),
213         )
214     ax.minorticks_on()
215     ax.grid(
216         which="major",
217         axis="y",
218         linestyle="-",
219         linewidth="0.5",
220         color="gray"
221     )
222     ax.grid(
223         which="minor",
224         axis="y",
225         linestyle=":",
226         linewidth="0.5",
227         color="gray",
228     )
229     if yl:
230         ax.set_ylim(yl)
231     plt.xticks(rotation=45)
232     plt.savefig("out.eps", bbox_inches="tight")
233     plt.close()
234
235 def histplot(w={}, t="", lx="Algorithm computation time [s]", ly="Number of paths found [-]"):
236     """Plot histogram graph.
237
238     Keyword arguments:
239     w -- What to plot.
240     t -- Graph title.
241     """
242     f, ax = plt.subplots()
243     ax.set_title("{} (log yscale)".format(t))
244     ax.set_yscale("log")
245     ax.set_xlim(-10, 500)
246     ax.set_xlabel(lx)
247     ax.set_ylabel(ly)
248
249     COLORS = ["tab:orange", "tab:red", "tab:blue", "tab:green"]
250     i = 0
251
252     for ck, cv in w.items():
253         ax.hist(
254             [v for k, v in w.items() if k == ck],
255             #alpha = 0.5,
256             histtype = "step",
257             #bins = 30,
258             color=COLORS[i]
259         )
260         X_WHERE = np.percentile([v for k, v in w.items() if k == ck], [95])
261         print("percentile is {}".format(X_WHERE))
262         plt.axvline(X_WHERE, lw=1, linestyle="--", color=COLORS[i])
263         i += 1
264
265     ax.minorticks_on()
266     ax.grid(
267         which="major",
268         axis="y",
269         linestyle="-",
270         linewidth="0.5",
271         color="gray",
272     )
273     ax.grid(
274         which="minor",
275         axis="y",
276         linestyle=":",
277         linewidth="0.5",
278         color="gray",
279     )
280     plt.legend([k for k, v in w.items()])
281     plt.xticks(rotation=45)
282     plt.savefig("out.eps", bbox_inches="tight")
283     plt.close()
284
285 if __name__ == "__main__":
286     if len(sys.argv) > 1:
287         w = sys.argv[1]
288     else:
289         w = "time"
290     if len(sys.argv) > 2:
291         scenario.DNAME = sys.argv[2]
292
293     plt.rcParams["font.size"] = 22
294     plt.rcParams["font.family"] = "sans-serif"
295     plt.rcParams["figure.figsize"] = [12, 12]
296
297     if w == "time":
298         boxplot(scenario.time(), "Elapsed time", yl=[0.0004, 200], ly="Time [s]")
299     elif w == "htime":
300         histplot(scenario.time(), "Histogram of time to find a path")
301     elif w == "cost":
302         boxplot(scenario.cost(), "Final path cost", yl=[0, 80], ly="Cost [m]")
303     elif w == "costs":
304         boxplots(scenario.costs())
305     elif w == "hcost":
306         histplot(scenario.cost(), "Final path cost histogram")
307     elif w == "orig_cost":
308         boxplot(scenario.orig_cost(), "Original path cost", yl=[0, 80], ly="Cost [m]")
309     elif w == "orig_hcost":
310         histplot(scenario.orig_cost(), "Original path cost histogram")
311     elif w == "cusp":
312         boxplot(scenario.cusp(), "Changes in direction", ly="Changes [-]")
313     elif w == "hcusp":
314         histplot(scenario.cusp(), "Changes in direction histogram")
315     elif w == "error":
316         barplot(
317             scenario.error_rate(),
318             "Path not found rate",
319             ly="Path not found [%]",
320         )
321     elif w == "iter":
322         boxplot(
323             scenario.iter(),
324             "Number of iterations",
325             yl=[1, 1000],
326             ly="Iterations [-]",
327         )
328     else:
329         print("""The following arguments are allowed:
330
331         time, htime, cost, hcost, cusp, hcusp, error, iter
332         """)