]> rtime.felk.cvut.cz Git - hubacji1/iamcar2.git/blob - scripts/print_json_objects_scenaris_histograms.py
Merge branch 'feature/refactor-plot-graphs'
[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     tmp_dirs = list(dirs)
107     tmp_files = list(files)
108     dirs = []
109     files = []
110     for w in what:
111         dirs += tmp_dirs
112         files += tmp_files
113     del(tmp_dirs)
114     del(tmp_files)
115     h0 = "%"
116     h1 = "%"
117     h2 = "%"
118     for w in what:
119         if len(h0) == 1:
120             h0 += "{:<%s}" % (int(len(files) * 32 / len(what) - 1))
121         else:
122             h0 += "{:<%s}" % (int(len(files) * 32 / len(what)))
123     print(h0.format(*what))
124     for d in dirs:
125         if len(h1) == 1:
126             h1 += "{:<31}"
127             h2 += "{:<31}"
128         else:
129             h1 += "{:<32}"
130             h2 += "{:<32}"
131     print(h1.format(*dirs))
132     print(h2.format(*files))
133     data = ""
134     for d in dirs:
135         data += "{:<16.2f}{:<16}"
136     assert len(histograms) > 0
137     bins = len(histograms[0])
138     for i in range(bins):
139         val = []
140         for h in histograms:
141             val += h[i]
142         print(data.format(*val))