]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/print_json_objects_scenaris_data.py
By default, show plotted scenario
[hubacji1/iamcar2.git] / scripts / print_json_objects_scenaris_data.py
1 """Print JSON formatted scenarios time data.
2
3 The structure of input directory (``sys.argv[1]``) 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 math import cos, inf, pi, sin
18 from matplotlib import pyplot as plt
19 from os import listdir
20 from sys import argv, exit
21
22 def get_scenario(fname):
23     """Load scenario from file.
24
25     Keyword arguments:
26     fname -- File name.
27     """
28     if fname is None:
29         raise ValueError("File name as argument needed")
30     with open(fname, "r") as f:
31         try:
32             scenario = loads(f.read())
33         except:
34             scenario = {"error": "Bad JSON format."}
35     return scenario
36
37 def get_scenarios(dname):
38     """Load scenarios from directiory.
39
40     Keyword arguments:
41     dname -- Directory name.
42     """
43     if dname is None:
44         raise ValueError("Directory name as argument needed")
45     s = {}
46     for d in listdir(dname):
47         for f in listdir("{}/{}".format(dname, d)):
48             if f not in s:
49                 s[f] = []
50             s[f].append({
51                 "dn": dname,
52                 "fn": f,
53                 "cnt": int(d),
54                 "sc": get_scenario("{}/{}/{}".format(dname, d, f)),
55             })
56     return s
57
58 def compute_stats(sl={}, what="time"):
59     """Return ``mean``, ``std``, ``med``, ``max``, and ``min`` of ``what``.
60
61     Keyword arguments:
62     sl -- Scenarios list.
63     what -- The variable in scenario stats to compute with.
64     """
65     assert len(sl) > 0
66     wl = [
67         s["sc"][what] for s in sl
68         if "sc" in s
69         and what in s["sc"]
70         and (
71             "cost" in s["sc"]
72             and s["sc"]["cost"] != 9999
73         )
74     ]
75     return wl
76     el = [
77         1 for s in sl
78         if "sc" in s
79         and "cost" in s["sc"]
80         and s["sc"]["cost"] != 9999
81         and s["sc"]["cost"] != -1
82     ]
83     if len(wl) == 0:
84         wl_mean = inf
85         wl_std = inf
86         wl_max = inf
87         wl_min = -inf
88         wl_med = inf
89     else:
90         wl_mean = sum(wl) / len(wl)
91         wl_tmp = [(x - wl_mean)**2 for x in wl]
92         wl_std = (sum(wl_tmp) / len(wl_tmp))**0.5
93         wl_max = max(wl)
94         wl_min = min(wl)
95         wl.sort()
96         wl_med = wl[round(len(wl) / 2)]
97     return {
98         "err": 100 * (len(sl) - len(el)) / len(sl),
99         "avg": wl_mean,
100         "std": wl_std,
101         "med": wl_med,
102         "max": wl_max,
103         "min": wl_min,
104     }
105
106 if __name__ == "__main__":
107     if (len(argv) == 2):
108         SCEN_DIR = argv[1]
109     else:
110         SCEN_DIR = "out"
111     scenarios = get_scenarios(SCEN_DIR)
112     scenarios = sorted(
113         scenarios.items(),
114         key=lambda kv: int(kv[0]) if kv[0].isnumeric() else kv[0]
115     )
116     tres = []
117     cres = []
118     for (f, sl) in scenarios:
119         assert f == sl[0]["fn"]
120         tres.append(compute_stats(sl, "time"))
121         cres.append(compute_stats(sl, "cost"))
122     with open("data_time_{}".format(SCEN_DIR.split("/")[0]), "w") as wf:
123         for i in range(len(tres[0])):
124             l = ""
125             for s in range(len(tres)):
126                 if i < len(tres[s]):
127                     l = "{} {}".format(l, tres[s][i])
128                 else:
129                     l = "{} {}".format(l, 0)
130             l = "{}\n".format(l)
131             wf.write(l)
132     with open("data_cost_{}".format(SCEN_DIR.split("/")[0]), "w") as wf:
133         for i in range(len(cres[0])):
134             l = "{}".format(i)
135             for s in range(len(cres)):
136                 if i < len(cres[s]):
137                     l = "{} {}".format(l, cres[s][i])
138                 else:
139                     l = "{} {}".format(l, 0)
140             l = "{}\n".format(l)
141             wf.write(l)