]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/scenario.py
Use scenario result when < 9999 only
[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 DNAME = "/home/jiri/phd/measurements/iamcar2_uniform-dist-sampling"
20 PNAME = [i for i in range(0, 10)]
21 PNAME += [chr(i) for i in range(97, 123)]
22
23 def sort_dict(f):
24     """Sort dict returned by ``f``."""
25     def w(*args, **kwargs):
26         d = f(*args, **kwargs)
27         d = {k: v for k, v in sorted(d.items(), key=lambda i: i[0])}
28         return d
29     return w
30
31 def load(fname):
32     """Load scenario from file.
33
34     Keyword arguments:
35     fname -- File name.
36     """
37     if fname is None:
38         raise ValueError("File name as argument needed")
39     with open(fname, "r") as f:
40         try:
41             scenario = loads(f.read())
42         except:
43             scenario = {"error": "Bad JSON format."}
44     return scenario
45
46 def load_dir(dname=DNAME):
47     """Load scenarios from directory.
48
49     Keyword arguments:
50     dname -- Directory name.
51     """
52     if dname is None:
53         raise ValueError("Directory name as argument needed")
54     scenarios = []
55     for d in listdir(dname):
56         for f in listdir("{}/{}".format(dname, d)):
57             s = load("{}/{}/{}".format(dname, d, f))
58             s["dname"] = dname
59             s["subdname"] = d
60             s["fname"] = f.split(".")[0]
61             scenarios.append(s)
62     return scenarios
63
64 def load_multidir(dname=DNAME):
65     """Load scenarios from directories in ``dname``.
66
67     Keyword arguments:
68     dname -- Directory name.
69     """
70     if dname is None:
71         raise ValueError("Directory name as argument needed")
72     s = []
73     if isinstance(dname, list):
74         for d in dname:
75             s += load_dir(d)
76     else:
77         s = load_dir(dname)
78     return s
79
80 @sort_dict
81 def grep(what="time", grep_all=False):
82     """Return the dictionary of ``fname``'s and corresponding list of values.
83
84     If ``what`` not present, use ``-1`` instead.
85
86     Keyword arguments:
87     what -- What to filter.
88     grep_all -- Add ``-1`` if ``what`` not in scenario.
89     """
90     filtered = {}
91     scenarios = load_multidir(DNAME)
92     for s in scenarios:
93         if s["fname"] not in filtered:
94             filtered[s["fname"]] = []
95         if what in s and s[what] < 9999:
96             filtered[s["fname"]].append(s[what])
97         elif grep_all:
98             filtered[s["fname"]].append(-1)
99     return filtered
100
101 def error_rate():
102     """Return the dictionary of ``fname``'s and corresponding error rates."""
103     f = grep("cost", True)
104     e = {}
105     for k, v in f.items():
106         dones = [1 for c in v if c < 9999 and c > -1]
107         e[k] = 100 * (len(v) - len(dones)) / len(v)
108     e2 = {}
109     i = 1
110     for k, v in e.items():
111         e2[PNAME[i]] = v
112         i += 1
113     return [e2]
114
115 def time():
116     """Return the dictionary of ``fname``'s and corresponding times."""
117     r = grep("time")
118     r2 = {}
119     i = 1
120     for k, v in r.items():
121         r2[PNAME[i]] = v
122         i += 1
123     return r2
124
125 def cost():
126     """Return the dictionary of ``fname``'s and corresponding costs."""
127     r = grep("cost")
128     r2 = {}
129     i = 1
130     for k, v in r.items():
131         r2[PNAME[i]] = v
132         i += 1
133     return r2
134
135 def orig_cost():
136     """Return the dictionary of ``fname``'s and corresponding orig. costs."""
137     r = grep("orig_path_cost")
138     r2 = {}
139     i = 1
140     for k, v in r.items():
141         r2[PNAME[i]] = v
142         i += 1
143     return r2
144
145 def cusp():
146     """Return the dictionary of ``fname``'s and corresponding cusps."""
147     r = grep("cusps-in-path")
148     r2 = {}
149     i = 1
150     for k, v in r.items():
151         r2[PNAME[i]] = v
152         i += 1
153     return r2
154
155 def iter():
156     """Return the dictionary of ``fname``'s and number of iterations."""
157     r = grep("iterations")
158     r2 = {}
159     i = 1
160     for k, v in r.items():
161         r2[PNAME[i]] = v
162         i += 1
163     return r2