]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/scenario.py
By default, show plotted scenario
[hubacji1/iamcar2.git] / scripts / scenario.py
1 """Procedures for loading, parsing, and processing JSON scenarios.
2
3 The structure of input directory (``dname``) must be the
4 following::
5
6    SCEN_DIR/
7       0/
8          fname1.json
9          fname2.json
10          ...
11       1/
12       2/
13       ...
14
15 """
16 from json import loads
17 from os import listdir
18
19 TITLE = ""
20 DNAME = "/home/jiri/phd/measurements/iamcar2_uniform-dist-sampling"
21 PNAME = [i for i in range(0, 10)]
22 PNAME += [chr(i) for i in range(97, 123)]
23 PNAME = [
24     0,
25     "L1R", "L1E", "L1M", "L1H",
26     "G2R", "G2E", "G2M", "G2H",
27     "T2R", "T2E", "T2M", "T2H",
28     "G3R", "G3E", "G3M", "G3H",
29     "T3R", "T3E", "T3M", "T3H",
30 ]
31 PNAME = [
32     0,
33     "55",
34     #"no", "sc", "gz", "opt", "osp"
35 ]
36
37 def sort_dict(f):
38     """Sort dict returned by ``f``."""
39     def w(*args, **kwargs):
40         d = f(*args, **kwargs)
41         d = {k: v for k, v in sorted(d.items(), key=lambda i: i[0])}
42         return d
43     return w
44
45 def load(fname):
46     """Load scenario from file.
47
48     Keyword arguments:
49     fname -- File name.
50     """
51     if fname is None:
52         raise ValueError("File name as argument needed")
53     with open(fname, "r") as f:
54         try:
55             scenario = loads(f.read())
56         except:
57             scenario = {"error": "Bad JSON format."}
58     return scenario
59
60 def load_dir(dname=DNAME):
61     """Load scenarios from directory.
62
63     Keyword arguments:
64     dname -- Directory name.
65     """
66     if dname is None:
67         raise ValueError("Directory name as argument needed")
68     global TITLE
69     TITLE = dname
70     scenarios = []
71     for d in listdir(dname):
72         for f in listdir("{}/{}".format(dname, d)):
73             s = load("{}/{}/{}".format(dname, d, f))
74             s["dname"] = dname
75             s["subdname"] = d
76             s["fname"] = f.split(".json")[0]
77             scenarios.append(s)
78     return scenarios
79
80 def load_multidir(dname=DNAME):
81     """Load scenarios from directories in ``dname``.
82
83     Keyword arguments:
84     dname -- Directory name.
85     """
86     if dname is None:
87         raise ValueError("Directory name as argument needed")
88     global TITLE
89     TITLE = dname
90     s = []
91     if isinstance(dname, list):
92         for d in dname:
93             s += load_dir(d)
94     else:
95         s = load_dir(dname)
96     return s
97
98 @sort_dict
99 def grep(what="time", grep_all=False):
100     """Return the dictionary of ``fname``'s and corresponding list of values.
101
102     If ``what`` not present, use ``-1`` instead.
103
104     Keyword arguments:
105     what -- What to filter.
106     grep_all -- Add ``-1`` if ``what`` not in scenario.
107     """
108     filtered = {}
109     scenarios = load_multidir(DNAME)
110     for s in scenarios:
111         if s["fname"] not in filtered:
112             filtered[s["fname"]] = []
113         if what in s and s[what] < 9999:
114             filtered[s["fname"]].append(s[what])
115         elif grep_all:
116             filtered[s["fname"]].append(-1)
117     return filtered
118
119 def greps(what="time", grep_all=False):
120     """Return the dictionary of ``fname``'s and corresponding list of values.
121
122     If ``what`` not present, use ``-1`` instead.
123
124     Keyword arguments:
125     what -- What to filter.
126     grep_all -- Add ``-1`` if ``what`` not in scenario.
127     """
128     filtered = {}
129     scenarios = load_multidir(DNAME)
130     for s in scenarios:
131         if s["fname"] not in filtered:
132             filtered[s["fname"]] = {}
133         if what in s:
134             filtered[s["fname"]][int(s["subdname"])] = s[what]
135     return filtered
136
137 def error_rate():
138     """Return the dictionary of ``fname``'s and corresponding error rates."""
139     f = grep("cost", True)
140     e = {}
141     for k, v in f.items():
142         dones = [1 for c in v if c < 9999 and c > 0]
143         e[k] = 100 * (len(v) - len(dones)) / len(v)
144     e2 = {}
145     i = 1
146     for k, v in e.items():
147         e2[PNAME[i]] = v
148         i += 1
149     return [e2]
150
151 def time():
152     """Return the dictionary of ``fname``'s and corresponding times."""
153     r = grep("time")
154     r2 = {}
155     i = 1
156     for k, v in r.items():
157         r2[k] = v
158         i += 1
159     r = grep("otime")
160     for k, v in r.items():
161         if len(v) > 0:
162             r2["opt. {}".format(k)] = v
163     return r2
164
165 def otime():
166     """Return the dictionary of ``fname``'s and corresponding opt. times."""
167     r = grep("otime")
168     r2 = {}
169     i = 1
170     for k, v in r.items():
171         r2[k] = v
172         i += 1
173     return r2
174
175 def cost():
176     """Return the dictionary of ``fname``'s and corresponding costs."""
177     r = grep("cost")
178     r2 = {}
179     i = 1
180     for k, v in r.items():
181         r2[PNAME[i]] = v
182         i += 1
183     return r2
184
185 def costs():
186     """Return the dictionary of ``fname``'s and corresponding costs."""
187     r = greps("log_path_cost")
188     r2 = {}
189     M = 0
190     MV = 0
191     it = {}
192     for k, v in r.items():
193         for k2, v2 in v.items():
194             M = max(M, len(v2))
195     for k, v in r.items():
196         for k2, v2 in v.items():
197             if len(v2) == M:
198                 it[k2] = v2
199             else:
200                 MV = max(MV, M - len(v2))
201                 it[k2] = [0 for i in range(M - len(v2))]
202                 it[k2].extend(v2)
203     r2[PNAME[1]] = it
204     r = greps("path_cost_before_opt")
205     r3 = {}
206     i = 1
207     for k, v in r.items():
208         r3[PNAME[i]] = v
209         i += 1
210     r = greps("iterations")
211     r4 = {}
212     i = 1
213     for k, v in r.items():
214         r4[PNAME[i]] = v
215         i += 1
216     return [r2, r3, r4]
217
218 def orig_cost():
219     """Return the dictionary of ``fname``'s and corresponding orig. costs."""
220     r = grep("orig_path_cost")
221     r2 = {}
222     i = 1
223     for k, v in r.items():
224         r2[PNAME[i]] = v
225         i += 1
226     return r2
227
228 def cusp():
229     """Return the dictionary of ``fname``'s and corresponding cusps."""
230     r = grep("cusps-in-path")
231     r2 = {}
232     i = 1
233     for k, v in r.items():
234         r2[PNAME[i]] = v
235         i += 1
236     return r2
237
238 def orig_cusp():
239     """Return the dictionary of ``fname``'s and corresponding cusps."""
240     r = grep("orig_cusps-in-path")
241     r2 = {}
242     i = 1
243     for k, v in r.items():
244         r2[PNAME[i]] = v
245         i += 1
246     return r2
247
248 def iter():
249     """Return the dictionary of ``fname``'s and number of iterations."""
250     r = grep("iterations")
251     r2 = {}
252     i = 1
253     for k, v in r.items():
254         r2[PNAME[i]] = v
255         i += 1
256     return r2
257
258 def log_path_cost():
259     """Return the dictionary of ``fname``'s and logged path costs."""
260     r = grep("log_path_cost")
261     r2 = {}
262     i = 1
263     for k, v in r.items():
264         r2[PNAME[i]] = v
265         i += 1
266     return r2