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