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