| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- import argparse
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- from pathlib import Path
- from model_properties import model_properties
- # Dictionary mapping human-readable color names to styles
- PREDEFINED_STYLES = {
- "blue": {"color": "tab:blue", "ls": "-", "marker": "o"},
- "orange": {"color": "tab:orange", "ls": "--", "marker": "s"},
- "green": {"color": "tab:green", "ls": "-.", "marker": "^"},
- "red": {"color": "tab:red", "ls": ":", "marker": "D"},
- "purple": {"color": "tab:purple", "ls": "-", "marker": "v"},
- "brown": {"color": "tab:brown", "ls": "--", "marker": "X"},
- }
- SHORTHANDS = {
- "b": "blue",
- "o": "orange",
- "g": "green",
- "r": "red",
- "p": "purple",
- "br": "brown"
- }
- VALID_STYLE_INPUTS = list(PREDEFINED_STYLES.keys()) + list(SHORTHANDS.keys())
- SIMULATOR_MAPPING = {
- "pypdevs-minimal": "(m)",
- "pypdevs-classic": "(c)",
- "pypdevs-parallel": "(p)",
- "pypdevs-dynamic": "(d)",
- "pypdevs-dynamic-classic": "(dc)",
- "agents": "(A)",
- }
- def get_style_config(user_input):
- """Helper to resolve shorthands and handle case-insensitivity."""
- normalized = user_input.lower()
- key = SHORTHANDS.get(normalized, normalized)
- return PREDEFINED_STYLES.get(key)
- def get_sim_shorthand(sim_id):
- sim_id_lower = str(sim_id).lower()
- return SIMULATOR_MAPPING.get(sim_id_lower, f"({sim_id})")
- def clean_data(df):
- df["total_time"] = (
- df["simulation_time"]
- + df["creation_time"]
- + df["setup_time"]
- )
- group_params = [c for c in ["depth", "width", "number"] if c in df.columns]
- if not group_params:
- return df
- q1 = df.groupby(group_params)["total_time"].transform(lambda x: x.quantile(0.25))
- q3 = df.groupby(group_params)["total_time"].transform(lambda x: x.quantile(0.75))
- iqr = q3 - q1
- lower = q1 - 1.5 * iqr
- upper = q3 + 1.5 * iqr
- return df[(df["total_time"] >= lower) & (df["total_time"] <= upper)]
- def get_spaced_indices(series, n_markers):
- if len(series) <= n_markers:
- return None
- values = series.values
- min_v, max_v = values.min(), values.max()
- if min_v == max_v:
- return [0]
- targets = np.linspace(min_v, max_v, n_markers)
- indices = []
- import bisect
- val_list = values.tolist()
- for t in targets:
- idx = bisect.bisect_left(val_list, t)
- if idx > 0:
- if idx == len(val_list) or abs(val_list[idx - 1] - t) < abs(val_list[idx] - t):
- idx = idx - 1
- if idx < len(val_list):
- indices.append(idx)
- return sorted(list(set(indices)))
- def plot_time_vs_param(csv_files, styles, param, fixed_param=None, fixed_value=None, max_value=0, o_path="", name=""):
- results = []
- models = []
- for i, path in enumerate(csv_files):
- df = pd.read_csv(path)
- sim_id = df["simulator"].iloc[0] if "simulator" in df.columns else "None"
- model_type = df["model_type"].iloc[0] if "model_type" in df.columns else "None"
- num = df["number"].iloc[0] if "number" in df.columns else 1
- if num > 1:
- models.append(model_type + "-" + str(num))
- else:
- models.append(model_type)
- df = clean_data(df)
- if fixed_param and fixed_value is not None:
- df = df[df[fixed_param] == fixed_value]
- df = df.copy()
- if param == "Models":
- df["Models"] = df.apply(
- lambda row: model_properties(
- str(row["model_type"]),
- int(row["width"]),
- int(row["depth"])
- ).get("Atomic Models", 0),
- axis=1
- )
- df = df.sort_values(by=param)
- if max_value > 0:
- df = df[df[param] <= max_value]
- grouped = df.groupby(param, as_index=False)["total_time"].mean()
- label = f"{model_type}-{num}" if num > 1 else f"{model_type}"
- label = f"{label} {get_sim_shorthand(sim_id)}"
- style_input = styles[i] if i < len(styles) else list(PREDEFINED_STYLES.keys())[i % 6]
- style = get_style_config(style_input)
- results.append((label, grouped, style))
- final_name = name + "_over_" + param if name else f"{'|'.join(set(models))}_over_{param}"
- plt.figure(figsize=(8, 6))
- for label, df, style in results:
- plt.plot(
- df[param],
- df["total_time"],
- label=label,
- color=style["color"],
- linestyle=style["ls"],
- marker=style["marker"],
- markersize=5,
- markevery=3,
- )
- 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, linestyle=':', alpha=0.6)
- output_dir = Path(__file__).resolve().parent / "Plots" / o_path
- output_dir.mkdir(parents=True, exist_ok=True)
- output_file = output_dir / f"{final_name}.png"
- plt.tight_layout()
- plt.savefig(output_file, dpi=300)
- print(f"Saved plot as {output_file}")
- def plot_time_vs_models(csv_files, styles, o_path="", name=""):
- Atomics = "Models"
- results = []
- models = []
- for i, path in enumerate(csv_files):
- df = pd.read_csv(path)
- sim_id = df["simulator"].iloc[0] if "simulator" in df.columns else "None"
- model_type = df["model_type"].iloc[0] if "model_type" in df.columns else "None"
- num = df["number"].iloc[0] if "number" in df.columns else 1
- if num > 1:
- models.append(model_type + "-" + str(num))
- else:
- models.append(model_type)
- df = clean_data(df)
- df = df.copy()
- df[Atomics] = df.apply(
- lambda row: model_properties(
- str(row["model_type"]),
- int(row["width"]),
- int(row["depth"])
- ).get("Atomic Models", 0),
- axis=1
- )
- df = df.sort_values(by=Atomics)
- grouped = df.groupby(Atomics, as_index=False)["total_time"].mean()
- label = f"{model_type}-{num}" if num > 1 else f"{model_type}"
- label = f"{label} {get_sim_shorthand(sim_id)}"
- style_input = styles[i] if i < len(styles) else list(PREDEFINED_STYLES.keys())[i % 6]
- style = get_style_config(style_input)
- results.append((label, grouped, style))
- final_name = name + "_over_" + Atomics if name else f"{'|'.join(set(models))}_over_{Atomics}"
- plt.figure(figsize=(8, 6))
- for label, df, style in results:
- plt.plot(
- df[Atomics],
- df["total_time"],
- label=label,
- color=style["color"],
- marker=style["marker"],
- linestyle='',
- markersize=4,
- alpha=0.7,
- )
- plt.title(f"Average Simulation Time vs {Atomics}")
- plt.xlabel(Atomics)
- plt.ylabel("Average Simulation Time (s)")
- plt.legend()
- plt.grid(True, linestyle=':', alpha=0.6)
- output_dir = Path(__file__).resolve().parent / "Plots" / o_path
- output_dir.mkdir(parents=True, exist_ok=True)
- output_file = output_dir / f"{final_name}.png"
- plt.tight_layout()
- 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.")
- 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")
- 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")
- # Subcommand: total (Atomic Models)
- parser_tot = subparsers.add_parser("total", help="Plot total time vs number of atomic models")
- # Shared arguments for all subparsers
- for subp in [parser_tvparam, parser_tvn, parser_tot]:
- subp.add_argument("csv_files", nargs="+", type=Path, help="CSV files to process")
- subp.add_argument(
- "-s", "--styles",
- type=str,
- nargs="+",
- help=f"Space-separated list of colors matching CSV order. Options: {', '.join(VALID_STYLE_INPUTS)}"
- )
- subp.add_argument("-p", "--path", type=str, default="", help="Subdirectory for storing plots")
- subp.add_argument("-n", "--name", type=str, help="Name of output file")
- args = parser.parse_args()
- # Default to cycling through styles if the user omits the -s flag
- if not args.styles:
- styles = list(PREDEFINED_STYLES.keys())[:len(args.csv_files)]
- else:
- styles = args.styles
- 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, styles, param=varying_param,
- fixed_param=fixed_param, fixed_value=fixed_value,
- max_value=args.max, o_path=args.path, name=args.name)
- elif args.command == "number":
- plot_time_vs_param(args.csv_files, styles, param="number", o_path=args.path, name=args.name)
- elif args.command == "total":
- plot_time_vs_models(args.csv_files, styles, o_path=args.path, name=args.name)
- if __name__ == "__main__":
- main()
|