| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- #!/usr/bin/env python3
- import sqlite3
- import pandas as pd
- import matplotlib.pyplot as plt
- import argparse
- from pathlib import Path
- from itertools import cycle
- from model_properties import model_properties
- # Standard Linux page size in bytes
- PAGE_SIZE = 4096
- SIMULATOR_MAPPING = {
- "minimal": "(m)",
- "classic": "(c)",
- "parallel": "(p)",
- "dynamic": "(d)",
- "dynamic-classic": "(dc)",
- "Memory": "(A)",
- }
- TIME_UNITS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600}
- MEMORY_UNITS = {
- "Bytes": 1, "KB": 1000, "MB": 1000 ** 2, "GB": 1000 ** 3,
- "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 get_memory_trace(db_path):
- if not db_path.exists() or db_path.stat().st_size == 0: return None
- try:
- with sqlite3.connect(db_path) as conn:
- query = "SELECT ts, stat_rss FROM record WHERE stat_comm IN ('python3', 'julia') ORDER BY ts ASC"
- df = pd.read_sql_query(query, conn)
- return df if not df.empty else None
- except sqlite3.Error as e:
- return None
- def process_data(df, mem_unit, time_unit):
- start_time = df["ts"].iloc[0]
- df["relative_time"] = (df["ts"] - start_time) / TIME_UNITS[time_unit]
- df["memory"] = (df["stat_rss"] * PAGE_SIZE) / MEMORY_UNITS[mem_unit]
- return df
- 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 i, db_file in enumerate(files):
- file = Path(db_file).resolve()
- df = get_memory_trace(file)
- if df is None: continue
- model_type = file.stem
- models.append(model_type)
- 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=style['color'],
- linestyle=style['ls'],
- linewidth=1.5
- )
- plotted_any = True
- if not plotted_any: return
- plt.xlabel(f"Time ({time_unit})");
- plt.ylabel(f"Resident Set Size ({mem_unit})")
- 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: {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", fontsize=12)
- else:
- plt.title(title, fontsize=12)
- plt.legend()
- plt.grid(True, linestyle=':', alpha=0.6)
- out_dir = Path(__file__).resolve().parent / "MemoryPlots" / path
- out_dir.mkdir(parents=True, exist_ok=True)
- plt.tight_layout();
- plt.savefig(out_dir / f"{name or '|'.join(set(models))}.png", dpi=300)
- def main():
- parser = argparse.ArgumentParser()
- 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="")
- parser.add_argument("-n", "--name", default="")
- parser.add_argument("-t", "--title")
- parser.add_argument("--bw", action="store_true")
- args = parser.parse_args()
- 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)
- if __name__ == "__main__": main()
|