]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/print_json_objects_scenaris_statistics.py
Merge branch 'feature/refactor-print'
[hubacji1/iamcar2.git] / scripts / print_json_objects_scenaris_statistics.py
1 """Print JSON formatted scenarios statistics.
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                 "fn": f,
52                 "cnt": int(d),
53                 "sc": get_scenario("{}/{}/{}".format(dname, d, f)),
54             })
55     return s
56
57 def compute_stats(sl={}, what="time"):
58     """Return ``mean``, ``std``, ``max``, and ``min`` of ``what``.
59
60     Keyword arguments:
61     sl -- Scenarios list.
62     what -- The variable in scenario stats to compute with.
63     """
64     assert len(sl) > 0
65     wl = [s["sc"][what] for s in sl if "sc" in s and what in s["sc"]]
66     if len(wl) == 0:
67         wl_mean = inf
68         wl_std = inf
69         wl_max = inf
70         wl_min = -inf
71     else:
72         wl_mean = sum(wl) / len(wl)
73         wl_tmp = [(x - wl_mean)**2 for x in wl]
74         wl_std = (sum(wl_tmp) / len(wl_tmp))**0.5
75         wl_max = max(wl)
76         wl_min = min(wl)
77     return {
78         "err": 100 * (len(sl) - len(wl)) / len(sl),
79         "mean": wl_mean,
80         "std": wl_std,
81         "max": wl_max,
82         "min": wl_min,
83     }
84
85 if __name__ == "__main__":
86     if (len(argv) == 2):
87         SCEN_DIR = argv[1]
88     else:
89         SCEN_DIR = "out"
90
91     def gos(h=False):
92         """Generate output string for values.
93
94         Keyword arguments:
95         h -- String for header?
96         """
97         pr = "{:<8.2f}" if not h else "{:<8}"
98         pr += "{:<16}"
99         for i in range(12):
100             pr += " {:<16.6f}" if not h else " {:<16}"
101         return pr
102
103     scenarios = get_scenarios(SCEN_DIR)
104     scenarios = sorted(
105         scenarios.items(),
106         key=lambda kv: int(kv[0]) if kv[0].isnumeric() else kv[0]
107     )
108     print(gos(True).format(
109             "%err [%]",
110             "filename",
111             "max [s]", # elapsed time
112             "min [s]",
113             "avg [s]",
114             "stddev [s]",
115             "max [m]", # path cost
116             "min [m]",
117             "avg [m]",
118             "stddev [m]",
119             "max [-]", # path cusps
120             "min [-]",
121             "avg [-]",
122             "stddev [-]",
123     ))
124     print()
125     for (f, sl) in scenarios:
126         tl = compute_stats(sl, "time")
127         cl = compute_stats(sl, "cost")
128         cusps = compute_stats(sl, "path#cusp")
129         print(gos().format(
130                 tl["err"],
131                 f,
132                 tl["max"],
133                 tl["min"],
134                 tl["mean"],
135                 tl["std"],
136                 cl["max"],
137                 cl["min"],
138                 cl["mean"],
139                 cl["std"],
140                 cusps["max"],
141                 cusps["min"],
142                 cusps["mean"],
143                 cusps["std"],
144         ))