]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/scenario.py
FIX 8ce842d
[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 load(fname):
22     """Load scenario from file.
23
24     Keyword arguments:
25     fname -- File name.
26     """
27     if fname is None:
28         raise ValueError("File name as argument needed")
29     with open(fname, "r") as f:
30         try:
31             scenario = loads(f.read())
32         except:
33             scenario = {"error": "Bad JSON format."}
34     return scenario
35
36 def load_dir(dname=DNAME):
37     """Load scenarios from directory.
38
39     Keyword arguments:
40     dname -- Directory name.
41     """
42     if dname is None:
43         raise ValueError("Directory name as argument needed")
44     scenarios = []
45     for d in listdir(dname):
46         for f in listdir("{}/{}".format(dname, d)):
47             s = load("{}/{}/{}".format(dname, d, f))
48             s["dname"] = dname
49             s["subdname"] = d
50             s["fname"] = f.split(".")[0]
51             scenarios.append(s)
52     return scenarios
53
54 def grep_all(what="time"):
55     """Return the dictionary of ``fname``'s and corresponding list of values.
56
57     If ``what`` not present, use ``-1`` instead.
58
59     Keyword arguments:
60     what -- What to filter.
61     """
62     filtered = {}
63     scenarios = load_dir(DNAME)
64     for s in scenarios:
65         if s["fname"] not in filtered:
66             filtered[s["fname"]] = []
67         if what in s:
68             filtered[s["fname"]].append(s[what])
69         else:
70             filtered[s["fname"]].append(-1)
71     return filtered
72
73 def grep(what="time"):
74     """Return the dictionary of ``fname``'s and corresponding list of values.
75
76     Keyword arguments:
77     what -- What to filter.
78     """
79     filtered = {}
80     scenarios = load_dir(DNAME)
81     for s in scenarios:
82         if s["fname"] not in filtered:
83             filtered[s["fname"]] = []
84         if what in s:
85             filtered[s["fname"]].append(s[what])
86     return filtered