]> rtime.felk.cvut.cz Git - hubacji1/iamcar.git/blobdiff - gplot.py
Merge branch 'release/0.7.0'
[hubacji1/iamcar.git] / gplot.py
index 0052d6781cca842f2b3d93dc89bc857932e762e4..1e9005163fd5603cd68578bfa81a3745b8f56d71 100644 (file)
--- a/gplot.py
+++ b/gplot.py
@@ -5,17 +5,25 @@ from matplotlib import pyplot as plt
 from os import listdir
 from sys import argv, exit
 import numpy as np
+import scipy.stats as ss
 
-LOGF="log"
-LOGSF=["T2","T3", "Klemm2015"]
-LEG={
-    LOGSF[0]: "T2",
-    LOGSF[1]: "T3",
-    LOGSF[2]: "Klemm2015"}
-COLS={
-    LEG[LOGSF[0]]: "orange",
-    LEG[LOGSF[1]]: "red",
-    LEG[LOGSF[2]]: "blue"}
+# ed - euclidean distance
+# rs - reeds and shepp path length
+# sh - reeds and shepp, same heading
+
+# ad - optimize with dijkstra, all nodes
+# as - optimize with smart, all nodes
+# ar - optimize with remove redundant points, all nodes
+# cd - optimize with dijkstra, cusp nodes
+# cs - optimize with smart, cusp nodes
+# cr - optimize with remove redundant points, cusp nodes
+
+LOGF = "log_wo"
+LOG = [
+    {"f": "T2", "c": "orange", "l": "T2"},
+]
+
+r = {}
 
 def load_trajectory(fname):
     """Load trajectory from file.
@@ -43,7 +51,7 @@ def load_trajectories(dname):
     return trajectories
 
 def gplot():
-    """Plot graph."""
+    """Plot graph. Template."""
     plt.rcParams["font.size"] = 24
     fig = plt.figure()
     ax = fig.add_subplot(111)
@@ -63,6 +71,22 @@ def gplot():
     plt.show()
     #plt.savefig("WHATEVER")
 
+def mean_conf_int(data, conf=0.95):
+    """Return (mean, lower, uppper) of data.
+
+    see https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data
+
+    Keyword arguments:
+    data -- A list of data.
+    conf -- Confidence interval.
+    """
+    a = np.array(data)
+    n = len(a)
+    m = np.mean(a)
+    se = ss.sem(a)
+    h = se * ss.t.ppf((1 + conf) / 2, n - 1)
+    return (m, m - h, m + h)
+
 def count_if_exist(trajectories, what):
     """From multiple trajectories compute the number of occurences.
 
@@ -109,80 +133,27 @@ def get_maxs_if_exist(trajectories, what):
             pass
     return val
 
-def plot_successrate():
-    """Plot success rate of single/multi-core implementations."""
-
-    r={}
-    for sf in LOGSF:
-        r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
-
-    v={}
-    for a in r.keys():
-        v[a] = (100 * count_if_exist(r[a], "traj") /
-                count_if_exist(r[a], "elap"))
-    vs = sorted(v.items(), key=lambda kv: kv[1])
-
-    plt.rcParams["font.size"] = 24
-    fig = plt.figure()
-    ax = fig.add_subplot(111)
-    ax.set_title("Success rate of trajectories found within 10 seconds limit")
-
-    ax.set_ylabel("Framework tested [-]")
-    ax.set_xlabel("Found successfully [%]")
-    ax.set_xlim(0, 100)
-    ax.set_yticklabels([])
-    j = 0
-    for (k, i) in vs:
-        print("{}: {}%".format(k, i))
-        ax.barh(j, float(i), 4, label=k)
-        j += -5
-    ax.legend()
-
-    plt.show()
-
-def plot_mintrajcost():
-    """Plot minimum trajectory cost found."""
-
-    r={}
-    for a in ALG:
-        for st in ST:
-            for co in CO:
-                r["{}, {}, {}".format(ALGT[a], STT[st], COT[co])] = (
-                        load_trajectories("{}/{}st{}co{}_lpar".format(
-                            LOGF, a, st, co)))
-
-    v={}
-    for a in r.keys():
-        v[a] = get_lasts_if_exist(r[a], "cost")
-
-    #plt.rcParams["font.size"] = 24
-    fig = plt.figure()
-    for i in range(len(r.keys())):
-        ax = fig.add_subplot(3, 1, i + 1)
-        ax.set_title("Minimum trajectory cost found in 10 seconds (sequential)")
-
-        ax.set_ylabel("Framework tested [-]")
-        ax.set_xlabel("Minimum trajectory cost [m]")
-        #ax.set_yticklabels([])
+def get_val_if_exist(trajectories, what):
+    """From m ultiple trajectories get value.
 
-        plt.bar(range(len(v[r.keys()[i]])), v[r.keys()[i]], label=r.keys()[i])
-
-        ax.legend()
-    plt.show()
-    return
+    Keyword arguments:
+    trajectories -- The list of trajectories.
+    what -- What to take.
+    """
+    val = []
+    for t in trajectories:
+        try:
+            val.append(t[what])
+        except:
+            pass
+    return val
 
 def plot_costdist():
     """Plot distribution of last costs across measured tests."""
