浏览代码

assing colours for memory plotting, normalise memory data centrally and have matching simulator labels between plots

Snej69420 5 月之前
父节点
当前提交
debbac017d
共有 3 个文件被更改,包括 92 次插入 和 20 次删除
  1. 31 4
      benchmarks/compare.py
  2. 58 13
      benchmarks/compareMemory.py
  3. 3 3
      benchmarks/model_properties.py

+ 31 - 4
benchmarks/compare.py

@@ -26,12 +26,27 @@ SHORTHANDS = {
 
 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()
+    for key, shorthand in SIMULATOR_MAPPING.items():
+        if key.lower() in sim_id_lower:
+            return shorthand
+    return f"({sim_id})"
 
 def clean_data(df):
     df["total_time"] = (
@@ -89,7 +104,11 @@ def plot_time_vs_param(csv_files, styles, param, fixed_param=None, fixed_value=N
         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"
-        models.append(model_type)
+        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:
@@ -111,7 +130,9 @@ def plot_time_vs_param(csv_files, styles, param, fixed_param=None, fixed_value=N
             df = df[df[param] <= max_value]
 
         grouped = df.groupby(param, as_index=False)["total_time"].mean()
-        label = f"{model_type} ({sim_id})"
+
+        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)
@@ -161,7 +182,11 @@ def plot_time_vs_models(csv_files, styles, o_path="", name=""):
         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"
-        models.append(model_type)
+        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()
@@ -176,7 +201,9 @@ def plot_time_vs_models(csv_files, styles, o_path="", name=""):
         df = df.sort_values(by=Atomics)
 
         grouped = df.groupby(Atomics, as_index=False)["total_time"].mean()
-        label = f"{model_type} ({sim_id})"
+
+        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)

+ 58 - 13
benchmarks/compareMemory.py

@@ -16,8 +16,7 @@ SIMULATOR_MAPPING = {
     "parallel": "(p)",
     "dynamic": "(d)",
     "dynamic-classic": "(dc)",
-    "Memory": "(a)",
-    "Agents": "(a)",
+    "Memory": "(A)",
 }
 
 TIME_UNITS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600}
@@ -26,6 +25,32 @@ MEMORY_UNITS = {
     "KiB": 1024, "MiB": 1024 ** 2, "GiB": 1024 ** 3
 }
 
+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'
+}
+STYLE_KEYS = list(PREDEFINED_STYLES.keys())
+VALID_STYLE_INPUTS = list(PREDEFINED_STYLES.keys()) + list(SHORTHANDS.keys())
+
+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, PREDEFINED_STYLES['blue'])
+
 
 def normalize_database(db_path):
     """Normalizes the database so that every process starts at 0 RSS (Net Growth)."""
@@ -74,13 +99,13 @@ def process_data(df, mem_unit, time_unit):
     return df
 
 
-def plot_traces(files, width=None, depth=None, mem_unit="MB", time_unit="s", path="", name="", title=None, bw=False):
+def plot_traces(files, styles, width=None, depth=None, mem_unit="MB", time_unit="s", path="", name="", title=None, bw=False):
     plt.figure(figsize=(10, 6))
     style_cycle = cycle(zip(cycle(plt.rcParams['axes.prop_cycle'].by_key()['color'] if not bw else ['black']),
                             cycle(['-', '--', '-.', ':'])))
     plotted_any, models, main_model_type = False, [], None
 
-    for db_file in files:
+    for i, db_file in enumerate(files):
         file = Path(db_file).resolve()
         df = get_memory_trace(file)
         if df is None: continue
