| |
|
|
| import csv |
| from collections import defaultdict |
| from pathlib import Path |
| from typing import Dict, List |
|
|
| import matplotlib.pyplot as plt |
| import numpy as np |
|
|
| |
| plt.rcParams["font.family"] = "Times New Roman" |
|
|
| |
| MODEL_ORDER: List[str] = [ |
| "GPT-5", |
| "GPT-4o-mini", |
| "DeepSeek-V3-1", |
| "DeepSeek-R1", |
| "Gemini-2.5-flash", |
| "Gemini-2.5-flash-nothinking", |
| "Qwen3-235b", |
| ] |
|
|
| |
| MODEL_LABELS: Dict[str, str] = { |
| "GPT-5": "GPT-5", |
| "GPT-4o-mini": "GPT-4o-mini", |
| "DeepSeek-V3-1": "DeepSeek-V3.1", |
| "DeepSeek-R1": "DeepSeek-R1", |
| "Gemini-2.5-flash": "Gemini-2.5", |
| "Gemini-2.5-flash-nothinking": "Gemini-2.5-NT", |
| "Qwen3-235b": "Qwen3-235b", |
| } |
|
|
| |
| MODEL_COLORS: Dict[str, str] = { |
| "GPT-5": "#1f77b4", |
| "GPT-4o-mini": "#ff7f0e", |
| "DeepSeek-V3-1": "#2ca02c", |
| "DeepSeek-R1": "#d62728", |
| "Gemini-2.5-flash": "#9467bd", |
| "Gemini-2.5-flash-nothinking": "#8c564b", |
| "Qwen3-235b": "#e377c2", |
| } |
|
|
|
|
| def load_total_classified(csv_path: Path) -> Dict[str, List[float]]: |
| """Load total_classified values per model from a CSV file. |
| |
| Returns: |
| data[model] = sorted list of total_classified values (floats). |
| """ |
|
|
| by_model: Dict[str, List[float]] = defaultdict(list) |
|
|
| with csv_path.open("r", encoding="utf-8", newline="") as f: |
| reader = csv.DictReader(f) |
| for row in reader: |
| model = (row.get("model") or "").strip() |
| if not model: |
| continue |
| if model not in MODEL_ORDER: |
| |
| continue |
| val_raw = row.get("total_classified") |
| if val_raw is None or val_raw == "": |
| continue |
| try: |
| |
| val = float(val_raw) |
| except ValueError: |
| continue |
| by_model[model].append(val) |
|
|
| |
| for m in list(by_model.keys()): |
| by_model[m].sort() |
|
|
| return by_model |
|
|
|
|
| def compute_ecdf(values: List[float]): |
| """Return x, y for the empirical CDF of a 1D sample. |
| |
| x: sorted values |
| y: ECDF in [0, 1] |
| """ |
|
|
| if not values: |
| return np.array([]), np.array([]) |
|
|
| x = np.asarray(values, dtype=float) |
| n = x.size |
| |
| y = np.arange(1, n + 1, dtype=float) / float(n) |
| return x, y |
|
|
|
|
| def compute_weighted_ecdf(values: List[float], weights: List[float]): |
| if not values or not weights or len(values) != len(weights): |
| return np.array([]), np.array([]) |
|
|
| x = np.asarray(values, dtype=float) |
| w = np.asarray(weights, dtype=float) |
|
|
| if np.all(w <= 0.0): |
| return np.array([]), np.array([]) |
|
|
| order = np.argsort(x) |
| x_sorted = x[order] |
| w_sorted = w[order] |
|
|
| cum_w = np.cumsum(w_sorted) |
| total_w = cum_w[-1] |
| if total_w <= 0.0: |
| return np.array([]), np.array([]) |
|
|
| y = cum_w / float(total_w) |
| return x_sorted, y |
|
|
|
|
| def create_legend_pdf_horizontal(output_path: Path) -> None: |
| fig, ax = plt.subplots(figsize=(12, 1.0)) |
| ax.axis("off") |
|
|
| handles = [] |
| labels = [] |
| for model in MODEL_ORDER: |
| color = MODEL_COLORS.get(model, "black") |
| (handle,) = ax.plot([], [], "-", linewidth=2, color=color) |
| handles.append(handle) |
| labels.append(MODEL_LABELS.get(model, model)) |
|
|
| ax.legend( |
| handles, |
| labels, |
| loc="center", |
| ncol=len(handles), |
| frameon=False, |
| fancybox=False, |
| shadow=False, |
| borderaxespad=0.1, |
| borderpad=0.3, |
| handletextpad=0.4, |
| labelspacing=0.2, |
| prop={"size": 14}, |
| ) |
|
|
| fig.tight_layout(pad=0.0) |
| fig.savefig( |
| output_path, |
| format="pdf", |
| dpi=300, |
| bbox_inches="tight", |
| pad_inches=0.0, |
| ) |
| plt.close(fig) |
| print(f"saved horizontal legend: {output_path}") |
|
|
|
|
| def plot_overall_ecdf( |
| overall_values_by_model: Dict[str, List[float]], |
| overall_weights_by_model: Dict[str, List[float]], |
| out_dir: Path, |
| ) -> None: |
| fig, ax = plt.subplots(figsize=(6, 4)) |
|
|
| any_line = False |
| for model in MODEL_ORDER: |
| values = overall_values_by_model.get(model) |
| weights = overall_weights_by_model.get(model) |
| if not values or not weights or len(values) != len(weights): |
| continue |
| x, y = compute_weighted_ecdf(values, weights) |
| if x.size == 0: |
| continue |
| x_plot = x / 1_000_000.0 |
| color = MODEL_COLORS.get(model, "black") |
| label = MODEL_LABELS.get(model, model) |
| ax.plot(x_plot, y, label=label, color=color, linewidth=2.0) |
| any_line = True |
|
|
| if not any_line: |
| plt.close(fig) |
| print("no ECDF lines drawn for overall, skip figure") |
| return |
|
|
| ax.set_xlabel(r"$\mathbf{Trace\ duration\ [10^3\ s]}$", fontsize=22) |
| ax.set_ylabel("", fontsize=22) |
|
|
| ax.set_ylim(0.0, 1.0) |
|
|
| ax.grid(True, which="both", axis="both", linestyle="-", linewidth=0.5, alpha=0.4) |
|
|
| ax.tick_params(axis="both", labelsize=22) |
| plt.setp(ax.get_xticklabels(), fontweight="bold") |
| plt.setp(ax.get_yticklabels(), fontweight="bold") |
|
|
| ax.margins(x=0.01) |
| fig.tight_layout(pad=0.0) |
|
|
| out_dir.mkdir(parents=True, exist_ok=True) |
| out_file = out_dir / "ecdf_overall_time_weighted.pdf" |
| fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02) |
| plt.close(fig) |
| print(f"saved ECDF figure: {out_file}") |
|
|
|
|
| def compute_time_statistics(values: List[float]) -> Dict[str, float]: |
| """Compute time statistics for a list of values (in milliseconds). |
| |
| Returns: |
| Dictionary with mean, median, and total in seconds. |
| """ |
| if not values: |
| return {"mean": 0.0, "median": 0.0, "total": 0.0, "count": 0} |
|
|
| |
| values_sec = [v / 1000.0 for v in values] |
| return { |
| "mean": np.mean(values_sec), |
| "median": np.median(values_sec), |
| "total": np.sum(values_sec), |
| "count": len(values), |
| } |
|
|
|
|
| def generate_mcp_vs_hardcoded_comparison( |
| base_project: str, scenario_time_data: Dict[str, Dict[str, List[float]]] |
| ) -> str: |
| """Generate comparison between MCP and hardcoded versions for a project.""" |
| lines = [] |
| lines.append(f"# {base_project}: MCP vs Hardcoded\n\n") |
|
|
| mcp_scenario = f"{base_project}-MCP" |
| hardcoded_scenario = base_project |
|
|
| if ( |
| mcp_scenario not in scenario_time_data |
| or hardcoded_scenario not in scenario_time_data |
| ): |
| lines.append("_Data not available for comparison_\n\n") |
| return "".join(lines) |
|
|
| mcp_data = scenario_time_data[mcp_scenario] |
| hardcoded_data = scenario_time_data[hardcoded_scenario] |
|
|
| all_models = sorted(set(mcp_data.keys()) | set(hardcoded_data.keys())) |
|
|
| |
| overall_stats = { |
| "mcp": {"total": 0.0, "count": 0}, |
| "hard": {"total": 0.0, "count": 0}, |
| } |
| for model in all_models: |
| mcp_stats = compute_time_statistics(mcp_data.get(model, [])) |
| hard_stats = compute_time_statistics(hardcoded_data.get(model, [])) |
| overall_stats["mcp"]["total"] += mcp_stats["total"] |
| overall_stats["mcp"]["count"] += mcp_stats["count"] |
| overall_stats["hard"]["total"] += hard_stats["total"] |
| overall_stats["hard"]["count"] += hard_stats["count"] |
|
|
| |
| lines.append("## Overall Summary (Averaged Across All Models)\n\n") |
| lines.append("| MCP Mean (s) | Hardcoded Mean (s) | Diff (MCP-Hard) |\n") |
| lines.append("| --- | --- | --- |\n") |
|
|
| if overall_stats["mcp"]["count"] > 0 and overall_stats["hard"]["count"] > 0: |
| avg_mcp = overall_stats["mcp"]["total"] / overall_stats["mcp"]["count"] |
| avg_hard = overall_stats["hard"]["total"] / overall_stats["hard"]["count"] |
| diff = avg_mcp - avg_hard |
| pct = (diff / avg_hard * 100) if avg_hard > 0 else 0 |
| lines.append( |
| f"| {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n" |
| ) |
|
|
| lines.append("\n---\n\n") |
|
|
| |
| lines.append("## Per-Model Comparison\n\n") |
| lines.append("| Model | MCP Mean (s) | Hardcoded Mean (s) | Diff (MCP-Hard) |\n") |
| lines.append("| --- | --- | --- | --- |\n") |
|
|
| for model in all_models: |
| mcp_stats = compute_time_statistics(mcp_data.get(model, [])) |
| hard_stats = compute_time_statistics(hardcoded_data.get(model, [])) |
|
|
| mean_diff = mcp_stats["mean"] - hard_stats["mean"] |
| mean_pct = ( |
| (mean_diff / hard_stats["mean"] * 100) if hard_stats["mean"] > 0 else 0 |
| ) |
|
|
| lines.append( |
| f"| {model} | {mcp_stats['mean']:.2f} | {hard_stats['mean']:.2f} | " |
| f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n" |
| ) |
| lines.append("\n") |
|
|
| return "".join(lines) |
|
|
|
|
| def generate_mcp_vs_hardcoded_overall_comparison( |
| projects: List[str], scenario_time_data: Dict[str, Dict[str, List[float]]] |
| ) -> str: |
| """Generate overall comparison across all MCP vs hardcoded projects.""" |
| lines = [] |
| lines.append("# Overall MCP vs Hardcoded Comparison\n\n") |
| lines.append(f"Averaged across all projects: {', '.join(projects)}\n\n") |
|
|
| |
| overall_data = {} |
| framework_stats = { |
| "mcp": {"total": 0.0, "count": 0}, |
| "hard": {"total": 0.0, "count": 0}, |
| } |
|
|
| for project in projects: |
| mcp_scenario = f"{project}-MCP" |
| hardcoded_scenario = project |
|
|
| if ( |
| mcp_scenario not in scenario_time_data |
| or hardcoded_scenario not in scenario_time_data |
| ): |
| continue |
|
|
| mcp_data = scenario_time_data[mcp_scenario] |
| hardcoded_data = scenario_time_data[hardcoded_scenario] |
|
|
| all_models = set(mcp_data.keys()) | set(hardcoded_data.keys()) |
|
|
| for model in all_models: |
| if model not in overall_data: |
| overall_data[model] = {"mcp": [], "hard": []} |
|
|
| mcp_vals = mcp_data.get(model, []) |
| hard_vals = hardcoded_data.get(model, []) |
|
|
| overall_data[model]["mcp"].extend(mcp_vals) |
| overall_data[model]["hard"].extend(hard_vals) |
|
|
| |
| mcp_stats = compute_time_statistics(mcp_vals) |
| hard_stats = compute_time_statistics(hard_vals) |
| framework_stats["mcp"]["total"] += mcp_stats["total"] |
| framework_stats["mcp"]["count"] += mcp_stats["count"] |
| framework_stats["hard"]["total"] += hard_stats["total"] |
| framework_stats["hard"]["count"] += hard_stats["count"] |
|
|
| |
| lines.append("## Framework-Level Comparison (All Models Averaged)\n\n") |
| lines.append("| MCP Mean (s) | Hardcoded Mean (s) | Diff (MCP-Hard) |\n") |
| lines.append("| --- | --- | --- |\n") |
|
|
| if framework_stats["mcp"]["count"] > 0 and framework_stats["hard"]["count"] > 0: |
| avg_mcp = framework_stats["mcp"]["total"] / framework_stats["mcp"]["count"] |
| avg_hard = framework_stats["hard"]["total"] / framework_stats["hard"]["count"] |
| diff = avg_mcp - avg_hard |
| pct = (diff / avg_hard * 100) if avg_hard > 0 else 0 |
| lines.append( |
| f"| {avg_mcp:.2f} | {avg_hard:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n" |
| ) |
|
|
| lines.append("\n---\n\n") |
|
|
| |
| lines.append("## Per-Model Summary\n\n") |
| lines.append("| Model | MCP Mean (s) | Hard Mean (s) | Diff (MCP-Hard) |\n") |
| lines.append("| --- | --- | --- | --- |\n") |
|
|
| for model in sorted(overall_data.keys()): |
| mcp_stats = compute_time_statistics(overall_data[model]["mcp"]) |
| hard_stats = compute_time_statistics(overall_data[model]["hard"]) |
|
|
| mean_diff = mcp_stats["mean"] - hard_stats["mean"] |
| mean_pct = ( |
| (mean_diff / hard_stats["mean"] * 100) if hard_stats["mean"] > 0 else 0 |
| ) |
|
|
| lines.append( |
| f"| {model} | {mcp_stats['mean']:.2f} | {hard_stats['mean']:.2f} | " |
| f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n" |
| ) |
| lines.append("\n---\n\n") |
|
|
| return "".join(lines) |
|
|
|
|
| def generate_version_comparison( |
| base_project: str, |
| version_a_suffix: str, |
| version_b_suffix: str, |
| scenario_time_data: Dict[str, Dict[str, List[float]]], |
| version_a_name: str, |
| version_b_name: str, |
| ) -> str: |
| """Generate comparison between two versions of a project.""" |
| lines = [] |
| lines.append(f"# {base_project}: {version_a_name} vs {version_b_name}\n\n") |
|
|
| scenario_a = f"{base_project}{version_a_suffix}" |
| scenario_b = f"{base_project}{version_b_suffix}" |
|
|
| if scenario_a not in scenario_time_data or scenario_b not in scenario_time_data: |
| lines.append("_Data not available for comparison_\n\n") |
| return "".join(lines) |
|
|
| data_a = scenario_time_data[scenario_a] |
| data_b = scenario_time_data[scenario_b] |
|
|
| all_models = sorted(set(data_a.keys()) | set(data_b.keys())) |
|
|
| |
| overall_stats = {"a": {"total": 0.0, "count": 0}, "b": {"total": 0.0, "count": 0}} |
| for model in all_models: |
| stats_a = compute_time_statistics(data_a.get(model, [])) |
| stats_b = compute_time_statistics(data_b.get(model, [])) |
| overall_stats["a"]["total"] += stats_a["total"] |
| overall_stats["a"]["count"] += stats_a["count"] |
| overall_stats["b"]["total"] += stats_b["total"] |
| overall_stats["b"]["count"] += stats_b["count"] |
|
|
| |
| lines.append("## Overall Summary (Averaged Across All Models)\n\n") |
| lines.append( |
| f"| {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n" |
| ) |
| lines.append("| --- | --- | --- |\n") |
|
|
| if overall_stats["a"]["count"] > 0 and overall_stats["b"]["count"] > 0: |
| avg_a = overall_stats["a"]["total"] / overall_stats["a"]["count"] |
| avg_b = overall_stats["b"]["total"] / overall_stats["b"]["count"] |
| diff = avg_a - avg_b |
| pct = (diff / avg_b * 100) if avg_b > 0 else 0 |
| lines.append(f"| {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n") |
|
|
| lines.append("\n---\n\n") |
|
|
| |
| lines.append("## Per-Model Comparison\n\n") |
| lines.append( |
| f"| Model | {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n" |
| ) |
| lines.append("| --- | --- | --- | --- |\n") |
|
|
| for model in all_models: |
| stats_a = compute_time_statistics(data_a.get(model, [])) |
| stats_b = compute_time_statistics(data_b.get(model, [])) |
|
|
| mean_diff = stats_a["mean"] - stats_b["mean"] |
| mean_pct = (mean_diff / stats_b["mean"] * 100) if stats_b["mean"] > 0 else 0 |
|
|
| lines.append( |
| f"| {model} | {stats_a['mean']:.2f} | {stats_b['mean']:.2f} | " |
| f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n" |
| ) |
| lines.append("\n") |
|
|
| return "".join(lines) |
|
|
|
|
| def generate_version_overall_comparison( |
| projects: List[str], |
| version_a_suffix: str, |
| version_b_suffix: str, |
| scenario_time_data: Dict[str, Dict[str, List[float]]], |
| version_a_name: str, |
| version_b_name: str, |
| comparison_title: str, |
| ) -> str: |
| """Generate overall comparison across all projects for two versions.""" |
| lines = [] |
| lines.append(f"# Overall {comparison_title}\n\n") |
| lines.append(f"Averaged across all projects: {', '.join(projects)}\n\n") |
|
|
| |
| overall_data = {} |
| framework_stats = {"a": {"total": 0.0, "count": 0}, "b": {"total": 0.0, "count": 0}} |
|
|
| for project in projects: |
| scenario_a = f"{project}{version_a_suffix}" |
| scenario_b = f"{project}{version_b_suffix}" |
|
|
| if scenario_a not in scenario_time_data or scenario_b not in scenario_time_data: |
| continue |
|
|
| data_a = scenario_time_data[scenario_a] |
| data_b = scenario_time_data[scenario_b] |
|
|
| all_models = set(data_a.keys()) | set(data_b.keys()) |
|
|
| for model in all_models: |
| if model not in overall_data: |
| overall_data[model] = {"a": [], "b": []} |
|
|
| vals_a = data_a.get(model, []) |
| vals_b = data_b.get(model, []) |
|
|
| overall_data[model]["a"].extend(vals_a) |
| overall_data[model]["b"].extend(vals_b) |
|
|
| |
| stats_a = compute_time_statistics(vals_a) |
| stats_b = compute_time_statistics(vals_b) |
| framework_stats["a"]["total"] += stats_a["total"] |
| framework_stats["a"]["count"] += stats_a["count"] |
| framework_stats["b"]["total"] += stats_b["total"] |
| framework_stats["b"]["count"] += stats_b["count"] |
|
|
| |
| lines.append("## Framework-Level Comparison (All Models Averaged)\n\n") |
| lines.append( |
| f"| {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n" |
| ) |
| lines.append("| --- | --- | --- |\n") |
|
|
| if framework_stats["a"]["count"] > 0 and framework_stats["b"]["count"] > 0: |
| avg_a = framework_stats["a"]["total"] / framework_stats["a"]["count"] |
| avg_b = framework_stats["b"]["total"] / framework_stats["b"]["count"] |
| diff = avg_a - avg_b |
| pct = (diff / avg_b * 100) if avg_b > 0 else 0 |
| lines.append(f"| {avg_a:.2f} | {avg_b:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n") |
|
|
| lines.append("\n---\n\n") |
|
|
| |
| lines.append("## Per-Model Summary\n\n") |
| lines.append( |
| f"| Model | {version_a_name} Mean (s) | {version_b_name} Mean (s) | Diff ({version_a_name}-{version_b_name}) |\n" |
| ) |
| lines.append("| --- | --- | --- | --- |\n") |
|
|
| for model in sorted(overall_data.keys()): |
| stats_a = compute_time_statistics(overall_data[model]["a"]) |
| stats_b = compute_time_statistics(overall_data[model]["b"]) |
|
|
| mean_diff = stats_a["mean"] - stats_b["mean"] |
| mean_pct = (mean_diff / stats_b["mean"] * 100) if stats_b["mean"] > 0 else 0 |
|
|
| lines.append( |
| f"| {model} | {stats_a['mean']:.2f} | {stats_b['mean']:.2f} | " |
| f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n" |
| ) |
| lines.append("\n---\n\n") |
|
|
| return "".join(lines) |
|
|
|
|
| def get_base_project_name(scenario: str) -> str: |
| if scenario.endswith("-A2A_mix"): |
| return scenario[: -len("-A2A_mix")] |
| if scenario.endswith("-H_A2A"): |
| return scenario[: -len("-H_A2A")] |
| if scenario.endswith("-A2A"): |
| return scenario[: -len("-A2A")] |
| if scenario.endswith("-MCP"): |
| return scenario[: -len("-MCP")] |
| return scenario |
|
|
|
|
| def generate_overall_model_comparison( |
| scenario_time_data: Dict[str, Dict[str, List[float]]], |
| ) -> str: |
| """Generate an all-projects summary comparing models across every scenario.""" |
|
|
| lines: List[str] = [] |
| lines.append("## All Projects Combined (Summary Across All Projects, by Model)\n\n") |
|
|
| |
| aggregated: Dict[str, List[float]] = defaultdict(list) |
| for project_data in scenario_time_data.values(): |
| for model, vals in project_data.items(): |
| aggregated[model].extend(vals) |
|
|
| if not aggregated: |
| lines.append("_No data available across projects_\n\n") |
| return "".join(lines) |
|
|
| |
| ordered_models: List[str] = [ |
| m for m in MODEL_ORDER if m in aggregated and aggregated[m] |
| ] |
| remaining_models = sorted( |
| m for m in aggregated.keys() if m not in ordered_models and aggregated[m] |
| ) |
| all_models = ordered_models + remaining_models |
|
|
| |
| model_stats: Dict[str, Dict[str, float]] = {} |
| for model in all_models: |
| model_stats[model] = compute_time_statistics(aggregated[model]) |
|
|
| |
| lines.append("### Model Statistics Summary\n\n") |
| lines.append("| Model | Mean (s) | Median (s) | Count | Total (s) |\n") |
| lines.append("| --- | --- | --- | --- | --- |\n") |
|
|
| for model in all_models: |
| stats = model_stats[model] |
| lines.append( |
| f"| {model} | {stats['mean']:.2f} | {stats['median']:.2f} | " |
| f"{stats['count']} | {stats['total']:.2f} |\n" |
| ) |
|
|
| |
| positive_models = [m for m in all_models if model_stats[m]["mean"] > 0] |
| if len(positive_models) > 1: |
| fastest_model = min(positive_models, key=lambda m: model_stats[m]["mean"]) |
| fastest_mean = model_stats[fastest_model]["mean"] |
|
|
| lines.append("\n### Relative Performance (vs. Fastest Model)\n\n") |
| lines.append( |
| f"Baseline (fastest): **{fastest_model}** ({fastest_mean:.2f}s mean)\n\n" |
| ) |
| lines.append("| Model | Mean (s) | Slowdown vs Baseline |\n") |
| lines.append("| --- | --- | --- |\n") |
|
|
| for model in all_models: |
| stats = model_stats[model] |
| if stats["mean"] > 0 and fastest_mean > 0: |
| slowdown = (stats["mean"] - fastest_mean) / fastest_mean * 100 |
| lines.append(f"| {model} | {stats['mean']:.2f} | {slowdown:+.1f}% |\n") |
| else: |
| lines.append(f"| {model} | {stats['mean']:.2f} | N/A |\n") |
|
|
| |
| slowest_model = max( |
| positive_models, |
| key=lambda m: model_stats[m]["mean"] if model_stats[m]["mean"] > 0 else 0, |
| ) |
| slowest_mean = model_stats[slowest_model]["mean"] |
| if fastest_mean > 0 and slowest_mean > 0: |
| slowest_slowdown = (slowest_mean - fastest_mean) / fastest_mean * 100 |
| lines.append( |
| f"\n**Slowest model:** {slowest_model} ({slowest_mean:.2f}s mean, " |
| f"{slowest_slowdown:+.1f}% slower than baseline)\n" |
| ) |
|
|
| lines.append("\n") |
| return "".join(lines) |
|
|
|
|
| def generate_project_model_comparison( |
| project_name: str, scenario_time_data: Dict[str, Dict[str, List[float]]] |
| ) -> str: |
| """Generate model-to-model comparison for a single project. |
| |
| Compares all models within the same project scenario. |
| """ |
| lines = [] |
| lines.append(f"# {project_name}: Model Comparison\n\n") |
|
|
| if project_name not in scenario_time_data: |
| lines.append("_Data not available for this project_\n\n") |
| return "".join(lines) |
|
|
| project_data = scenario_time_data[project_name] |
| all_models = sorted(project_data.keys()) |
|
|
| if not all_models: |
| lines.append("_No model data available_\n\n") |
| return "".join(lines) |
|
|
| |
| model_stats = {} |
| for model in all_models: |
| vals = project_data.get(model, []) |
| model_stats[model] = compute_time_statistics(vals) |
|
|
| |
| lines.append("## Model Statistics Summary\n\n") |
| lines.append("| Model | Mean (s) | Median (s) | Count | Total (s) |\n") |
| lines.append("| --- | --- | --- | --- | --- |\n") |
|
|
| for model in all_models: |
| stats = model_stats[model] |
| lines.append( |
| f"| {model} | {stats['mean']:.2f} | {stats['median']:.2f} | " |
| f"{stats['count']} | {stats['total']:.2f} |\n" |
| ) |
|
|
| |
| if len(all_models) > 1: |
| lines.append("\n## Relative Performance (vs. Fastest Model)\n\n") |
|
|
| |
| fastest_model = min( |
| all_models, |
| key=lambda m: ( |
| model_stats[m]["mean"] if model_stats[m]["mean"] > 0 else float("inf") |
| ), |
| ) |
| fastest_mean = model_stats[fastest_model]["mean"] |
|
|
| |
| slowest_model = max( |
| all_models, |
| key=lambda m: model_stats[m]["mean"] if model_stats[m]["mean"] > 0 else 0, |
| ) |
| slowest_mean = model_stats[slowest_model]["mean"] |
|
|
| lines.append( |
| f"Baseline (fastest): **{fastest_model}** ({fastest_mean:.2f}s mean)\n\n" |
| ) |
| lines.append("| Model | Mean (s) | Slowdown vs Baseline |\n") |
| lines.append("| --- | --- | --- |\n") |
|
|
| for model in all_models: |
| stats = model_stats[model] |
| if stats["mean"] > 0 and fastest_mean > 0: |
| slowdown = (stats["mean"] - fastest_mean) / fastest_mean * 100 |
| lines.append(f"| {model} | {stats['mean']:.2f} | {slowdown:+.1f}% |\n") |
| else: |
| lines.append(f"| {model} | {stats['mean']:.2f} | N/A |\n") |
|
|
| |
| if fastest_mean > 0 and slowest_mean > 0: |
| slowest_slowdown = (slowest_mean - fastest_mean) / fastest_mean * 100 |
| lines.append( |
| f"\n**Slowest model:** {slowest_model} ({slowest_mean:.2f}s mean, " |
| f"{slowest_slowdown:+.1f}% slower than baseline)\n" |
| ) |
|
|
| lines.append("\n") |
| return "".join(lines) |
|
|
|
|
| def plot_ecdf_for_project( |
| project_dir: Path, csv_path: Path, out_dir: Path, x_max_ms: float |
| ) -> None: |
| """Plot ECDF of total_classified for all models in one project. |
| |
| One figure per project, up to 7 lines (one per model present in the CSV). |
| """ |
|
|
| data_by_model = load_total_classified(csv_path) |
| if not data_by_model: |
| print(f"no total_classified data in {csv_path}, skip") |
| return |
|
|
| |
| |
| if x_max_ms <= 0.0: |
| local_max = 0.0 |
| for vals in data_by_model.values(): |
| if vals: |
| v_max = max(vals) |
| if v_max > local_max: |
| local_max = v_max |
| x_max_ms = local_max |
|
|
| fig, ax = plt.subplots(figsize=(6, 4)) |
|
|
| |
| any_line = False |
| for model in MODEL_ORDER: |
| values = data_by_model.get(model) |
| if not values: |
| continue |
| x, y = compute_ecdf(values) |
| if x.size == 0: |
| continue |
| |
| |
| |
| x_plot = x / 1_000_000.0 |
| color = MODEL_COLORS.get(model, "black") |
| label = MODEL_LABELS.get(model, model) |
| ax.plot(x_plot, y, label=label, color=color, linewidth=2.0) |
| any_line = True |
|
|
| if not any_line: |
| plt.close(fig) |
| print(f"no ECDF lines drawn for {csv_path}, skip figure") |
| return |
|
|
| |
| |
| x_max_plot = x_max_ms / 1_000_000.0 |
| if x_max_plot > 0.0: |
| ax.set_xlim(0.0, x_max_plot) |
|
|
| |
| ax.set_xlabel(r"$\mathbf{Trace\ duration\ [10^3\ s]}$", fontsize=22) |
| |
| ax.set_ylabel("", fontsize=22) |
|
|
| ax.set_ylim(0.0, 1.0) |
|
|
| |
| ax.grid(True, which="both", axis="both", linestyle="-", linewidth=0.5, alpha=0.4) |
|
|
| ax.tick_params(axis="both", labelsize=22) |
| plt.setp(ax.get_xticklabels(), fontweight="bold") |
| plt.setp(ax.get_yticklabels(), fontweight="bold") |
|
|
| |
| ax.margins(x=0.01) |
| fig.tight_layout(pad=0.0) |
|
|
| out_dir.mkdir(parents=True, exist_ok=True) |
| out_file = out_dir / f"ecdf_{project_dir.name}.pdf" |
| |
| |
| fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02) |
| plt.close(fig) |
| print(f"saved ECDF figure: {out_file}") |
|
|
|
|
| def main() -> None: |
| |
| part2_dir = Path(__file__).resolve().parent |
|
|
| |
| out_dir = part2_dir / "ECDFs" |
|
|
| overall_values_by_model: Dict[str, List[float]] = defaultdict(list) |
| overall_weights_by_model: Dict[str, List[float]] = defaultdict(list) |
|
|
| |
| scenario_time_data: Dict[str, Dict[str, List[float]]] = {} |
|
|
| |
| |
| series_x_max_ms: Dict[str, float] = {} |
|
|
| |
| for sub in sorted(p for p in part2_dir.iterdir() if p.is_dir()): |
| if sub.name.startswith("z_"): |
| |
| continue |
| csv_path = sub / "performance_breakdown_summary.csv" |
| if not csv_path.exists(): |
| continue |
| data_by_model = load_total_classified(csv_path) |
|
|
| |
| scenario_time_data[sub.name] = data_by_model |
|
|
| |
| for model, vals in data_by_model.items(): |
| if not vals: |
| continue |
| total_time = float(sum(vals)) |
| count = len(vals) |
| if total_time <= 0.0 or count <= 0: |
| continue |
| weight_per_sample = total_time / float(count) |
| for v in vals: |
| overall_values_by_model[model].append(v) |
| overall_weights_by_model[model].append(weight_per_sample) |
|
|
| |
| |
| scenario_max = 0.0 |
| for vals in data_by_model.values(): |
| if vals: |
| v_max = max(vals) |
| if v_max > scenario_max: |
| scenario_max = v_max |
| if scenario_max > 0.0: |
| base_name = get_base_project_name(sub.name) |
| prev_max = series_x_max_ms.get(base_name, 0.0) |
| if scenario_max > prev_max: |
| series_x_max_ms[base_name] = scenario_max |
|
|
| |
| |
| for sub in sorted(p for p in part2_dir.iterdir() if p.is_dir()): |
| if sub.name.startswith("z_"): |
| continue |
| csv_path = sub / "performance_breakdown_summary.csv" |
| if not csv_path.exists(): |
| continue |
| base_name = get_base_project_name(sub.name) |
| x_max_ms = series_x_max_ms.get(base_name, 0.0) |
| print(f"processing {csv_path}") |
| try: |
| plot_ecdf_for_project(sub, csv_path, out_dir, x_max_ms) |
| except Exception as exc: |
| print(f" error while plotting {csv_path}: {exc}") |
|
|
| if overall_values_by_model: |
| plot_overall_ecdf(overall_values_by_model, overall_weights_by_model, out_dir) |
|
|
| |
| legend_path = out_dir / "ECDF_Model_Legend_horizontal.pdf" |
| create_legend_pdf_horizontal(legend_path) |
|
|
| |
| print("\n" + "=" * 60) |
| print("Generating time comparison summaries...") |
| print("=" * 60) |
|
|
| |
| mcp_hardcoded_projects = [ |
| "MarkdownValidator", |
| "GameBuilder", |
| "EmailResponder", |
| ] |
|
|
| comparison_lines = [] |
| |
| comparison_lines.append( |
| generate_mcp_vs_hardcoded_overall_comparison( |
| mcp_hardcoded_projects, scenario_time_data |
| ) |
| ) |
|
|
| |
| for project in mcp_hardcoded_projects: |
| comparison_lines.append( |
| generate_mcp_vs_hardcoded_comparison(project, scenario_time_data) |
| ) |
|
|
| comparison_md_path = out_dir / "Time_Comparison_MCP_vs_Hardcoded.md" |
| comparison_md_path.write_text("".join(comparison_lines), encoding="utf-8") |
| print(f"Created: {comparison_md_path}") |
|
|
| |
| version_projects = [ |
| "SQL_assistant", |
| "intelligent_recruitment_platform", |
| "landing_page_generator", |
| "self_evaluation_loop_flow", |
| "write_a_book_with_flows", |
| ] |
|
|
| comparison_lines = [] |
| |
| comparison_lines.append( |
| generate_version_overall_comparison( |
| version_projects, |
| "-MCP", |
| "-A2A", |
| scenario_time_data, |
| "MCP", |
| "A2A", |
| "MCP vs A2A Time Comparison", |
| ) |
| ) |
|
|
| |
| for project in version_projects: |
| comparison_lines.append( |
| generate_version_comparison( |
| project, "-MCP", "-A2A", scenario_time_data, "MCP", "A2A" |
| ) |
| ) |
|
|
| comparison_md_path = out_dir / "Time_Comparison_MCP_vs_A2A.md" |
| comparison_md_path.write_text("".join(comparison_lines), encoding="utf-8") |
| print(f"Created: {comparison_md_path}") |
|
|
| |
| comparison_lines = [] |
| |
| comparison_lines.append( |
| generate_version_overall_comparison( |
| version_projects, |
| "-A2A", |
| "-A2A_mix", |
| scenario_time_data, |
| "A2A", |
| "A2A_mix", |
| "A2A vs A2A_mix Time Comparison", |
| ) |
| ) |
|
|
| |
| for project in version_projects: |
| comparison_lines.append( |
| generate_version_comparison( |
| project, "-A2A", "-A2A_mix", scenario_time_data, "A2A", "A2A_mix" |
| ) |
| ) |
|
|
| comparison_md_path = out_dir / "Time_Comparison_A2A_vs_A2A_mix.md" |
| comparison_md_path.write_text("".join(comparison_lines), encoding="utf-8") |
| print(f"Created: {comparison_md_path}") |
|
|
| |
| print("\nGenerating detailed A2A vs A2A_mix per-project comparisons...") |
| a2a_mix_comparison_lines = [] |
| a2a_mix_comparison_lines.append( |
| "# A2A vs A2A_mix: Detailed Per-Project Comparison\n\n" |
| ) |
| a2a_mix_comparison_lines.append( |
| "This document compares A2A and A2A_mix architectures for each project, " |
| ) |
| a2a_mix_comparison_lines.append( |
| "showing both per-model and overall statistics.\n\n" |
| ) |
| a2a_mix_comparison_lines.append("---\n\n") |
|
|
| |
| global_all_models = sorted( |
| set().union(*[set(d.keys()) for d in scenario_time_data.values()]) |
| ) |
| overall_deltas: List[Dict[str, float]] = [] |
| per_model_global: Dict[str, Dict[str, float]] = defaultdict( |
| lambda: {"a2a_sum": 0.0, "a2a_cnt": 0, "mix_sum": 0.0, "mix_cnt": 0} |
| ) |
|
|
| for project in version_projects: |
| scenario_a2a = f"{project}-A2A" |
| scenario_a2a_mix = f"{project}-A2A_mix" |
|
|
| if ( |
| scenario_a2a not in scenario_time_data |
| or scenario_a2a_mix not in scenario_time_data |
| ): |
| continue |
|
|
| a2a_mix_comparison_lines.append(f"## {project}\n\n") |
| a2a_mix_comparison_lines.append("### Project-Level Summary\n\n") |
|
|
| data_a2a = scenario_time_data[scenario_a2a] |
| data_a2a_mix = scenario_time_data[scenario_a2a_mix] |
| all_models = sorted(set(data_a2a.keys()) | set(data_a2a_mix.keys())) |
|
|
| |
| overall_a2a_total = 0.0 |
| overall_a2a_count = 0 |
| overall_a2a_mix_total = 0.0 |
| overall_a2a_mix_count = 0 |
|
|
| for model in all_models: |
| stats_a2a = compute_time_statistics(data_a2a.get(model, [])) |
| stats_a2a_mix = compute_time_statistics(data_a2a_mix.get(model, [])) |
| overall_a2a_total += stats_a2a["total"] |
| overall_a2a_count += stats_a2a["count"] |
| overall_a2a_mix_total += stats_a2a_mix["total"] |
| overall_a2a_mix_count += stats_a2a_mix["count"] |
| |
| per_model_global[model]["a2a_sum"] += stats_a2a["total"] |
| per_model_global[model]["a2a_cnt"] += stats_a2a["count"] |
| per_model_global[model]["mix_sum"] += stats_a2a_mix["total"] |
| per_model_global[model]["mix_cnt"] += stats_a2a_mix["count"] |
|
|
| if overall_a2a_count > 0 and overall_a2a_mix_count > 0: |
| avg_a2a = overall_a2a_total / overall_a2a_count |
| avg_a2a_mix = overall_a2a_mix_total / overall_a2a_mix_count |
| diff = avg_a2a_mix - avg_a2a |
| pct = (diff / avg_a2a * 100) if avg_a2a > 0 else 0 |
| a2a_mix_comparison_lines.append("### Overall Summary\n\n") |
| a2a_mix_comparison_lines.append( |
| "| A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n" |
| ) |
| a2a_mix_comparison_lines.append("| --- | --- | --- |\n") |
| a2a_mix_comparison_lines.append( |
| f"| {avg_a2a:.2f} | {avg_a2a_mix:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n\n" |
| ) |
| overall_deltas.append( |
| { |
| "project": project, |
| "a2a": avg_a2a, |
| "mix": avg_a2a_mix, |
| "diff": diff, |
| "pct": pct, |
| } |
| ) |
|
|
| |
| a2a_mix_comparison_lines.append("### Per-Model Comparison\n\n") |
| a2a_mix_comparison_lines.append( |
| "| Model | A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n" |
| ) |
| a2a_mix_comparison_lines.append("| --- | --- | --- | --- |\n") |
|
|
| for model in all_models: |
| stats_a2a = compute_time_statistics(data_a2a.get(model, [])) |
| stats_a2a_mix = compute_time_statistics(data_a2a_mix.get(model, [])) |
| mean_diff = stats_a2a_mix["mean"] - stats_a2a["mean"] |
| mean_pct = ( |
| (mean_diff / stats_a2a["mean"] * 100) if stats_a2a["mean"] > 0 else 0 |
| ) |
| a2a_mix_comparison_lines.append( |
| f"| {model} | {stats_a2a['mean']:.2f} | {stats_a2a_mix['mean']:.2f} | " |
| f"{mean_diff:+.2f}s ({mean_pct:+.1f}%) |\n" |
| ) |
|
|
| a2a_mix_comparison_lines.append("\n---\n\n") |
|
|
| |
| if overall_deltas: |
| a2a_mix_comparison_lines.insert( |
| 4, |
| "## Overall (All Projects)\n\n" |
| "| Project | A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n" |
| "| --- | --- | --- | --- |\n" |
| + "".join( |
| f"| {d['project']} | {d['a2a']:.2f} | {d['mix']:.2f} | {d['diff']:+.2f}s ({d['pct']:+.1f}%) |\n" |
| for d in overall_deltas |
| ) |
| + "\n", |
| ) |
|
|
| if per_model_global: |
| per_model_lines = [] |
| per_model_lines.append("## All Projects Combined (Per-Model)\n\n") |
| per_model_lines.append( |
| "| Model | A2A Mean (s) | A2A_mix Mean (s) | Diff (A2A_mix - A2A) |\n" |
| ) |
| per_model_lines.append("| --- | --- | --- | --- |\n") |
| for model in MODEL_ORDER: |
| stats = per_model_global.get(model) |
| if not stats: |
| continue |
| a2a_cnt = stats["a2a_cnt"] |
| mix_cnt = stats["mix_cnt"] |
| if a2a_cnt <= 0 or mix_cnt <= 0: |
| continue |
| avg_a2a = stats["a2a_sum"] / a2a_cnt |
| avg_mix = stats["mix_sum"] / mix_cnt |
| diff = avg_mix - avg_a2a |
| pct = (diff / avg_a2a * 100) if avg_a2a > 0 else 0 |
| per_model_lines.append( |
| f"| {model} | {avg_a2a:.2f} | {avg_mix:.2f} | {diff:+.2f}s ({pct:+.1f}%) |\n" |
| ) |
| per_model_lines.append("\n---\n\n") |
| |
| a2a_mix_comparison_lines[5:5] = per_model_lines |
|
|
| a2a_mix_md_path = out_dir / "A2A_vs_A2A_mix_Detailed_Comparison.md" |
| a2a_mix_md_path.write_text("".join(a2a_mix_comparison_lines), encoding="utf-8") |
| print(f"Created: {a2a_mix_md_path}") |
|
|
| |
| print("\nGenerating per-project model comparisons (21 projects)...") |
| all_project_names = sorted(scenario_time_data.keys()) |
|
|
| model_comparison_lines = [] |
| model_comparison_lines.append("# Per-Project Model Performance Comparison\n\n") |
| model_comparison_lines.append( |
| f"This document compares model performance within each of the {len(all_project_names)} projects.\n\n" |
| ) |
| model_comparison_lines.append("Each project shows:\n") |
| model_comparison_lines.append( |
| "- Model statistics (mean, median, count, total time)\n" |
| ) |
| model_comparison_lines.append( |
| "- Relative performance compared to the fastest model\n\n" |
| ) |
|
|
| |
| model_comparison_lines.append("---\n\n") |
| model_comparison_lines.append(generate_overall_model_comparison(scenario_time_data)) |
| model_comparison_lines.append("---\n\n") |
|
|
| for project_name in all_project_names: |
| model_comparison_lines.append( |
| generate_project_model_comparison(project_name, scenario_time_data) |
| ) |
| model_comparison_lines.append("---\n\n") |
|
|
| model_comparison_md_path = out_dir / "Per_Project_Model_Comparison.md" |
| model_comparison_md_path.write_text( |
| "".join(model_comparison_lines), encoding="utf-8" |
| ) |
| print(f"Created: {model_comparison_md_path}") |
|
|
| print("\n" + "=" * 60) |
| print("All time comparison summaries generated!") |
| print("=" * 60) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|