-
-    r={}
-    for sf in LOGSF:
-        r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
-
-    v={}
+    v = {}
     for a in r.keys():
         v[a] = get_lasts_if_exist(r[a], "cost")
 
-    plt.rcParams["font.size"] = 24
     fig = plt.figure()
     ax = fig.add_subplot(111)
     ax.set_title("Path cost histogram")
@@ -190,14 +161,18 @@ def plot_costdist():
     ax.set_ylabel("Number of paths with given cost [-]")
     ax.set_xlabel("Path cost [m]")
     ax.set_yscale("log")
-    ax.set_aspect("equal")
 
-    for a in r.keys():
-        plt.hist(v[a], alpha=0.5, label=a, bins=100, histtype="step",
-                color=COLS[a])
+    for a in LOG:
+        plt.hist(
+                v[a["f"]],
+                alpha = 0.5,
+                label = a["l"],
+                bins = 100,
+                histtype = "step",
+                color = a["c"])
         try:
-                X_WHERE = np.percentile(v[a], [95])
-                plt.axvline(X_WHERE, lw=1, color=COLS[a], linestyle="--")
+                X_WHERE = np.percentile(v[a["f"]], [95])
+                plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
         except:
                 pass
 
@@ -206,31 +181,59 @@ def plot_costdist():
 
 def plot_maxtime():
     """Plot time of the last traj (the maximum time)."""
-
-    r={}
-    for sf in LOGSF:
-        r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
-
-    v={}
+    v = {}
     for a in r.keys():
         v[a] = get_lasts_if_exist(r[a], "secs")
 
-    plt.rcParams["font.size"] = 24
     fig = plt.figure()
     ax = fig.add_subplot(111)
-    ax.set_title("Path found time histogram")
+    ax.set_title("Histogram of time to find the path")
 
     ax.set_ylabel("Number of paths found [-]")
-    ax.set_xlabel("Algorithm elapsed time [s]")
+    ax.set_xlabel("Algorithm computation time [s]")
     ax.set_yscale("log")
-    ax.set_aspect("equal")
 
+    for a in LOG:
+        plt.hist(
+                v[a["f"]],
+                alpha = 0.5,
+                label = a["l"],
+                bins = np.arange(0, 10, 0.1),
+                histtype = "step",
+                color = a["c"])
+        try:
+                X_WHERE = np.percentile(v[a["f"]], [95])
+                plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
+        except:
+                pass
+
+    plt.legend()
+    plt.show()
+
+def plot_nothingdone():
+    """Plot *nothing done* time of ``overlaptrees`` procedure."""
+    v = {}
     for a in r.keys():
-        plt.hist(v[a], alpha=0.5, label=a, bins=np.arange(0, 10, 0.1),
-                histtype="step", color=COLS[a])
+        v[a] = get_lasts_if_exist(r[a], "nodo")
+
+    fig = plt.figure()
+    ax = fig.add_subplot(111)
+    ax.set_title("Histogram of nothing-done-time")
+
+    ax.set_ylabel("Occurences [-]")
+    ax.set_xlabel("Nothing-done-time percentage [-]")
+
+    for a in LOG:
+        plt.hist(
+                v[a["f"]],
+                alpha = 0.5,
+                label = a["l"],
+                bins = np.arange(0, 1, 0.1),
+                histtype = "step",
+                color = a["c"])
         try:
-                X_WHERE = np.percentile(v[a], [95])
-                plt.axvline(X_WHERE, lw=1, color=COLS[a], linestyle="--")
+                X_WHERE = np.percentile(v[a["f"]], [95])
+                plt.axvline(X_WHERE, lw=1, color=a["c"], linestyle="--")
         except:
                 pass
 
@@ -239,34 +242,30 @@ def plot_maxtime():
 
 def print_nofnodes():
     """Print average number of nodes."""
-
-    r={}
-    for sf in LOGSF:
-        r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
-
     v={}
     for a in r.keys():
         lasts = get_lasts_if_exist(r[a], "node")
         v[a] = np.average(lasts)
 
-    print("Average number of points:")
-    for a in r.keys():
-        print("{}: {}".format(a, v[a]))
+    print("Average number of nodes:")
+    for a in LOG:
+        print("{}: {}".format(a["f"], v[a["f"]]))
 
 def print_successrate():
     """Print success rate of implementations."""
-    r={}
-    for sf in LOGSF:
-        r["{}".format(LEG[sf])] = load_trajectories("{}/{}".format(LOGF, sf))
-
     v={}
     for a in r.keys():
         v[a] = (100.0 * count_if_exist(r[a], "traj") /
                 count_if_exist(r[a], "elap"))
 
     print("Success rate:")
-    for a in r.keys():
-        print("{}: {}".format(a, v[a]))
+    for a in LOG:
+        print("{}: {}".format(a["f"], v[a["f"]]))
 
 if __name__ == "__main__":
+    r = {}
+    for sf in [i["f"] for i in LOG]:
+        r[sf] = load_trajectories("{}/{}".format(LOGF, sf))
+    print_successrate()
+    plot_maxtime()
     plot_costdist()