]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/plot_cost.py
84d9bc9a965f2e466e77f9f4acb4827b5619f7f3
[hubacji1/iamcar2.git] / scripts / plot_cost.py
1 #!/usr/bin/env python3
2 """Plot scenario's runs cost."""
3 from json import loads
4 from os import listdir
5 from sys import argv, exit
6 import matplotlib.pyplot as plt
7 import numpy as np
8
9 def load(fn=None):
10     """Load scenario from file.
11
12     Keyword arguments
13     -----------------
14
15     - `fn` -- File name.
16     """
17     if fn is None:
18         raise ValueError("File name as argument needed")
19     s = None
20     with open(fn, "r") as f:
21         s = loads(f.read())
22     return s
23
24 def load_dir(dn=None, fn=None):
25     """Load scenarios from directory.
26
27     Keyword arguments
28     -----------------
29
30     - `dn` -- Directory name.
31     """
32     if dn is None:
33         raise ValueError("Directory name as argument needed")
34     scenarios = []
35     for d in listdir(dn):
36         s = load("{}/{}/{}.json".format(dn, d, fn))
37         s["dn"] = dn
38         s["subdn"] = d
39         s["fn"] = fn
40         scenarios.append(s)
41     return scenarios
42
43 def perc(li=[], p=0):
44     return np.percentile(li, p) if len(li) > 0 else p
45
46 if __name__ == "__main__":
47     if len(argv) != 3:
48         print("""Usage: ./plot_cost.py DIR FN
49 Where:
50
51 - DIR is the directory with the results.
52 - FN is the desired test filename.
53 """)
54         exit(1)
55     result_dir = argv[1]
56     test_fn = argv[2]
57     scenarios = load_dir(result_dir, test_fn)
58     L = 1000#len(scenarios[0]["log_path_cost"])
59     err_hist = [0 for i in range(L)]
60     val_list = [[] for i in range(L)]
61     icnt_list = []
62     bcnt_list = []
63     rcnt_list = []
64     time_list = []
65     otime_list = []
66     min_s = 0
67     min_c = 0.0
68     max_s = 0
69     max_c = 0.0
70     for s in scenarios:
71         lpc = s["log_path_cost"]
72         for i in range(L):
73             if lpc[i] == 0:
74                 err_hist[i] += 1
75             else:
76                 val_list[i].append(lpc[i])
77         if min_c == 0.0 or s["goal_cc"] < min_c:
78             min_c = s["goal_cc"]
79             min_s = s["subdn"]
80         if s["goal_cc"] > max_c:
81             max_c = s["goal_cc"]
82             max_s = s["subdn"]
83         try:
84             icnt_list.append(s["icnt"])
85             bcnt_list.append(s["bcnt"])
86             rcnt_list.append(s["rcnt"])
87         except:
88             pass
89         try:
90             time_list.append(s["time"])
91         except:
92             pass
93         try:
94             otime_list.append(s["otime"])
95         except:
96             pass
97     print("{} {}".format(min_s, max_s))
98     icnt_avg = np.average(icnt_list)
99     bcnt_avg = np.average(bcnt_list)
100     rcnt_avg = np.average(rcnt_list)
101     br_avg = np.average([b / r for (b, r) in zip(bcnt_list, rcnt_list)])
102     print("avg. icnt = {}".format(icnt_avg))
103     print("avg. bcnt = {}".format(bcnt_avg))
104     print("avg. rcnt = {}".format(rcnt_avg))
105     print("b/r avg. {}".format(br_avg))
106
107     plt.rcParams["figure.figsize"] = [12, 12]
108     plt.rcParams["font.size"] = 24
109     plt.rcParams["font.family"] = "cmr10"
110     plt.rcParams["hatch.linewidth"] = 1.0
111     plt.rcParams["lines.linewidth"] = 1.0
112     plt.rc('axes', unicode_minus=False)
113
114     f, ax = plt.subplots()
115     eax = ax.twinx()
116     ax.set_title(scenarios[0]["fn"])
117     ax.set_xlabel("Number of iterations [-]")
118     ax.set_ylabel("Cost [m]")
119     eax.set_ylabel("Finished with no path [%]")
120     ax.set_ylim([0, 100])
121     eax.set_ylim([0, 100])
122
123     eax.fill_between(
124         x=range(L),
125         y1=0,
126         y2=[i for i in err_hist],
127         color="tab:red",
128         alpha=0.2,
129         label="No path found",
130     )
131
132     la = [
133         "Minimum and maximum",
134         "10 % and 90 % percentile",
135         "20 % and 80 % percentile",
136         "30 % and 70 % percentile",
137         "40 % and 60 % percentile",
138         "Median",
139     ]
140     for j in range(6):
141         ax.fill_between(
142             x=range(L),
143             y1=[perc(val_list[i], 50 - (5-j)*10) for i in range(L)],
144             y2=[perc(val_list[i], 50 + (5-j)*10) for i in range(L)],
145             color="tab:orange",
146             alpha=0.2 + j*0.05,
147             label=la[j],
148         )
149     ax.plot(
150         range(L),
151         [np.average(val_list[i]) for i in range(L)],
152         color="tab:red",
153         alpha=0.45,
154         label="Average cost",
155     )
156
157     ax.minorticks_on()
158     ax.tick_params(axis='x', labelrotation=45)
159     ax.legend(loc="upper left")
160     eax.legend(loc="upper right")
161     plt.savefig("out.pdf", bbox_inches="tight")
162     plt.close()