Browse Source

update plotter to compare various models and simulators

Snej69420 10 months ago
parent
commit
242fbb608d
1 changed files with 71 additions and 44 deletions
  1. 71 44
      devstone/compare.py

+ 71 - 44
devstone/compare.py

@@ -5,69 +5,96 @@ import pandas as pd
 import matplotlib.pyplot as plt
 from pathlib import Path
 
-def process_files(csv_files, fixed_param, fixed_value, max_value=0):
-    """Combine and average simulation times by the varying parameter."""
-    results = {}
-    varying_param = "depth" if fixed_param == "width" else "width"
+def clean_data(df):
+    df["total_time"] = (
+        df["simulation_time"]
+        + df["creation_time"]
+        + df["setup_time"]
+    )
+
+    possible_group_cols = ["depth", "width", "number", "total_time"]
+    grouping_cols = [c for c in possible_group_cols if c in df.columns]
+
+    def clean(group):
+        Q1 = group["total_time"].quantile(0.25)
+        Q3 = group["total_time"].quantile(0.75)
+        IQR = Q3 - Q1
+        lower = Q1 - 1.5 * IQR
+        upper = Q3 + 1.5 * IQR
+        return group[(group["total_time"] >= lower) & (group["total_time"] <= upper)]
 
+    cleaned = (
+        df.groupby(grouping_cols, group_keys=False)[grouping_cols]
+          .apply(clean)
+    )
+
+    return cleaned
+
+def plot_time_vs_param(csv_files, param, fixed_param=None, fixed_value=None, max_value=0, name="DEVS"):
+    results = {}
     for path in csv_files:
         df = pd.read_csv(path)
-        df = df[df[fixed_param] == fixed_value].copy()
+        df = clean_data(df)
+        if fixed_param and fixed_value is not None:
+            df = df[df[fixed_param] == fixed_value]
         if max_value > 0:
-            df = df[df[varying_param] <= max_value].copy()
+            df = df[df[param] <= max_value]
 
-        df["total_time"] = (
-            df["simulation_time"]
-            + df["creation_time"]
-            + df["setup_time"]
-        )
+        grouped = df.groupby(param, as_index=False)["total_time"].mean()
+        results[path.stem] = grouped
 
-        Q1 = df["total_time"].quantile(0.25)
-        Q3 = df["total_time"].quantile(0.75)
-        IQR = Q3 - Q1
-        lower_bound = Q1 - 1.5 * IQR
-        upper_bound = Q3 + 1.5 * IQR
-        df = df[(df["total_time"] >= lower_bound) & (df["total_time"] <= upper_bound)]
-        grouped = df.groupby(varying_param, as_index=False)["total_time"].mean()
-        results[path.parent.name + "-" + path.stem] = grouped
-
-    return results, varying_param
-
-def plot_results(results, varying_param, fixed_param, fixed_value, name):
-    plt.figure(figsize=(8, 6))
+    plt.figure(figsize=(8,6))
     for label, df in results.items():
-        plt.plot(df[varying_param], df["total_time"], marker='o', label=label)
+        plt.plot(df[param], df["total_time"], marker='o', label=label)
 
-    plt.title(f"Average Simulation Time vs {varying_param.capitalize()} (fixed {fixed_param}={fixed_value})")
-    plt.xlabel(varying_param.capitalize())
+    title = f"Average Simulation Time vs {param.capitalize()}"
+    if fixed_param:
+        title += f" (fixed {fixed_param}={fixed_value})"
+    plt.title(title)
+    plt.xlabel(param.capitalize())
     plt.ylabel("Average Simulation Time (s)")
     plt.legend()
     plt.grid(True)
 
-    path = "../Plots/"
-    output_name = f"{name}_{fixed_param}_{fixed_value}.png"
+    output_dir = Path("../Plots")
+    output_dir.mkdir(parents=True, exist_ok=True)
+    output_file = output_dir / f"{name}_{param}.png"
     plt.tight_layout()
-    plt.savefig(path + output_name, dpi=300)
-    print(f"Saved plot as {output_name}")
-
+    plt.savefig(output_file, dpi=300)
+    print(f"Saved plot as {output_file}")
 
 def main():
     parser = argparse.ArgumentParser(description="Compare simulation results from multiple CSV files.")
-    parser.add_argument("csv_files", nargs="+", type=Path, help="Paths to the result CSV files.")
-    parser.add_argument("-n", "--name", default="DEVS", type=str, help="Name of the output file.")
-    group = parser.add_mutually_exclusive_group(required=True)
-    group.add_argument("-w", "--width", type=int, help="Fixed width value.")
-    group.add_argument("-d", "--depth", type=int, help="Fixed depth value.")
-    parser.add_argument('-m', '--max', type=int, default=0, help='Maximum value of the varying parameter')
+    subparsers = parser.add_subparsers(dest="command", required=True)
+
+    # Subcommand: time-vs-depth/width
+    parser_tvparam = subparsers.add_parser("param", help="Plot total time vs depth or width")
+    parser_tvparam.add_argument("csv_files", nargs="+", type=Path, help="CSV files to process")
+    parser_tvparam.add_argument("-n", "--name", default="DEVS", type=str, help="Name of output file")
+    group = parser_tvparam.add_mutually_exclusive_group(required=True)
+    group.add_argument("-w", "--width", type=int, help="Fixed width value")
+    group.add_argument("-d", "--depth", type=int, help="Fixed depth value")
+    parser_tvparam.add_argument('-m', '--max', type=int, default=0, help="Maximum value of varying parameter")
+
+    # Subcommand: time-vs-number
+    parser_tvn = subparsers.add_parser("number", help="Plot total time vs number")
+    parser_tvn.add_argument("csv_files", nargs="+", type=Path, help="CSV files to process")
+    parser_tvn.add_argument("-n", "--name", default="DEVS", type=str, help="Name of output file")
 
     args = parser.parse_args()
-    if args.width is not None:
-        fixed_param, fixed_value = "width", args.width
-    else:
-        fixed_param, fixed_value = "depth", args.depth
 
-    results, varying_param = process_files(args.csv_files, fixed_param, fixed_value, args.max)
-    plot_results(results, varying_param, fixed_param, fixed_value, args.name)
+    if args.command == "param":
+        if args.width is not None:
+            fixed_param, fixed_value = "width", args.width
+            varying_param = "depth"
+        else:
+            fixed_param, fixed_value = "depth", args.depth
+            varying_param = "width"
+        plot_time_vs_param(args.csv_files, param=varying_param,
+                           fixed_param=fixed_param, fixed_value=fixed_value,
+                           max_value=args.max, name=args.name)
+    elif args.command == "number":
+        plot_time_vs_param(args.csv_files, param="number", name=args.name)
 
 if __name__ == "__main__":
     main()