]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/print_json_objects_scenaris_statistics.py
Add med to print statistics
[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``, ``med``, ``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         wl.sort()
78         wl_med = wl[round(len(wl) / 2)]
79     return {
80         "err": 100 * (len(sl) - len(wl)) / len(sl),
81         "mean": wl_mean,
82         "std": wl_std,
83         "med": wl_med,
84         "max": wl_max,
85         "min": wl_min,
86     }
87
88 if __name__ == "__main__":
89     if (len(argv) == 2):
90         SCEN_DIR = argv[1]
91     else:
92         SCEN_DIR = "out"
93
94     def gos(h=False):
95         """Generate output string for values.
96
97         Keyword arguments:
98         h -- String for header?
99         """
100         pr = "{:<8.2f}" if not h else "{:<8}"
101         pr += "{:<16}"
102         for i in range(12):
103             pr += " {:<16.6f}" if not h else " {:<16}"
104         return pr
105
106     scenarios = get_scenarios(SCEN_DIR)
107     scenarios = sorted(
108         scenarios.items(),
109         key=lambda kv: int(kv[0]) if kv[0].isnumeric() else kv[0]
110     )
111     print(gos(True).format(
112             "%err [%]",
113             "filename",
114             "max [s]", # elapsed time
115             "min [s]",
116             "avg [s]",
117             "stddev [s]",
118             "max [m]", # path cost
119             "min [m]",
120             "avg [m]",
121             "stddev [m]",
122             "max [-]", # path cusps
123             "min [-]",
124             "avg [-]",
125             "stddev [-]",
126     ))
127     print()
128     for (f, sl) in scenarios:
129         tl = compute_stats(sl, "time")
130         cl = compute_stats(sl, "cost")
131         cusps = compute_stats(sl, "cusps-in-path")
132         print(gos().format(
133                 tl["err"],
134                 f,
135                 tl["max"],
136                 tl["min"],
137                 tl["mean"],
138                 tl["std"],
139                 cl["max"],
140                 cl["min"],
141                 cl["mean"],
142                 cl["std"],
143                 cusps["max"],
144                 cusps["min"],
145                 cusps["mean"],
146                 cusps["std"],
147         ))