]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/print_json_objects_scenaris_statistics.py
Merge branch 'feature/multiple-times-rrt'
[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                 "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 = [s["sc"][what] for s in sl if "sc" in s and what in s["sc"]]
67     el = [
68         1 for s in sl
69         if "sc" in s
70         and "cost" in s["sc"]
71         and s["sc"]["cost"] != -1
72     ]
73     if len(wl) == 0:
74         wl_mean = inf
75         wl_std = inf
76         wl_max = inf
77         wl_min = -inf
78         wl_med = inf
79     else:
80         wl_mean = sum(wl) / len(wl)
81         wl_tmp = [(x - wl_mean)**2 for x in wl]
82         wl_std = (sum(wl_tmp) / len(wl_tmp))**0.5
83         wl_max = max(wl)
84         wl_min = min(wl)
85         wl.sort()
86         wl_med = wl[round(len(wl) / 2)]
87     return {
88         "err": 100 * (len(sl) - len(el)) / len(sl),
89         "avg": wl_mean,
90         "std": wl_std,
91         "med": wl_med,
92         "max": wl_max,
93         "min": wl_min,
94     }
95
96 if __name__ == "__main__":
97     if (len(argv) == 2):
98         SCEN_DIR = argv[1]
99     else:
100         SCEN_DIR = "out"
101
102     def gos(h=False):
103         """Generate output string for values.
104
105         Keyword arguments:
106         h -- String for header?
107         """
108         pr = "{:<16.2f}" if not h else "{:<16}"
109         pr += "{:<16}"
110         pr += "{:<16}"
111         pr += "{:<16}"
112         pr += "{:<16}"
113         for i in range(30): # 5 (from compute_stats) x 6 (stats in README)
114             pr += "{:<16.6f}" if not h else "{:<16}"
115         return pr
116
117     scenarios = get_scenarios(SCEN_DIR)
118     scenarios = sorted(
119         scenarios.items(),
120         key=lambda kv: int(kv[0]) if kv[0].isnumeric() else kv[0]
121     )
122     print(gos(True).format(
123             "%--------------|", "---------------|", "---------------|",
124             "---------------|", "---------------|",
125
126             "----------------", "----------------",
127             "time",
128             "----------------", "---------------|",
129
130             "----------------", "----------------",
131             "iterations",
132             "----------------", "---------------|",
133
134             "----------------", "----------------",
135             "cost",
136             "----------------", "---------------|",
137
138             "----------------", "----------------",
139             "cusps-in-path",
140             "----------------", "---------------|",
141
142             "----------------", "----------------",
143             "connecteds-in-pa", "th",
144             "---------------|",
145
146             "----------------", "----------------",
147             "nodes",
148             "----------------", "---------------|",
149     ))
150     print(gos(True).format(
151             "%err [%]", "planner", "filename",
152             "-", "-",
153             "avg [s]", "std [s]", "med [s]", "max [s]", "min [s]", # time
154             "avg [-]", "std [-]", "med [-]", "max [-]", "min [-]", # iterations
155             "avg [m]", "std [m]", "med [m]", "max [m]", "min [m]", # cost
156             "avg [-]", "std [-]", "med [-]", "max [-]", "min [-]", # cusps-in-p
157             "avg [-]", "std [-]", "med [-]", "max [-]", "min [-]", # connecteds
158             "avg [-]", "std [-]", "med [-]", "max [-]", "min [-]", # nodes
159     ))
160     print()
161     for (f, sl) in scenarios:
162         assert f == sl[0]["fn"]
163         tl = compute_stats(sl, "time")
164         il = compute_stats(sl, "iterations")
165         cl = compute_stats(sl, "cost")
166         cul = compute_stats(sl, "cusps-in-path")
167         col = compute_stats(sl, "connecteds-in-path")
168         nl = compute_stats(sl, "nodes")
169         print(gos().format(
170                 tl["err"], sl[0]["dn"], sl[0]["fn"],
171                 "-", "-",
172                 tl["avg"], tl["std"], tl["med"], tl["max"], tl["min"],
173                 il["avg"], il["std"], il["med"], il["max"], il["min"],
174                 cl["avg"], cl["std"], cl["med"], cl["max"], cl["min"],
175                 cul["avg"], cul["std"], cul["med"], cul["max"], cul["min"],
176                 col["avg"], col["std"], col["med"], col["max"], col["min"],
177                 nl["avg"], nl["std"], nl["med"], nl["max"], nl["min"],
178         ))