]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/plot_cost.py
Remove obsolete extension
[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     ncnt_list = []
70     cc_list = []
71     time_list = []
72     otime_list = []
73     min_s = 0
74     min_c = 0.0
75     max_s = 0
76     max_c = 0.0
77     for s in scenarios:
78         lpc = s["costs"]
79         for i in range(L):
80             if len(lpc) <= i:
81                 lpc.append(lpc[-1])
82             if lpc[i] == 0:
83                 err_hist[i] += 1
84             else:
85                 val_list[i].append(lpc[i])
86         if min_c == 0.0 or s["goal_cc"] < min_c:
87             min_c = s["goal_cc"]
88             min_s = s["subdn"]
89         if s["goal_cc"] > max_c:
90             max_c = s["goal_cc"]
91             max_s = s["subdn"]
92         if s["goal_cc"] > 0:
93             cc_list.append(s["goal_cc"])
94         try:
95             icnt_list.append(s["icnt"])
96             bcnt_list.append(s["bcnt"])
97             rcnt_list.append(s["rcnt"])
98             ncnt_list.append(s["ncnt"])
99         except:
100             pass
101         try:
102             time_list.append(s["time"])
103         except:
104             pass
105         try:
106             otime_list.append(s["otime"])
107         except:
108             pass
109     o_err_hist = list(err_hist)
110     err_hist = [i * 100.0 / RUNS if i > 0 else -6 for i in o_err_hist]
111     # this is failure rate
112     w_it = False
113     if w_it:
114         print("Failure {} % in the iteration {}".format(err_hist[w_it], w_it))
115     else:
116         try:
117             print("Failure 0.0 % in the iteration {}".format(err_hist.index(0.0)))
118         except:
119             print("Failure 0.0 % not reached")
120     # --- exit(1)
121     print("{} {}".format(min_s, max_s))
122     icnt_avg = np.average(icnt_list)
123     bcnt_avg = np.average(bcnt_list)
124     rcnt_avg = np.average(rcnt_list)
125     ncnt_avg = np.average(ncnt_list)
126     cc_avg = np.average(cc_list)
127     try:
128         cc_max = np.max(cc_list)
129     except:
130         cc_max = 0
131     time_avg = np.average(time_list)
132     time_max = np.max(time_list)
133     otime_avg = np.average(otime_list)
134     try:
135         otime_max = np.max(otime_list)
136     except:
137         otime_max = 0
138     br_avg = np.average([b / r for (b, r) in zip(bcnt_list, rcnt_list)])
139     print("avg. icnt = {}".format(icnt_avg))
140     print("avg. bcnt = {}".format(bcnt_avg))
141     print("avg. rcnt = {}".format(rcnt_avg))
142     print("avg. ncnt = {}".format(ncnt_avg))
143     print("avg. cc = {}".format(cc_avg))
144     print("max. cc = {}".format(cc_max))
145     print("avg. time = {}".format(time_avg))
146     print("max. time = {}".format(time_max))
147     print("avg. otime = {}".format(otime_avg))
148     print("max. otime = {}".format(otime_max))
149     print("b/r avg. {}".format(br_avg))
150     print("last avg. cost = {}".format(np.average(val_list[-1])))
151     #print("last max. cost = {}".format(perc(val_list[-1], 100)))
152     #exit(1)
153
154     plt.rcParams["figure.figsize"] = [14, 7]
155     plt.rcParams["font.size"] = 24
156     plt.rcParams["font.family"] = "cmr10"
157     plt.rcParams["hatch.linewidth"] = 1.0
158     plt.rcParams["lines.linewidth"] = 1.0
159     plt.rc('axes', unicode_minus=False)
160
161     f, ax = plt.subplots()
162     eax = ax.twinx()
163     ax.grid(which="major", linestyle=":", color="tab:gray")
164     #ax.grid(which="minor", linestyle=":", color="gray")
165     #ax.set_title(scenarios[0]["fn"])
166     #ax.set_title("Scenario 3: Final path cost after optimization")
167     ax.set_xlabel("Number of iterations [-]")
168     ax.set_ylabel("Cost [m]")
169     eax.set_ylabel("Failure rate [%]")
170     #ax.set_ylim([20.1, 57]) # scenario 7
171     #ax.set_ylim([18, 43]) # scenario 2
172     ax.set_ylim([10, 60])
173     eax.set_ylim([-5, 100])
174
175     eax.fill_between(
176         x=range(L),
177         y1=-5,
178         y2=[i for i in err_hist],
179         color="tab:red",
180         alpha=0.2,
181         label="Failure rate",
182     )
183
184     la = [
185         "Min. to max.",
186         "10 - 90 %",
187         "20 - 80 %",
188         "30 - 70 %",
189         "40 - 60 %",
190         #"Median",
191     ]
192     for j in range(5):
193         ax.fill_between(
194             x=range(L),
195             y1=[perc(val_list[i], 50 - (5-j)*10) for i in range(L)],
196             y2=[perc(val_list[i], 50 + (5-j)*10) for i in range(L)],
197             color="tab:orange",
198             alpha=0.2 + j*0.05,
199             label=la[j],
200         )
201     ax.plot(
202         range(L),
203         [np.average(val_list[i]) for i in range(L)],
204         color="tab:blue",
205         alpha=0.45,
206         label="Average cost",
207     )
208
209     ax.minorticks_on()
210     ax.tick_params(axis='x', labelrotation=45)
211     h1, la1 = ax.get_legend_handles_labels()
212     h2, la2 = eax.get_legend_handles_labels()
213
214     h = h1 + h2
215     la = la1 + la2
216
217     ax.legend(h, la, loc="upper right", ncol=1)
218     plt.savefig("out.pdf", bbox_inches="tight")
219     plt.close()