Download data/processed/RQ3/plot_total_tokens_violin.py from AINativeOps/AINativeBench: direct link, hf CLI and curl.
- Browser
- Download file 35.4 kB
-
https://huggingface.co/datasets/AINativeOps/AINativeBench/resolve/main/data/processed/RQ3/plot_total_tokens_violin.py
- Command line
-
hf download hf://datasets/AINativeOps/AINativeBench/data/processed/RQ3/plot_total_tokens_violin.py
-
curl -L -o plot_total_tokens_violin.py https://huggingface.co/datasets/AINativeOps/AINativeBench/resolve/main/data/processed/RQ3/plot_total_tokens_violin.py
35.4 kB
| #!/usr/bin/env python3 | |
| import csv | |
| import os | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| import numpy as np | |
| try: | |
| import matplotlib.pyplot as plt | |
| from matplotlib.ticker import FuncFormatter | |
| HAS_MATPLOTLIB = True | |
| except ModuleNotFoundError: | |
| plt = None # type: ignore[assignment] | |
| FuncFormatter = None # type: ignore[assignment] | |
| HAS_MATPLOTLIB = False | |
| if HAS_MATPLOTLIB: | |
| 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", | |
| } | |
| ARCH_ORDER: List[str] = [ | |
| "Unknown", | |
| "MCP", | |
| "A2A", | |
| "A2A_mix", | |
| ] | |
| 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", | |
| } | |
| STATUS_ORDER: List[str] = [ | |
| "success_no_retry", | |
| "success_with_retry", | |
| "failed", | |
| ] | |
| STATUS_TITLES: Dict[str, str] = { | |
| "success_no_retry": "Pass (no retries)", | |
| "success_with_retry": "Pass (with retries)", | |
| "failed": "Failure", | |
| } | |
| def infer_project_dir(file_path: str) -> str: | |
| raw = (file_path or "").strip() | |
| if not raw: | |
| return "" | |
| try: | |
| p = Path(raw) | |
| return p.parents[2].name | |
| except Exception: | |
| return "" | |
| def infer_architecture(project_dir: str) -> str: | |
| name = (project_dir or "").strip() | |
| if not name: | |
| return "Unknown" | |
| if name.endswith("-MCP"): | |
| return "MCP" | |
| if name.endswith("-H_A2A") or name.endswith("-H-A2A"): | |
| return "A2A_mix" | |
| if name.endswith("-A2A"): | |
| return "A2A" | |
| return "Unknown" | |
| def infer_base_task(project_dir: str) -> str: | |
| name = (project_dir or "").strip() | |
| for suffix in ("-H_A2A", "-H-A2A", "-MCP", "-A2A"): | |
| if name.endswith(suffix): | |
| return name[: -len(suffix)] | |
| return name | |
| def make_project_name(base_task: str, arch: str) -> str: | |
| task = (base_task or "").strip() | |
| if not task: | |
| return "" | |
| if arch == "Unknown": | |
| return task | |
| if arch == "MCP": | |
| return f"{task}-MCP" | |
| if arch == "A2A_mix": | |
| return f"{task}-H-A2A" | |
| if arch == "A2A": | |
| return f"{task}-A2A" | |
| return f"{task}-{arch}" | |
| def infer_architecture_from_project_name(project_name: str) -> str: | |
| name = (project_name or "").strip() | |
| if not name: | |
| return "Unknown" | |
| if name.endswith("-MCP"): | |
| return "MCP" | |
| if name.endswith("-H-A2A") or name.endswith("-H_A2A"): | |
| return "A2A_mix" | |
| if name.endswith("-A2A"): | |
| return "A2A" | |
| return "Unknown" | |
| def base_task_from_project_name(project_name: str) -> str: | |
| name = (project_name or "").strip() | |
| for suffix in ("-H-A2A", "-H_A2A", "-MCP", "-A2A"): | |
| if name.endswith(suffix): | |
| return name[: -len(suffix)] | |
| return name | |
| def export_violin_input_summary( | |
| projects: List[Tuple[str, str, str]], | |
| project_data: Dict[str, Dict[str, Dict[str, List[float]]]], | |
| out_dir: Path, | |
| ) -> None: | |
| if (os.environ.get("EXPORT_VIOLIN_INPUT") or "").strip() not in { | |
| "1", | |
| "true", | |
| "True", | |
| }: | |
| return | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_path = out_dir / "violin_input_summary.csv" | |
| with out_path.open("w", encoding="utf-8", newline="") as f: | |
| writer = csv.writer(f) | |
| writer.writerow( | |
| [ | |
| "project", | |
| "base_task", | |
| "architecture", | |
| "status_group", | |
| "model", | |
| "n", | |
| "mean", | |
| "median", | |
| "min", | |
| "max", | |
| ] | |
| ) | |
| for _, _, name in projects: | |
| pdata = project_data.get(name, {}) | |
| base_task = base_task_from_project_name(name) | |
| arch = infer_architecture_from_project_name(name) | |
| for status in STATUS_ORDER: | |
| by_model = pdata.get(status, {}) | |
| for model in MODEL_ORDER: | |
| vals = by_model.get(model, []) | |
| if not vals: | |
| continue | |
| arr = np.asarray(vals, dtype=float) | |
| writer.writerow( | |
| [ | |
| name, | |
| base_task, | |
| arch, | |
| status, | |
| model, | |
| int(arr.size), | |
| float(np.mean(arr)), | |
| float(np.median(arr)), | |
| float(np.min(arr)), | |
| float(np.max(arr)), | |
| ] | |
| ) | |
| print(f"saved violin input summary: {out_path}") | |
| def _nice_step(max_val: float, target_ticks: int = 6) -> float: | |
| if max_val <= 0: | |
| return 1.0 | |
| raw = max_val / float(target_ticks) | |
| magnitude = 10 ** int(np.floor(np.log10(raw))) | |
| residual = raw / magnitude | |
| if residual <= 1: | |
| nice = 1 | |
| elif residual <= 2: | |
| nice = 2 | |
| elif residual <= 5: | |
| nice = 5 | |
| else: | |
| nice = 10 | |
| return nice * magnitude | |
| def _token_formatter(x, pos): | |
| if x >= 1_000_000: | |
| return f"{x / 1_000_000:.1f}M" | |
| if x >= 1000: | |
| return f"{int(x // 1000)}k" | |
| return str(int(x)) | |
| def load_projects( | |
| details_csv: Path, | |
| ) -> Tuple[List[Tuple[str, str, str]], Dict[Tuple[str, str], str]]: | |
| present: Dict[str, set] = defaultdict(set) | |
| with details_csv.open("r", encoding="utf-8", newline="") as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| project_dir = infer_project_dir(row.get("file_path") or "") | |
| if not project_dir: | |
| continue | |
| arch = infer_architecture(project_dir) | |
| base_task = infer_base_task(project_dir) | |
| if not base_task: | |
| continue | |
| model = (row.get("model") or "").strip() | |
| if model and model not in MODEL_ORDER: | |
| continue | |
| total_raw = row.get("total_tokens") | |
| if total_raw is None or total_raw == "": | |
| continue | |
| try: | |
| float(total_raw) | |
| except ValueError: | |
| continue | |
| present[base_task].add(arch) | |
| projects: List[Tuple[str, str, str]] = [] | |
| project_map: Dict[Tuple[str, str], str] = {} | |
| for base_task in sorted(present.keys()): | |
| for arch in ARCH_ORDER: | |
| if arch not in present[base_task]: | |
| continue | |
| name = make_project_name(base_task, arch) | |
| project_map[(base_task, arch)] = name | |
| projects.append((base_task, arch, name)) | |
| return projects, project_map | |
| def classify_status(status_raw: str, with_retry_raw: str) -> str: | |
| s = (status_raw or "").strip().lower() | |
| w = (with_retry_raw or "").strip().lower() | |
| if s == "success" and w == "false": | |
| return "success_no_retry" | |
| if s == "success" and w == "true": | |
| return "success_with_retry" | |
| return "failed" | |
| def load_total_tokens( | |
| details_csv: Path, project_map: Dict[Tuple[str, str], str] | |
| ) -> Dict[str, Dict[str, Dict[str, List[float]]]]: | |
| data: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict( | |
| lambda: defaultdict(lambda: defaultdict(list)) | |
| ) | |
| with details_csv.open("r", encoding="utf-8", newline="") as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| project_dir = infer_project_dir(row.get("file_path") or "") | |
| if not project_dir: | |
| continue | |
| task = infer_base_task(project_dir) | |
| arch = infer_architecture(project_dir) | |
| key = (task, arch) | |
| project_name = project_map.get(key) or make_project_name(task, arch) | |
| if not project_name: | |
| continue | |
| model = (row.get("model") or "").strip() | |
| if model not in MODEL_ORDER: | |
| continue | |
| status_group = classify_status(row.get("status"), row.get("with_retry")) | |
| total_raw = row.get("total_tokens") | |
| if total_raw is None or total_raw == "": | |
| continue | |
| try: | |
| total_val = float(total_raw) | |
| except ValueError: | |
| continue | |
| data[project_name][status_group][model].append(total_val) | |
| return data | |
| def load_all_token_data( | |
| details_csv: Path, project_map: Dict[Tuple[str, str], str] | |
| ) -> Tuple[ | |
| Dict[str, Dict[str, Dict[str, List[float]]]], | |
| Dict[str, Dict[str, Dict[str, List[float]]]], | |
| Dict[str, List[float]], | |
| ]: | |
| """ | |
| Load token statistics with two views: | |
| - project_data: keyed by project name (task-architecture) -> status -> model -> list of totals | |
| - arch_model_data: keyed by task -> architecture -> model -> list of totals (across all statuses) | |
| - overall_status_values: keyed by status -> all token totals | |
| """ | |
| project_data: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict( | |
| lambda: defaultdict(lambda: defaultdict(list)) | |
| ) | |
| arch_model_data: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict( | |
| lambda: defaultdict(lambda: defaultdict(list)) | |
| ) | |
| overall_status_values: Dict[str, List[float]] = defaultdict(list) | |
| with details_csv.open("r", encoding="utf-8", newline="") as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| project_dir = infer_project_dir(row.get("file_path") or "") | |
| if not project_dir: | |
| continue | |
| task = infer_base_task(project_dir) | |
| arch = infer_architecture(project_dir) | |
| key = (task, arch) | |
| project_name = project_map.get(key) or make_project_name(task, arch) | |
| if not project_name: | |
| continue | |
| model = (row.get("model") or "").strip() | |
| if model not in MODEL_ORDER: | |
| continue | |
| status_group = classify_status(row.get("status"), row.get("with_retry")) | |
| total_raw = row.get("total_tokens") | |
| if total_raw is None or total_raw == "": | |
| continue | |
| try: | |
| total_val = float(total_raw) | |
| except ValueError: | |
| continue | |
| project_data[project_name][status_group][model].append(total_val) | |
| arch_model_data[task][arch][model].append(total_val) | |
| overall_status_values[status_group].append(total_val) | |
| return project_data, arch_model_data, overall_status_values | |
| def summarize_values(values: List[float]) -> Dict[str, float]: | |
| if not values: | |
| return {} | |
| arr = np.asarray(values, dtype=float) | |
| return { | |
| "count": int(arr.size), | |
| "mean": float(np.mean(arr)), | |
| } | |
| def _fmt_number(val: float) -> str: | |
| return f"{val:,.0f}" | |
| def _fmt_mean(stats: Dict[str, float]) -> str: | |
| if not stats: | |
| return "-" | |
| return _fmt_number(stats.get("mean", 0.0)) | |
| def _safe_mean(values: List[float]) -> float: | |
| if not values: | |
| return None # type: ignore[return-value] | |
| return float(np.mean(np.asarray(values, dtype=float))) | |
| def _fmt_mean_val(val: float) -> str: | |
| if val is None: | |
| return "-" | |
| return _fmt_number(val) | |
| def _fmt_delta(new_val: float, old_val: float) -> str: | |
| if new_val is None or old_val is None: | |
| return "-" | |
| diff = new_val - old_val | |
| pct_str = "n/a" if old_val == 0 else f"{(diff / old_val) * 100:.1f}%" | |
| sign = "+" if diff >= 0 else "" | |
| return f"{sign}{_fmt_number(diff)} ({pct_str})" | |
| def generate_project_stats_md( | |
| projects: List[Tuple[str, str, str]], | |
| project_data: Dict[str, Dict[str, Dict[str, List[float]]]], | |
| overall_status_values: Dict[str, List[float]], | |
| out_dir: Path, | |
| ) -> None: | |
| def _base_task_name(task: str) -> str: | |
| suffixes = ("-H_A2A", "-H-A2A", "-MCP", "-A2A") | |
| for suffix in suffixes: | |
| if task.endswith(suffix): | |
| return task[: -len(suffix)] | |
| return task | |
| def build_series_data() -> Dict[str, Dict[str, Dict[str, List[float]]]]: | |
| series: Dict[str, Dict[str, Dict[str, List[float]]]] = defaultdict( | |
| lambda: defaultdict(lambda: defaultdict(list)) | |
| ) | |
| for task, arch, name in projects: | |
| base_task = _base_task_name(task) | |
| pdata = project_data.get(name, {}) | |
| for status in STATUS_ORDER: | |
| by_model = pdata.get(status, {}) | |
| for model, vals in by_model.items(): | |
| series[base_task][status][model].extend(vals) | |
| return series | |
| def append_status_table( | |
| lines: List[str], | |
| by_status: Dict[str, Dict[str, List[float]]], | |
| statuses: List[str], | |
| ) -> None: | |
| for status in statuses: | |
| by_model = by_status.get(status, {}) | |
| if not by_model: | |
| continue | |
| lines.append("") | |
| lines.append(f"### {STATUS_TITLES.get(status, status)}") | |
| lines.append("") | |
| lines.append("| Model | n | Mean |") | |
| lines.append("| --- | --- | --- |") | |
| for model in MODEL_ORDER: | |
| vals = by_model.get(model, []) | |
| stats = summarize_values(vals) | |
| mean = _fmt_mean(stats) | |
| lines.append( | |
| f"| {MODEL_LABELS.get(model, model)} | {stats.get('count', 0)} | {mean} |" | |
| ) | |
| def append_status_comparison( | |
| lines: List[str], | |
| label: str, | |
| by_status: Dict[str, Dict[str, List[float]]], | |
| base_status: str, | |
| comp_status: str, | |
| ) -> None: | |
| lines.append("") | |
| lines.append(label) | |
| lines.append("") | |
| lines.append( | |
| f"| Model | {STATUS_TITLES[base_status]} mean | {STATUS_TITLES[comp_status]} mean | Δ vs {STATUS_TITLES[base_status]} |" | |
| ) | |
| lines.append("| --- | --- | --- | --- |") | |
| for model in MODEL_ORDER: | |
| base_mean = _safe_mean(by_status.get(base_status, {}).get(model, [])) | |
| comp_mean = _safe_mean(by_status.get(comp_status, {}).get(model, [])) | |
| lines.append( | |
| "| " | |
| + " | ".join( | |
| [ | |
| MODEL_LABELS.get(model, model), | |
| _fmt_mean_val(base_mean), | |
| _fmt_mean_val(comp_mean), | |
| _fmt_delta(comp_mean, base_mean), | |
| ] | |
| ) | |
| + " |" | |
| ) | |
| def build_report( | |
| title: str, | |
| base_status: str, | |
| comp_status: str, | |
| filename: str, | |
| ) -> None: | |
| statuses = [base_status, comp_status] | |
| series_data = build_series_data() | |
| lines: List[str] = [] | |
| lines.append(f"# Project token statistics - {title}") | |
| lines.append("") | |
| lines.append("## Overall status token summary") | |
| lines.append("") | |
| lines.append("| Status | n | Mean |") | |
| lines.append("| --- | --- | --- |") | |
| for status in statuses: | |
| stats = summarize_values(overall_status_values.get(status, [])) | |
| mean = _fmt_mean(stats) | |
| lines.append( | |
| f"| {STATUS_TITLES.get(status, status)} | {stats.get('count', 0)} | {mean} |" | |
| ) | |
| for task, arch, name in projects: | |
| pdata = project_data.get(name, {}) | |
| lines.append("") | |
| lines.append(f"## {name}") | |
| if not pdata: | |
| lines.append("") | |
| lines.append("> No token data found.") | |
| continue | |
| append_status_table(lines, pdata, statuses) | |
| append_status_comparison( | |
| lines, | |
| f"### {STATUS_TITLES[base_status]} vs {STATUS_TITLES[comp_status]} (mean, abs & %)", | |
| pdata, | |
| base_status, | |
| comp_status, | |
| ) | |
| # Series-level aggregation by task prefix | |
| lines.append("") | |
| lines.append("## Series aggregates (by task prefix)") | |
| for task in sorted(series_data.keys()): | |
| sdata = series_data[task] | |
| lines.append("") | |
| lines.append(f"### {task} (aggregated across variants)") | |
| append_status_table(lines, sdata, statuses) | |
| append_status_comparison( | |
| lines, | |
| f"#### {STATUS_TITLES[base_status]} vs {STATUS_TITLES[comp_status]} (mean, abs & %)", | |
| sdata, | |
| base_status, | |
| comp_status, | |
| ) | |
| out_path = out_dir / filename | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_path.write_text("\n".join(lines), encoding="utf-8") | |
| print(f"saved markdown: {out_path}") | |
| build_report( | |
| "Pass (no retry) vs Pass (with retry)", | |
| "success_no_retry", | |
| "success_with_retry", | |
| "project_token_stats_pass_vs_retry.md", | |
| ) | |
| build_report( | |
| "Pass (no retry) vs Failure", | |
| "success_no_retry", | |
| "failed", | |
| "project_token_stats_pass_vs_failure.md", | |
| ) | |
| def generate_architecture_deltas_md( | |
| projects: List[Tuple[str, str, str]], | |
| arch_model_data: Dict[str, Dict[str, Dict[str, List[float]]]], | |
| out_dir: Path, | |
| ) -> None: | |
| def write_report(title: str, chain: List[str], filename: str) -> None: | |
| lines: List[str] = [] | |
| lines.append("# Token shifts across architectures") | |
| lines.append("") | |
| lines.append(f"Series: **{title}**") | |
| lines.append("") | |
| lines.append( | |
| "Each table shows the absolute change (Δ) and the relative percentage change of the mean total tokens." | |
| ) | |
| def render_pair(task_arch_data: Dict[str, Dict[str, List[float]]]) -> None: | |
| arch_display = { | |
| "Unknown": "Pure CrewAI", | |
| "MCP": "MCP", | |
| "A2A": "A2A", | |
| "A2A_mix": "H-A2A", | |
| } | |
| header = f"| Model | {arch_display[chain[0]]} | {arch_display[chain[1]]} | Δ {arch_display[chain[1]]}-{arch_display[chain[0]]} |" | |
| sep = "| --- | --- | --- | --- |" | |
| lines.append("") | |
| lines.append(header) | |
| lines.append(sep) | |
| for model in MODEL_ORDER: | |
| left_vals = task_arch_data.get(chain[0], {}).get(model, []) | |
| right_vals = task_arch_data.get(chain[1], {}).get(model, []) | |
| left_mean = float(np.mean(left_vals)) if left_vals else None | |
| right_mean = float(np.mean(right_vals)) if right_vals else None | |
| row = [ | |
| MODEL_LABELS.get(model, model), | |
| "-" if left_mean is None else _fmt_number(left_mean), | |
| "-" if right_mean is None else _fmt_number(right_mean), | |
| _fmt_delta(right_mean, left_mean), | |
| ] | |
| lines.append("| " + " | ".join(row) + " |") | |
| lines.append("") | |
| lines.append("Project-level average (all models combined)") | |
| lines.append("") | |
| lines.append( | |
| f"| Metric | {arch_display[chain[0]]} | {arch_display[chain[1]]} | Δ {arch_display[chain[1]]}-{arch_display[chain[0]]} |" | |
| ) | |
| lines.append("| --- | --- | --- | --- |") | |
| def _mean_all(arch: str) -> float: | |
| combined: List[float] = [] | |
| for vals in task_arch_data.get(arch, {}).values(): | |
| combined.extend(vals) | |
| return float(np.mean(combined)) if combined else None | |
| left_all = _mean_all(chain[0]) | |
| right_all = _mean_all(chain[1]) | |
| lines.append( | |
| "| " | |
| + " | ".join( | |
| [ | |
| "Avg tokens (all models)", | |
| "-" if left_all is None else _fmt_number(left_all), | |
| "-" if right_all is None else _fmt_number(right_all), | |
| _fmt_delta(right_all, left_all), | |
| ] | |
| ) | |
| + " |" | |
| ) | |
| task_set = {t for t, _, _ in projects} | |
| for task in sorted(task_set): | |
| task_arch_data = arch_model_data.get(task, {}) | |
| arches = set(task_arch_data.keys()) | |
| if not task_arch_data: | |
| continue | |
| if not set(chain).issubset(arches): | |
| continue | |
| lines.append("") | |
| lines.append(f"## {task}") | |
| render_pair(task_arch_data) | |
| out_path = out_dir / filename | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_path.write_text("\n".join(lines), encoding="utf-8") | |
| print(f"saved markdown: {out_path}") | |
| def write_a2a_to_h_a2a_report(filename: str) -> None: | |
| lines: List[str] = [] | |
| lines.append("# Token shifts across architectures") | |
| lines.append("") | |
| lines.append("Series: **A2A → H-A2A**") | |
| lines.append("") | |
| lines.append( | |
| "Each table shows the absolute change (Δ) and the relative percentage change of the mean total tokens." | |
| ) | |
| def render_pair( | |
| task_base: str, | |
| left_arch_data: Dict[str, Dict[str, List[float]]], | |
| right_arch_data: Dict[str, Dict[str, List[float]]], | |
| ) -> None: | |
| right_label = "H-A2A" | |
| header = f"| Model | A2A | {right_label} | Δ {right_label}-A2A |" | |
| sep = "| --- | --- | --- | --- |" | |
| lines.append("") | |
| lines.append(header) | |
| lines.append(sep) | |
| for model in MODEL_ORDER: | |
| left_vals = left_arch_data.get("A2A", {}).get(model, []) | |
| right_vals: List[float] = [] | |
| for arch_vals in right_arch_data.values(): | |
| right_vals.extend(arch_vals.get(model, [])) | |
| left_mean = float(np.mean(left_vals)) if left_vals else None | |
| right_mean = float(np.mean(right_vals)) if right_vals else None | |
| row = [ | |
| MODEL_LABELS.get(model, model), | |
| "-" if left_mean is None else _fmt_number(left_mean), | |
| "-" if right_mean is None else _fmt_number(right_mean), | |
| _fmt_delta(right_mean, left_mean), | |
| ] | |
| lines.append("| " + " | ".join(row) + " |") | |
| lines.append("") | |
| lines.append("Project-level average (all models combined)") | |
| lines.append("") | |
| lines.append(f"| Metric | A2A | {right_label} | Δ {right_label}-A2A |") | |
| lines.append("| --- | --- | --- | --- |") | |
| def _mean_all( | |
| arch_data: Dict[str, Dict[str, List[float]]], arch: str | |
| ) -> float: | |
| combined: List[float] = [] | |
| for vals in arch_data.get(arch, {}).values(): | |
| combined.extend(vals) | |
| return float(np.mean(combined)) if combined else None | |
| left_all = _mean_all(left_arch_data, "A2A") | |
| right_combined: List[float] = [] | |
| for arch_vals in right_arch_data.values(): | |
| for vals in arch_vals.values(): | |
| right_combined.extend(vals) | |
| right_all = float(np.mean(right_combined)) if right_combined else None | |
| lines.append( | |
| "| " | |
| + " | ".join( | |
| [ | |
| "Avg tokens (all models)", | |
| "-" if left_all is None else _fmt_number(left_all), | |
| "-" if right_all is None else _fmt_number(right_all), | |
| _fmt_delta(right_all, left_all), | |
| ] | |
| ) | |
| + " |" | |
| ) | |
| task_set = sorted({t for t, _, _ in projects}) | |
| for task in task_set: | |
| task_arch_data = arch_model_data.get(task, {}) | |
| if not task_arch_data: | |
| continue | |
| if "A2A" not in task_arch_data or "A2A_mix" not in task_arch_data: | |
| continue | |
| left_arch_data = {"A2A": task_arch_data.get("A2A", {})} | |
| right_arch_data = {"A2A_mix": task_arch_data.get("A2A_mix", {})} | |
| lines.append("") | |
| lines.append(f"## {task}") | |
| render_pair(task, left_arch_data, right_arch_data) | |
| out_path = out_dir / filename | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_path.write_text("\n".join(lines), encoding="utf-8") | |
| print(f"saved markdown: {out_path}") | |
| write_report( | |
| "Pure CrewAI → MCP", | |
| ["Unknown", "MCP"], | |
| "architecture_token_deltas_crewai_to_mcp.md", | |
| ) | |
| write_report("MCP → A2A", ["MCP", "A2A"], "architecture_token_deltas_mcp_to_a2a.md") | |
| write_a2a_to_h_a2a_report("architecture_token_deltas_a2a_to_h-a2a.md") | |
| def generate_project_model_distribution_md( | |
| projects: List[Tuple[str, str, str]], | |
| project_data: Dict[str, Dict[str, Dict[str, List[float]]]], | |
| out_dir: Path, | |
| ) -> None: | |
| lines: List[str] = [] | |
| lines.append("# Model token distribution per project") | |
| lines.append("") | |
| lines.append( | |
| "Per-project, per-model total token usage with breakdown by execution outcome. " | |
| "Only the mean total tokens are reported. Baseline vs maximum is computed from the overall mean aggregated across all three statuses." | |
| ) | |
| def _base_task_name(task: str) -> str: | |
| suffixes = ("-H_A2A", "-H-A2A", "-MCP", "-A2A") | |
| for suffix in suffixes: | |
| if task.endswith(suffix): | |
| return task[: -len(suffix)] | |
| return task | |
| # Collect overall and series data | |
| overall_raw: Dict[str, List[float]] = defaultdict(list) | |
| series_raw: Dict[str, Dict[str, List[float]]] = defaultdict( | |
| lambda: defaultdict(list) | |
| ) | |
| for task, arch, name in projects: | |
| pdata = project_data.get(name, {}) | |
| base_task = _base_task_name(task) | |
| for model in MODEL_ORDER: | |
| for status in STATUS_ORDER: | |
| vals = pdata.get(status, {}).get(model, []) | |
| overall_raw[model].extend(vals) | |
| series_raw[base_task][model].extend(vals) | |
| def append_dist_section( | |
| lines: List[str], | |
| title: str, | |
| raw_data: Dict[str, List[float]], | |
| level_label: str = "###", | |
| ) -> Dict[str, float]: | |
| lines.append("") | |
| lines.append(f"{level_label} {title}") | |
| lines.append("| Model | n | Mean |") | |
| lines.append("| --- | --- | --- |") | |
| means: Dict[str, float] = {} | |
| for model in MODEL_ORDER: | |
| vals = raw_data.get(model, []) | |
| stats = summarize_values(vals) | |
| if stats: | |
| means[model] = stats["mean"] | |
| mean_str = _fmt_mean(stats) | |
| lines.append( | |
| f"| {MODEL_LABELS.get(model, model)} | {stats.get('count', 0)} | {mean_str} |" | |
| ) | |
| lines.append("") | |
| lines.append(f"{level_label} Baseline vs maximum ({title})") | |
| if means: | |
| min_model = min(means.items(), key=lambda kv: kv[1]) | |
| max_model = max(means.items(), key=lambda kv: kv[1]) | |
| diff = max_model[1] - min_model[1] | |
| ratio = ( | |
| "n/a" if min_model[1] == 0 else f"{(diff / min_model[1]) * 100:.1f}%" | |
| ) | |
| lines.append( | |
| f"- Baseline (lowest mean): {MODEL_LABELS.get(min_model[0], min_model[0])} " | |
| f"= {_fmt_number(min_model[1])} tokens" | |
| ) | |
| lines.append( | |
| f"- Maximum (highest mean): {MODEL_LABELS.get(max_model[0], max_model[0])} " | |
| f"= {_fmt_number(max_model[1])} tokens" | |
| ) | |
| lines.append(f"- Delta: {_fmt_number(diff)} ({ratio})") | |
| else: | |
| lines.append("- No data to compare.") | |
| return means | |
| # 1. Global Overall Summary | |
| lines.append("") | |
| lines.append("## Global Summary (All Projects Combined)") | |
| append_dist_section(lines, "Overall per-model total tokens", overall_raw) | |
| # 2. Series Aggregates | |
| lines.append("") | |
| lines.append("## Series Aggregates (Aggregated by Base Task)") | |
| for base_task in sorted(series_raw.keys()): | |
| lines.append("") | |
| lines.append(f"### Series: {base_task}") | |
| append_dist_section( | |
| lines, f"Aggregated tokens for {base_task}", series_raw[base_task], "####" | |
| ) | |
| # 3. Individual Projects | |
| lines.append("") | |
| lines.append("## Individual Project Details") | |
| for task, arch, name in projects: | |
| pdata = project_data.get(name, {}) | |
| lines.append("") | |
| lines.append(f"### {name}") | |
| if not pdata: | |
| lines.append("") | |
| lines.append("> No token data found.") | |
| continue | |
| project_raw: Dict[str, List[float]] = {} | |
| for model in MODEL_ORDER: | |
| combined: List[float] = [] | |
| for status in STATUS_ORDER: | |
| combined.extend(pdata.get(status, {}).get(model, [])) | |
| project_raw[model] = combined | |
| append_dist_section(lines, "Per-model total tokens", project_raw, "####") | |
| out_path = out_dir / "project_model_distribution.md" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_path.write_text("\n".join(lines), encoding="utf-8") | |
| print(f"saved markdown: {out_path}") | |
| def plot_violin_for_project( | |
| project_name: str, | |
| project_data: Dict[str, Dict[str, List[float]]], | |
| out_dir: Path, | |
| global_max: float, | |
| ) -> None: | |
| if not HAS_MATPLOTLIB: | |
| print("matplotlib not available; skip violin plots") | |
| return | |
| any_values = False | |
| for status in STATUS_ORDER: | |
| by_model = project_data.get(status, {}) | |
| for m in MODEL_ORDER: | |
| vals = by_model.get(m) | |
| if vals: | |
| any_values = True | |
| if not any_values or global_max <= 0.0: | |
| print(f"no total_tokens for project {project_name}, skip") | |
| return | |
| fig, axes = plt.subplots(1, len(STATUS_ORDER), figsize=(10, 6), sharey=True) | |
| if len(STATUS_ORDER) == 1: | |
| axes = [axes] | |
| y_max = global_max * 1.02 | |
| target_ticks = 6 | |
| while True: | |
| step = _nice_step(y_max, target_ticks=target_ticks) | |
| y_max_rounded = float(np.ceil(y_max / step) * step) | |
| if y_max_rounded <= y_max * 1.08 or target_ticks >= 12: | |
| break | |
| target_ticks += 2 | |
| for idx_status, status in enumerate(STATUS_ORDER): | |
| ax = axes[idx_status] | |
| by_model = project_data.get(status, {}) | |
| for i, model in enumerate(MODEL_ORDER, start=1): | |
| vals = by_model.get(model) | |
| if not vals: | |
| continue | |
| v_max = float(max(vals)) | |
| parts = ax.violinplot( | |
| vals, | |
| positions=[i], | |
| widths=0.8, | |
| showmeans=False, | |
| showextrema=False, | |
| showmedians=False, | |
| ) | |
| for pc in parts["bodies"]: | |
| pc.set_facecolor(MODEL_COLORS.get(model, "black")) | |
| pc.set_edgecolor("black") | |
| pc.set_alpha(0.7) | |
| median_val = float(np.median(vals)) | |
| ax.hlines( | |
| median_val, | |
| i - 0.3, | |
| i + 0.3, | |
| colors="black", | |
| linewidth=1.0, | |
| ) | |
| if v_max > y_max_rounded: | |
| y_pos = y_max_rounded * 0.985 | |
| ax.plot([i], [y_pos], marker="^", color="black", markersize=4) | |
| ax.text( | |
| i, | |
| y_pos, | |
| f">{_token_formatter(v_max, 0)}", | |
| ha="center", | |
| va="top", | |
| fontsize=10, | |
| ) | |
| ax.set_title(STATUS_TITLES.get(status, status), fontsize=24, fontweight="bold") | |
| ax.set_xticks(range(1, len(MODEL_ORDER) + 1)) | |
| ax.set_xticklabels([]) | |
| ax.set_xlim(0.5, len(MODEL_ORDER) + 0.5) | |
| ax.set_ylim(0, y_max_rounded) | |
| yticks = np.arange(0, y_max_rounded + step * 0.5, step) | |
| ax.set_yticks(yticks) | |
| ax.yaxis.set_major_formatter(FuncFormatter(_token_formatter)) | |
| ax.grid(axis="y", linestyle="-", linewidth=0.5, alpha=0.3) | |
| ax.tick_params(axis="y", labelsize=22) | |
| ax.tick_params(axis="x", labelsize=16) | |
| for lbl in ax.get_yticklabels(): | |
| lbl.set_fontweight("bold") | |
| if idx_status == 0: | |
| ax.set_ylabel("") | |
| fig.subplots_adjust(left=0.07, right=0.98, bottom=0.10, top=0.98, wspace=0.03) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| out_path = out_dir / f"{project_name}_total_tokens_violin.pdf" | |
| fig.savefig(out_path, format="pdf", dpi=300, bbox_inches="tight", pad_inches=0.02) | |
| plt.close(fig) | |
| print(f"saved violin figure: {out_path}") | |
| def main() -> None: | |
| part1_dir = Path(__file__).resolve().parent | |
| details_csv = part1_dir / "task_token_statistics-DETAILS.csv" | |
| if not details_csv.exists(): | |
| details_csv = ( | |
| part1_dir / "performance_reports" / "task_token_statistics-DETAILS.csv" | |
| ) | |
| out_dir = part1_dir / "Violin" | |
| projects, project_map = load_projects(details_csv) | |
| project_data, arch_model_data, overall_status_values = load_all_token_data( | |
| details_csv, project_map | |
| ) | |
| export_violin_input_summary(projects, project_data, out_dir) | |
| # Compute a shared y-axis maximum per task so that all architectures | |
| # of the same task use the same vertical scale in their violin plots. | |
| task_max_values: Dict[str, float] = {} | |
| task_values: Dict[str, List[float]] = defaultdict(list) | |
| for task, arch, name in projects: | |
| pdata = project_data.get(name, {}) | |
| for status in STATUS_ORDER: | |
| by_model = pdata.get(status, {}) | |
| for m in MODEL_ORDER: | |
| vals = by_model.get(m) | |
| if vals: | |
| task_values[task].extend(vals) | |
| for task, vals in task_values.items(): | |
| if not vals: | |
| continue | |
| arr = np.asarray(vals, dtype=float) | |
| abs_max = float(np.max(arr)) | |
| if abs_max <= 0.0: | |
| continue | |
| task_max_values[task] = abs_max | |
| for task, arch, name in projects: | |
| pdata = project_data.get(name, {}) | |
| global_max = task_max_values.get(task, 0.0) | |
| try: | |
| plot_violin_for_project(name, pdata, out_dir, global_max) | |
| except Exception as exc: | |
| print(f"error plotting project {name}: {exc}") | |
| # Generate markdown summaries | |
| generate_project_stats_md(projects, project_data, overall_status_values, out_dir) | |
| generate_architecture_deltas_md(projects, arch_model_data, out_dir) | |
| generate_project_model_distribution_md(projects, project_data, out_dir) | |
| if __name__ == "__main__": | |
| main() | |