]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/scenario.py
Fix plotting nodes
[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     "T3H",
34 ]
35
36 def sort_dict(f):
37     """Sort dict returned by ``f``."""
38     def w(*args, **kwargs):
39         d = f(*args, **kwargs)
40         d = {k: v for k, v in sorted(d.items(), key=lambda i: i[0])}
41         return d
42     return w
43
44 def load(fname):
45     """Load scenario from file.
46
47     Keyword arguments:
48     fname -- File name.
49     """
50     if fname is None:
51         raise ValueError("File name as argument needed")
52     with open(fname, "r") as f:
53         try:
54             scenario = loads(f.read())
55         except:
56             scenario = {"error": "Bad JSON format."}
57     return scenario
58
59 def load_dir(dname=DNAME):
60     """Load scenarios from directory.
61
62     Keyword arguments:
63     dname -- Directory name.
64     """
65     if dname is None:
66         raise ValueError("Directory name as argument needed")
67     global TITLE
68     TITLE = dname
69     scenarios = []
70     for d in listdir(dname):
71         for f in listdir("{}/{}".format(dname, d)):
72             s = load("{}/{}/{}".format(dname, d, f))
73             s["dname"] = dname
74             s["subdname"] = d
75             s["fname"] = f.split(".json")[0]
76             scenarios.append(s)
77     return scenarios
78
79 def load_multidir(dname=DNAME):
80     """Load scenarios from directories in ``dname``.
81
82     Keyword arguments:
83     dname -- Directory name.
84     """
85     if dname is None:
86         raise ValueError("Directory name as argument needed")
87     global TITLE
88     TITLE = dname
89     s = []
90     if isinstance(dname, list):
91         for d in dname:
92             s += load_dir(d)
93     else:
94         s = load_dir(dname)
95     return s
96
97 @sort_dict
98 def grep(what="time", grep_all=False):
99     """Return the dictionary of ``fname``'s and corresponding list of values.
100
101     If ``what`` not present, use ``-1`` instead.
102
103     Keyword arguments:
104     what -- What to filter.
105     grep_all -- Add ``-1`` if ``what`` not in scenario.
106     """
107     filtered = {}
108     scenarios = load_multidir(DNAME)
109     for s in scenarios:
110         if s["fname"] not in filtered:
111             filtered[s["fname"]] = []
112         if what in s and s[what] < 99999999:
113             filtered[s["fname"]].append(s[what])
114         elif grep_all:
115             filtered[s["fname"]].append(-1)
116     return filtered
117
118 def greps(what="time", grep_all=False):
119     """Return the dictionary of ``fname``'s and corresponding list of values.
120
121     If ``what`` not present, use ``-1`` instead.
122
123     Keyword arguments:
124     what -- What to filter.
125     grep_all -- Add ``-1`` if ``what`` not in scenario.
126     """
127     filtered = {}
128     scenarios = load_multidir(DNAME)
129     for s in scenarios:
130         if s["fname"] not in filtered:
131             filtered[s["fname"]] = {}
132         if what in s:
133             filtered[s["fname"]][int(s["subdname"])] = s[what]
134     return filtered
135
136 def error_rate():
137     """Return the dictionary of ``fname``'s and corresponding error rates."""
138     f = grep("cost", True)
139     e = {}
140     for k, v in f.items():
141         dones = [1 for c in v if c < 9999 and c > 0]
142         e[k] = 100 * (len(v) - len(dones)) / len(v)
143     e2 = {}
144     i = 1
145     for k, v in e.items():
146         e2[PNAME[i]] = v
147         i += 1
148     return [e2]
149
150 def time():
151     """Return the dictionary of ``fname``'s and corresponding times."""
152     r = grep("time")
153     r2 = {}
154     i = 1
155     for k, v in r.items():
156         r2[PNAME[i]] = v
157         i += 1
158     return r2
159
160 def cost():
161     """Return the dictionary of ``fname``'s and corresponding costs."""
162     r = grep("cost")
163     r2 = {}
164     i = 1
165     for k, v in r.items():
166         r2[PNAME[i]] = v
167         i += 1
168     return r2
169
170 def costs():
171     """Return the dictionary of ``fname``'s and corresponding costs."""
172     r = greps("log_path_cost")
173     r2 = {}
174     M = 0
175     MV = 0
176     it = {}
177     for k, v in r.items():
178         for k2, v2 in v.items():
179             M = max(M, len(v2))
180     for k, v in r.items():
181         for k2, v2 in v.items():
182             if len(v2) == M:
183                 it[k2] = v2
184             else:
185                 MV = max(MV, M - len(v2))
186                 it[k2] = [0 for i in range(M - len(v2))]
187                 it[k2].extend(v2)
188     r2[PNAME[1]] = it
189     r = greps("path_cost_before_opt")
190     r3 = {}
191     i = 1
192     for k, v in r.items():
193         r3[PNAME[i]] = v
194         i += 1
195     return [r2, r3]
196
197 def orig_cost():
198     """Return the dictionary of ``fname``'s and corresponding orig. costs."""
199     r = grep("orig_path_cost")
200     r2 = {}
201     i = 1
202     for k, v in r.items():
203         r2[PNAME[i]] = v
204         i += 1
205     return r2
206
207 def cusp():
208     """Return the dictionary of ``fname``'s and corresponding cusps."""
209     r = grep("cusps-in-path")
210     r2 = {}
211     i = 1
212     for k, v in r.items():
213         r2[PNAME[i]] = v
214         i += 1
215     return r2
216
217 def orig_cusp():
218     """Return the dictionary of ``fname``'s and corresponding cusps."""
219     r = grep("orig_cusps-in-path")
220     r2 = {}
221     i = 1
222     for k, v in r.items():
223         r2[PNAME[i]] = v
224         i += 1
225     return r2
226
227 def iter():
228     """Return the dictionary of ``fname``'s and number of iterations."""
229     r = grep("iterations")
230     r2 = {}
231     i = 1
232     for k, v in r.items():
233         r2[PNAME[i]] = v
234         i += 1
235     return r2
236
237 def log_path_cost():
238     """Return the dictionary of ``fname``'s and logged path costs."""
239     r = grep("log_path_cost")
240     r2 = {}
241     i = 1
242     for k, v in r.items():
243         r2[PNAME[i]] = v
244         i += 1
245     return r2