]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/print_json_objects_scenaris_histograms.py
Add script for plotting logged rewired data
[hubacji1/iamcar2.git] / scripts / print_json_objects_scenaris_histograms.py
1 """Print JSON formatted scenarios histograms.
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 numpy import histogram
20 from os import listdir
21 from sys import argv, exit
22
23 def get_scenario(fname):
24     """Load scenario from file.
25
26     Keyword arguments:
27     fname -- File name.
28     """
29     if fname is None:
30         raise ValueError("File name as argument needed")
31     with open(fname, "r") as f:
32         try:
33             scenario = loads(f.read())
34         except:
35             scenario = {"error": "Bad JSON format."}
36     return scenario
37
38 def get_scenarios(dname):
39     """Load scenarios from directiory.
40
41     Keyword arguments:
42     dname -- Directory name.
43     """
44     if dname is None:
45         raise ValueError("Directory name as argument needed")
46     s = {}
47     for d in listdir(dname):
48         for f in listdir("{}/{}".format(dname, d)):
49             if f not in s:
50                 s[f] = []
51             s[f].append({
52                 "dn": dname,
53                 "fn": f,
54                 "cnt": int(d),
55                 "sc": get_scenario("{}/{}/{}".format(dname, d, f)),
56             })
57     return s
58
59 def compute_stats(sl={}, what="time", **kwargs):
60     """Return histogram of ``what``.
61
62     Keyword arguments:
63     sl -- Scenarios list.
64     what -- The variable in scenario stats to compute with.
65     **kwargs -- Keyword arguments for ``numpy.histogram``.
66     """
67     assert len(sl) > 0
68     wl = [s["sc"][what] for s in sl if "sc" in s and what in s["sc"]]
69     return histogram(wl, **kwargs)
70
71 if __name__ == "__main__":
72     if (len(argv) == 2):
73         SCEN_DIR = argv[1]
74     else:
75         SCEN_DIR = "out"
76
77     scenarios = get_scenarios(SCEN_DIR)
78     scenarios = sorted(
79         scenarios.items(),
80         key=lambda kv: int(kv[0]) if kv[0].isnumeric() else kv[0]
81     )
82     dirs = []
83     files = []
84     histograms = []
85     what = [
86         "time",
87         "iterations",
88         "cost",
89         "cusps-in-path",
90         "connecteds-in-path",
91         "nodes",
92     ]
93     for (f, sl) in scenarios:
94         assert f == sl[0]["fn"]
95         dirs.append(sl[0]["dn"])
96         files.append(sl[0]["fn"])
97         for w in what:
98             tmp_hist = compute_stats(sl, w)
99             delta = (tmp_hist[1][1] - tmp_hist[1][0]) / 2
100             histograms.append([
101                 (e - delta, h)
102                 for (e, h)
103                 in zip(tmp_hist[1][1:], tmp_hist[0])
104             ])
105     assert len(dirs) == len(files)
106     h1 = "%" # dir names
107     h2 = "%" # file (planner) names
108     i = 0
109     for d in dirs:
110         if i == 0:
111             print("%", end="")
112             h = "{:<%s}" % int(len(what) * 32 - 1)
113             print(h.format(d), end="")
114         else:
115             h = "{:<%s}" % int(len(what) * 32)
116             print(h.format(d), end="")
117         i += 1
118     print()
119     i = 0
120     for f in files:
121         if i == 0:
122             print("%", end="")
123             h = "{:<%s}" % int(len(what) * 32 - 1)
124             print(h.format(f), end="")
125         else:
126             h = "{:<%s}" % int(len(what) * 32)
127             print(h.format(f), end="")
128         i += 1
129     print()
130     i = 0
131     for f in files:
132         for w in what:
133             if i == 0:
134                 print("%", end="")
135                 print("{:<31}".format(w), end="")
136             else:
137                 print("{:<32}".format(w), end="")
138             i += 1
139     print()
140     assert len(histograms) > 0
141     hl = len(histograms[0])
142     for i in range(hl):
143         for j in range(len(histograms)):
144             print(
145                 "{:<16.2f}{:<16}".format(
146                     histograms[j][i][0],
147                     histograms[j][i][1],
148                 ),
149                 end=""
150             )
151         print()