@@ -90,8 +115,18 @@ def plot_traces(files, width=None, depth=None, mem_unit="MB", time_unit="s", pat
         if main_model_type is None: main_model_type = model_type
         df = process_data(df, mem_unit, time_unit)
         color, linestyle = next(style_cycle)
+
+        style_input = styles[i] if i < len(styles) else STYLE_KEYS[i % len(STYLE_KEYS)]
+        style = get_style_config(style_input)
         label = f"{model_type} {SIMULATOR_MAPPING.get(file.parent.name, f'({file.parent.name})')}"
-        plt.plot(df["relative_time"], df["memory"], label=label, color=color, linestyle=linestyle, linewidth=1.5)
+        plt.plot(
+            df["relative_time"],
+            df["memory"],
+            label=label,
+            color=style['color'],
+            linestyle=style['ls'],
+            linewidth=1.5
+        )
         plotted_any = True
 
     if not plotted_any: return
@@ -99,15 +134,18 @@ def plot_traces(files, width=None, depth=None, mem_unit="MB", time_unit="s", pat
     plt.xlabel(f"Time ({time_unit})");
     plt.ylabel(f"Resident Set Size Net Growth ({mem_unit})")
 
-    if main_model_type and width and depth:
-        props = model_properties(main_model_type, width, depth)
-        atomics = int(props.get("Atomic Models", 0))
-        events = int(props.get("Events", 0))
+    if not title:
+        if main_model_type and width and depth:
+            props = model_properties(main_model_type, width, depth)
+            atomics = int(props.get("Atomic Models", 0))
+            events = int(props.get("Events", 0))
 
-        plt.suptitle(f"Memory Usage over Time (Net Growth): {main_model_type}", fontsize=12)
-        plt.title(f"Width: {width}, Depth: {depth} | #Atomic Models: {atomics:,} | #Events: {events:,}", fontsize=10)
+            plt.suptitle(f"Memory Usage over Time (Net Growth): {main_model_type}", fontsize=12)
+            plt.title(f"Width: {width}, Depth: {depth} | #Atomic Models: {atomics:,} | #Events: {events:,}", fontsize=10)
+        else:
+            plt.title("Memory Usage over Time (Net Growth)", fontsize=12)
     else:
-        plt.title("Memory Usage over Time (Net Growth)", fontsize=12)
+        plt.title(title, fontsize=12)
 
     plt.legend()
     plt.grid(True, linestyle=':', alpha=0.6)
@@ -123,6 +161,7 @@ def main():
     parser.add_argument("files", nargs="+")
     parser.add_argument("-w", "--width", type=int)
     parser.add_argument("-d", "--depth", type=int)
+    parser.add_argument('-s', '--styles', type=str, nargs='+', help=f"Space-separated list of colors matching CSV order. Options: {', '.join(VALID_STYLE_INPUTS)}")
     parser.add_argument("-mu", "--memory-unit", default="MB")
     parser.add_argument("-tu", "--time-unit", default="s")
     parser.add_argument("-p", "--path", default="")
@@ -130,7 +169,13 @@ def main():
     parser.add_argument("-t", "--title")
     parser.add_argument("--bw", action="store_true")
     args = parser.parse_args()
-    plot_traces(args.files, args.width, args.depth, args.memory_unit, args.time_unit, args.path, args.name, args.title,
+
+    if not args.styles:
+        styles = [STYLE_KEYS[i % len(STYLE_KEYS)] for i in range(len(args.files))]
+    else:
+        styles = args.styles
+
+    plot_traces(args.files, styles, args.width, args.depth, args.memory_unit, args.time_unit, args.path, args.name, args.title,
                 args.bw)
 
 

+ 3 - 3
benchmarks/model_properties.py

@@ -32,7 +32,7 @@ def HOmod(width: int, depth: int) -> dict:
     properties["External Outgoing Connections"] = depth
     properties["Internal Connections"] = ((width - 1) ** 2 + ((width - 1) * width) / 2) * (depth - 1)
     properties["Events"] = 1
-    for i in range(1, depth - 1):
+    for i in range(1, depth):
         e = (1 + (i - 1) * (width - 1)) * ((width - 1) * width) / 2 + (width - 1) * (width + (i - 1) * (width - 1))
         properties["Events"] += e
     return properties
@@ -81,9 +81,9 @@ def model_properties(model: str, width: int, depth: int) -> dict:
         case "HOmod":
             return HOmod(width, depth)
         case "HI2LI":
-            return {}
+            return LI(width, depth)
         case "LI2HI":
-            return {}
+            return HI(width, depth)
         case "dLI":
             return dLI(width, depth)
         case "mdLI":