compare.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import argparse
  2. import numpy as np
  3. import pandas as pd
  4. import matplotlib.pyplot as plt
  5. from pathlib import Path
  6. from model_properties import model_properties
  7. # Dictionary mapping human-readable color names to styles
  8. PREDEFINED_STYLES = {
  9. "blue": {"color": "tab:blue", "ls": "-", "marker": "o"},
  10. "orange": {"color": "tab:orange", "ls": "--", "marker": "s"},
  11. "green": {"color": "tab:green", "ls": "-.", "marker": "^"},
  12. "red": {"color": "tab:red", "ls": ":", "marker": "D"},
  13. "purple": {"color": "tab:purple", "ls": "-", "marker": "v"},
  14. "brown": {"color": "tab:brown", "ls": "--", "marker": "X"},
  15. }
  16. SHORTHANDS = {
  17. "b": "blue",
  18. "o": "orange",
  19. "g": "green",
  20. "r": "red",
  21. "p": "purple",
  22. "br": "brown"
  23. }
  24. VALID_STYLE_INPUTS = list(PREDEFINED_STYLES.keys()) + list(SHORTHANDS.keys())
  25. SIMULATOR_MAPPING = {
  26. "pypdevs-minimal": "(m)",
  27. "pypdevs-classic": "(c)",
  28. "pypdevs-parallel": "(p)",
  29. "pypdevs-dynamic": "(d)",
  30. "pypdevs-dynamic-classic": "(dc)",
  31. "agents": "(A)",
  32. }
  33. def get_style_config(user_input):
  34. """Helper to resolve shorthands and handle case-insensitivity."""
  35. normalized = user_input.lower()
  36. key = SHORTHANDS.get(normalized, normalized)
  37. return PREDEFINED_STYLES.get(key)
  38. def get_sim_shorthand(sim_id):
  39. sim_id_lower = str(sim_id).lower()
  40. return SIMULATOR_MAPPING.get(sim_id_lower, f"({sim_id})")
  41. def clean_data(df):
  42. df["total_time"] = (
  43. df["simulation_time"]
  44. + df["creation_time"]
  45. + df["setup_time"]
  46. )
  47. group_params = [c for c in ["depth", "width", "number"] if c in df.columns]
  48. if not group_params:
  49. return df
  50. q1 = df.groupby(group_params)["total_time"].transform(lambda x: x.quantile(0.25))
  51. q3 = df.groupby(group_params)["total_time"].transform(lambda x: x.quantile(0.75))
  52. iqr = q3 - q1
  53. lower = q1 - 1.5 * iqr
  54. upper = q3 + 1.5 * iqr
  55. return df[(df["total_time"] >= lower) & (df["total_time"] <= upper)]
  56. def get_spaced_indices(series, n_markers):
  57. if len(series) <= n_markers:
  58. return None
  59. values = series.values
  60. min_v, max_v = values.min(), values.max()
  61. if min_v == max_v:
  62. return [0]
  63. targets = np.linspace(min_v, max_v, n_markers)
  64. indices = []
  65. import bisect
  66. val_list = values.tolist()
  67. for t in targets:
  68. idx = bisect.bisect_left(val_list, t)
  69. if idx > 0:
  70. if idx == len(val_list) or abs(val_list[idx - 1] - t) < abs(val_list[idx] - t):
  71. idx = idx - 1
  72. if idx < len(val_list):
  73. indices.append(idx)
  74. return sorted(list(set(indices)))
  75. def plot_time_vs_param(csv_files, styles, param, fixed_param=None, fixed_value=None, max_value=0, o_path="", name=""):
  76. results = []
  77. models = []
  78. for i, path in enumerate(csv_files):
  79. df = pd.read_csv(path)
  80. sim_id = df["simulator"].iloc[0] if "simulator" in df.columns else "None"
  81. model_type = df["model_type"].iloc[0] if "model_type" in df.columns else "None"
  82. num = df["number"].iloc[0] if "number" in df.columns else 1
  83. if num > 1:
  84. models.append(model_type + "-" + str(num))
  85. else:
  86. models.append(model_type)
  87. df = clean_data(df)
  88. if fixed_param and fixed_value is not None:
  89. df = df[df[fixed_param] == fixed_value]
  90. df = df.copy()
  91. if param == "Models":
  92. df["Models"] = df.apply(
  93. lambda row: model_properties(
  94. str(row["model_type"]),
  95. int(row["width"]),
  96. int(row["depth"])
  97. ).get("Atomic Models", 0),
  98. axis=1
  99. )
  100. df = df.sort_values(by=param)
  101. if max_value > 0:
  102. df = df[df[param] <= max_value]
  103. grouped = df.groupby(param, as_index=False)["total_time"].mean()
  104. label = f"{model_type}-{num}" if num > 1 else f"{model_type}"
  105. label = f"{label} {get_sim_shorthand(sim_id)}"
  106. style_input = styles[i] if i < len(styles) else list(PREDEFINED_STYLES.keys())[i % 6]
  107. style = get_style_config(style_input)
  108. results.append((label, grouped, style))
  109. final_name = name + "_over_" + param if name else f"{'|'.join(set(models))}_over_{param}"
  110. plt.figure(figsize=(8, 6))
  111. for label, df, style in results:
  112. plt.plot(
  113. df[param],
  114. df["total_time"],
  115. label=label,
  116. color=style["color"],
  117. linestyle=style["ls"],
  118. marker=style["marker"],
  119. markersize=5,
  120. markevery=3,
  121. )
  122. title = f"Average Simulation Time vs {param.capitalize()}"
  123. if fixed_param:
  124. title += f" (fixed {fixed_param}={fixed_value})"
  125. plt.title(title)
  126. plt.xlabel(param.capitalize())
  127. plt.ylabel("Average Simulation Time (s)")
  128. plt.legend()
  129. plt.grid(True, linestyle=':', alpha=0.6)
  130. output_dir = Path(__file__).resolve().parent / "Plots" / o_path
  131. output_dir.mkdir(parents=True, exist_ok=True)
  132. output_file = output_dir / f"{final_name}.png"
  133. plt.tight_layout()
  134. plt.savefig(output_file, dpi=300)
  135. print(f"Saved plot as {output_file}")
  136. def plot_time_vs_models(csv_files, styles, o_path="", name=""):
  137. Atomics = "Models"
  138. results = []
  139. models = []
  140. for i, path in enumerate(csv_files):
  141. df = pd.read_csv(path)
  142. sim_id = df["simulator"].iloc[0] if "simulator" in df.columns else "None"
  143. model_type = df["model_type"].iloc[0] if "model_type" in df.columns else "None"
  144. num = df["number"].iloc[0] if "number" in df.columns else 1
  145. if num > 1:
  146. models.append(model_type + "-" + str(num))
  147. else:
  148. models.append(model_type)
  149. df = clean_data(df)
  150. df = df.copy()
  151. df[Atomics] = df.apply(
  152. lambda row: model_properties(
  153. str(row["model_type"]),
  154. int(row["width"]),
  155. int(row["depth"])
  156. ).get("Atomic Models", 0),
  157. axis=1
  158. )
  159. df = df.sort_values(by=Atomics)
  160. grouped = df.groupby(Atomics, as_index=False)["total_time"].mean()
  161. label = f"{model_type}-{num}" if num > 1 else f"{model_type}"
  162. label = f"{label} {get_sim_shorthand(sim_id)}"
  163. style_input = styles[i] if i < len(styles) else list(PREDEFINED_STYLES.keys())[i % 6]
  164. style = get_style_config(style_input)
  165. results.append((label, grouped, style))
  166. final_name = name + "_over_" + Atomics if name else f"{'|'.join(set(models))}_over_{Atomics}"
  167. plt.figure(figsize=(8, 6))
  168. for label, df, style in results:
  169. plt.plot(
  170. df[Atomics],
  171. df["total_time"],
  172. label=label,
  173. color=style["color"],
  174. marker=style["marker"],
  175. linestyle='',
  176. markersize=4,
  177. alpha=0.7,
  178. )
  179. plt.title(f"Average Simulation Time vs {Atomics}")
  180. plt.xlabel(Atomics)
  181. plt.ylabel("Average Simulation Time (s)")
  182. plt.legend()
  183. plt.grid(True, linestyle=':', alpha=0.6)
  184. output_dir = Path(__file__).resolve().parent / "Plots" / o_path
  185. output_dir.mkdir(parents=True, exist_ok=True)
  186. output_file = output_dir / f"{final_name}.png"
  187. plt.tight_layout()
  188. plt.savefig(output_file, dpi=300)
  189. print(f"Saved plot as {output_file}")
  190. def main():
  191. parser = argparse.ArgumentParser(description="Compare simulation results from multiple CSV files.")
  192. subparsers = parser.add_subparsers(dest="command", required=True)
  193. # Subcommand: time-vs-depth/width
  194. parser_tvparam = subparsers.add_parser("param", help="Plot total time vs depth or width")
  195. group = parser_tvparam.add_mutually_exclusive_group(required=True)
  196. group.add_argument("-w", "--width", type=int, help="Fixed width value")
  197. group.add_argument("-d", "--depth", type=int, help="Fixed depth value")
  198. parser_tvparam.add_argument('-m', '--max', type=int, default=0, help="Maximum value of varying parameter")
  199. # Subcommand: time-vs-number
  200. parser_tvn = subparsers.add_parser("number", help="Plot total time vs number")
  201. # Subcommand: total (Atomic Models)
  202. parser_tot = subparsers.add_parser("total", help="Plot total time vs number of atomic models")
  203. # Shared arguments for all subparsers
  204. for subp in [parser_tvparam, parser_tvn, parser_tot]:
  205. subp.add_argument("csv_files", nargs="+", type=Path, help="CSV files to process")
  206. subp.add_argument(
  207. "-s", "--styles",
  208. type=str,
  209. nargs="+",
  210. help=f"Space-separated list of colors matching CSV order. Options: {', '.join(VALID_STYLE_INPUTS)}"
  211. )
  212. subp.add_argument("-p", "--path", type=str, default="", help="Subdirectory for storing plots")
  213. subp.add_argument("-n", "--name", type=str, help="Name of output file")
  214. args = parser.parse_args()
  215. # Default to cycling through styles if the user omits the -s flag
  216. if not args.styles:
  217. styles = list(PREDEFINED_STYLES.keys())[:len(args.csv_files)]
  218. else:
  219. styles = args.styles
  220. if args.command == "param":
  221. if args.width is not None:
  222. fixed_param, fixed_value = "width", args.width
  223. varying_param = "depth"
  224. else:
  225. fixed_param, fixed_value = "depth", args.depth
  226. varying_param = "width"
  227. plot_time_vs_param(args.csv_files, styles, param=varying_param,
  228. fixed_param=fixed_param, fixed_value=fixed_value,
  229. max_value=args.max, o_path=args.path, name=args.name)
  230. elif args.command == "number":
  231. plot_time_vs_param(args.csv_files, styles, param="number", o_path=args.path, name=args.name)
  232. elif args.command == "total":
  233. plot_time_vs_models(args.csv_files, styles, o_path=args.path, name=args.name)
  234. if __name__ == "__main__":
  235. main()