AINativeBench / data /processed /RQ2 /BookWriter-MCP /plot_agent_time_share_bars.py
王子睿
restructure + add files
8c10cf2
Raw
History Blame Contribute Delete
18.2 kB
#!/usr/bin/env python3
"""Plot per-model agent LLM+Tool time share across models for *mix projects.
Usage:
python plot_agent_time_share_bars.py
This script processes a single project directory. By default it uses the
current working directory, or a directory specified via --project-dir. It
reads the "agent_llm_tool_breakdown_by_model.csv" in that directory and
generates one stacked bar chart:
- One figure per project (per CSV).
- In each figure there are up to 7 bars, one per model, with fixed
left-to-right order:
GPT-5, GPT-4o-mini, DeepSeek-V3-1, DeepSeek-R1,
Gemini-2.5-flash, Gemini-2.5-flash-nothinking, Qwen3-235b.
- Each bar is stacked by agents, using total_agent_llm_tool_time_ms summed over
all occurrences for that (model, agent_name).
- Within a bar, these agents are normalized so that the total bar height is
1.0 (Latency Breakdown from 0 to 1).
- Each agent segment is annotated with its absolute time in ms.
The resulting PDF is written into each project folder as
"agent_time_share_bars.pdf".
"""
import argparse
import csv
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Optional
import math
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
# Use a serif font similar to "New Roma time" for all text
plt.rcParams["font.family"] = "Times New Roman"
# Ensure mathtext (used for bold slash) also renders in Times New Roman style
plt.rcParams["mathtext.fontset"] = "custom"
plt.rcParams["mathtext.rm"] = "Times New Roman"
plt.rcParams["mathtext.it"] = "Times New Roman:italic"
plt.rcParams["mathtext.bf"] = "Times New Roman:bold"
# Fixed model order (must match the names used in the CSV files)
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",
]
# Optional display labels
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",
}
# Color cycle for agents (pastel, low-saturation colors)
AGENT_COLOR_CYCLE: List[str] = [
"#88a4c9", # light blue
"#ff8696", # light pink
"#bbe6dd", # light teal
"#fde8b2", # light cream
"#c7b9e2", # light purple
"#f4b6c2", # light rose
]
def find_agent_breakdown_csvs(root: Path) -> List[Path]:
"""Find all agent_llm_tool_breakdown_by_model.csv under first-level subdirs."""
csv_paths: List[Path] = []
for sub in root.iterdir():
if not sub.is_dir():
continue
candidate = sub / "agent_llm_tool_breakdown_by_model.csv"
if candidate.exists():
csv_paths.append(candidate)
csv_paths.sort()
return csv_paths
def load_agent_totals(csv_path: Path) -> Dict[str, Dict[str, float]]:
"""Load per-model per-agent total_agent_llm_tool_time_ms from CSV.
Returns:
data[model][agent_name] = total_agent_llm_tool_time_ms
"""
data: Dict[str, Dict[str, float]] = defaultdict(dict)
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()
agent_name = (row.get("agent_name") or "").strip()
if not model or not agent_name:
continue
try:
val = float(row.get("total_agent_llm_tool_time_ms", "0") or 0)
except ValueError:
val = 0.0
data[model][agent_name] = data[model].get(agent_name, 0.0) + val
return data
def parse_agent_map_args(map_args: List[str]) -> Dict[str, str]:
"""Parse --agent-map raw:new arguments into a mapping dictionary."""
mapping: Dict[str, str] = {}
for item in map_args:
if ":" not in item:
continue
raw, mapped = item.split(":", 1)
raw = raw.strip()
mapped = mapped.strip()
if raw and mapped:
mapping[raw] = mapped
return mapping
def apply_agent_mapping(
model_to_agents: Dict[str, Dict[str, float]],
agent_name_map: Dict[str, str],
) -> Dict[str, Dict[str, float]]:
"""Aggregate agents according to a name mapping."""
if not agent_name_map:
return model_to_agents
mapped: Dict[str, Dict[str, float]] = {}
for model, agents in model_to_agents.items():
agg: Dict[str, float] = defaultdict(float)
for raw_agent, val in agents.items():
display = agent_name_map.get(raw_agent, raw_agent)
agg[display] += val
mapped[model] = dict(agg)
return mapped
def compute_percent_labels(shares: List[float]) -> List[float]:
total = sum(shares)
if total <= 0.0:
return [0.0 for _ in shares]
raw = [(s / total) * 10000.0 for s in shares]
floors = [int(math.floor(r)) for r in raw]
floor_sum = sum(floors)
diff = 10000 - floor_sum
remainders = [r - f for r, f in zip(raw, floors)]
order = sorted(range(len(shares)), key=lambda i: remainders[i], reverse=True)
if diff > 0:
for k in range(min(diff, len(order))):
floors[order[k]] += 1
elif diff < 0:
for k in range(min(-diff, len(order))):
floors[order[-1 - k]] -= 1
return [v / 100.0 for v in floors]
def plot_agent_time_share_bars(
project_name: str,
csv_path: Path,
model_to_agents: Dict[str, Dict[str, float]],
out_dir: Path,
agent_order: Optional[List[str]] = None,
) -> None:
"""Plot stacked agent time-share bars for one project across all models.
- One bar per model (7 bars total, some may be missing if no data).
- Each bar is stacked by agents, normalized so total height is 1.0.
- Each segment is annotated with its absolute ms value.
"""
# Collect the union of agents across all models
agent_names = set()
for agents in model_to_agents.values():
agent_names.update(agents.keys())
if not agent_names:
return
# Determine agent order.
# If an explicit order is provided (after mapping), use it (and append any
# missing agents by total time). Otherwise, order agents by total time
# across all models (descending).
def _agent_total(agent: str) -> float:
return sum(model_to_agents.get(m, {}).get(agent, 0.0) for m in MODEL_ORDER)
if agent_order:
known = list(agent_order)
missing = [a for a in agent_names if a not in known]
if missing:
missing_sorted = sorted(missing, key=_agent_total, reverse=True)
agent_order = known + missing_sorted
else:
agent_order = sorted(agent_names, key=_agent_total, reverse=True)
# Map agents to colors (cycle if more agents than colors)
agent_colors: Dict[str, str] = {}
for idx, agent in enumerate(agent_order):
agent_colors[agent] = AGENT_COLOR_CYCLE[idx % len(AGENT_COLOR_CYCLE)]
x = list(range(len(MODEL_ORDER)))
# Prepare per-agent shares and raw ms per model
shares_by_agent: Dict[str, List[float]] = {a: [] for a in agent_order}
ms_by_agent: Dict[str, List[float]] = {a: [] for a in agent_order}
for model in MODEL_ORDER:
agents = model_to_agents.get(model, {})
ms_vals = [float(agents.get(a, 0.0) or 0.0) for a in agent_order]
ks_vals = [v / 1000000.0 for v in ms_vals]
for agent, val in zip(agent_order, ks_vals):
shares_by_agent[agent].append(val)
ms_by_agent[agent].append(val)
max_total_s = 0.0
for idx in range(len(MODEL_ORDER)):
total = sum(shares_by_agent[agent][idx] for agent in agent_order)
if total > max_total_s:
max_total_s = total
fig, ax = plt.subplots(figsize=(7.5, 5))
# Build stacked bars
bottoms = [0.0 for _ in x]
bar_handles: Dict[str, any] = {}
bar_width = 0.98
for agent in agent_order:
heights = shares_by_agent[agent]
color = agent_colors[agent]
bars = ax.bar(
x,
heights,
bottom=bottoms,
color=color,
edgecolor="none",
width=bar_width,
)
bar_handles[agent] = bars
bottoms = [b + h for b, h in zip(bottoms, heights)]
# Reduce inner left/right whitespace inside the axes
margin = (1.0 - bar_width) / 2.0
ax.set_xlim(-0.5 + margin, len(MODEL_ORDER) - 0.5 - margin)
ax.yaxis.grid(True, linestyle="--", alpha=0.3, linewidth=0.8)
# Annotate percentage values inside each agent's bar segment
# Estimate minimum height needed for a label (fontsize 10)
# As a heuristic, we use ~2.5% of the max total as the minimum height
min_height_for_label = max_total_s * 0.025
# Minimum gap between labels to avoid overlap
min_gap = max_total_s * 0.04
# Process each model's bar separately
for model_idx in range(len(MODEL_ORDER)):
label_entries = [] # [y_center, x_center, percent_text, agent_idx]
for agent_idx, agent in enumerate(agent_order):
share_val = shares_by_agent[agent][model_idx]
if share_val <= 0.0:
continue
# Filter: only show label if segment height is sufficient
if share_val < min_height_for_label:
continue
# Calculate total for this model to compute percentage
total_for_model = sum(shares_by_agent[a][model_idx] for a in agent_order)
if total_for_model <= 0.0:
continue
percent = (share_val / total_for_model) * 100.0
# Calculate the exact vertical center position of this agent's segment
# Bars are stacked from bottom to top following agent_order
# Bottom edge: sum of all previous agents' heights
segment_bottom = sum(
shares_by_agent[a][model_idx] for a in agent_order[:agent_idx]
)
# Top edge: bottom + current agent's height
segment_top = segment_bottom + share_val
# Vertical center: exactly in the middle
y_center = (segment_bottom + segment_top) / 2.0
# Calculate the exact horizontal center position
bar = bar_handles[agent][model_idx]
x_center = bar.get_x() + bar.get_width() / 2.0
percent_text = f"${percent:.1f}\\%$"
label_entries.append([y_center, x_center, percent_text, agent_idx])
# Apply greedy spacing to reduce label overlap
if len(label_entries) > 1:
max_iterations = 50
for _ in range(max_iterations):
label_entries.sort(key=lambda e: e[0])
changed = False
for i in range(1, len(label_entries)):
y_prev = label_entries[i - 1][0]
y_curr = label_entries[i][0]
if y_curr - y_prev < min_gap:
needed = min_gap - (y_curr - y_prev)
shift_up = needed / 3.0
shift_down = 2.0 * shift_up
label_entries[i - 1][0] = y_prev - shift_down
label_entries[i][0] = y_curr + shift_up
changed = True
if not changed:
break
# Draw all labels for this model
for y_center, x_center, percent_text, agent_idx in label_entries:
ax.text(
x_center,
y_center,
percent_text,
ha="center",
va="center",
fontsize=10,
color="black",
fontweight="bold",
)
# X axis labels in fixed order
tick_labels = [MODEL_LABELS.get(m, m) for m in MODEL_ORDER]
ax.set_xticks(x)
ax.set_xticklabels(tick_labels, rotation=0, ha="center")
# Set tick label fonts: smaller on x axis to reduce overlap, keep y axis larger
ax.tick_params(axis="x", labelsize=10)
ax.tick_params(axis="y", labelsize=14)
ax.set_ylim(0.0, max_total_s * 1.15)
ax.set_ylabel("Latency Breakdown(×10³s)", fontsize=18)
# Add total time labels on top of each bar
for idx in range(len(MODEL_ORDER)):
total_time = sum(shares_by_agent[agent][idx] for agent in agent_order)
if total_time > 0:
offset = max_total_s * 0.02
label_y = total_time + offset
ax.text(
idx,
label_y,
f"{total_time:.2f}",
ha="center",
va="bottom",
fontsize=14,
fontweight="bold",
)
# Legend at top, horizontal, with inline "Agent" label.
# First legend: a standalone text label "Agent".
heading_handle = plt.Rectangle((0, 0), 1, 1, facecolor="none", edgecolor="none")
legend_anchor_y = 1.06
heading_legend_x = -0.08
heading_legend = ax.legend(
[heading_handle],
["Agent"],
fontsize=12,
loc="center left",
bbox_to_anchor=(heading_legend_x, legend_anchor_y),
ncol=1,
frameon=False,
columnspacing=0.8,
handletextpad=0.5,
)
# Second legend: grouped entries for individual agents.
# Legend order follows bar stack order from top to bottom
legend_order = list(reversed(agent_order))
# Create row-major order list: [item1, item2, dummy, item3, item4, item5]
row_order = []
for agent in legend_order:
row_order.append((agent, agent_colors[agent]))
# Add dummy placeholder at position 2 (after first 2 items)
row_order.insert(2, (None, None))
# Convert row-major to column-major for matplotlib legend (ncol=3)
# Row-major: [0,1,2], [3,4,5] -> Column-major: [0,3], [1,4], [2,5]
handles = []
labels = []
nrows = 2
ncols = 3
for col in range(ncols):
for row in range(nrows):
idx = row * ncols + col
if idx < len(row_order):
agent, color = row_order[idx]
if agent is None:
handles.append(
plt.Rectangle((0, 0), 1, 1, facecolor="none", edgecolor="none")
)
labels.append("")
else:
handles.append(
plt.Rectangle((0, 0), 1, 1, facecolor=color, edgecolor="none")
)
labels.append(agent)
# Use 3 columns to create 2-row layout: first row has 2 items + 1 dummy, second row has 3 items
ncols_agents = 3
agent_legend_x = 0.1
agent_legend = ax.legend(
handles,
labels,
fontsize=12,
loc="center left",
bbox_to_anchor=(agent_legend_x, legend_anchor_y),
ncol=ncols_agents,
frameon=False,
columnspacing=0.8,
handletextpad=0.5,
)
# Make sure both legends are drawn
ax.add_artist(heading_legend)
legend_texts = heading_legend.get_texts()
if legend_texts:
legend_texts[0].set_fontsize(18)
fig.subplots_adjust(left=0.09, right=0.999, bottom=0.167, top=0.88)
out_file = out_dir / f"{project_name}_agent_time_share_bars.pdf"
fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02)
plt.close(fig)
print(f"saved figure: {out_file}")
def parse_args() -> argparse.Namespace:
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="Plot stacked agent time-share bars for a single project.",
)
parser.add_argument(
"--project-dir",
type=str,
default=".",
help=(
"Project directory containing agent_llm_tool_breakdown_by_model.csv "
"(default: current working directory)."
),
)
parser.add_argument(
"--csv",
type=str,
default=None,
help=(
"Path to agent_llm_tool_breakdown_by_model.csv. "
"If not provided, defaults to <project-dir>/agent_llm_tool_breakdown_by_model.csv."
),
)
parser.add_argument(
"--agent-order",
type=str,
default=None,
help=(
"Comma-separated list of agent display names from TOP to BOTTOM. "
"The legend (left-to-right) will follow the same top-to-bottom order."
),
)
parser.add_argument(
"--agent-map",
type=str,
action="append",
default=[],
help=(
"Agent name mapping in the form 'raw_name:mapped_name'. "
"Can be specified multiple times."
),
)
return parser.parse_args()
def main() -> None:
args = parse_args()
project_dir = Path(args.project_dir).resolve()
if not project_dir.is_dir():
print(f"project_dir {project_dir} is not a directory")
return
if args.csv:
csv_path = Path(args.csv).resolve()
else:
csv_path = project_dir / "agent_llm_tool_breakdown_by_model.csv"
if not csv_path.exists():
print(f"{csv_path} not found")
return
project_name = project_dir.name
print(f"processing {csv_path} (project={project_name})")
model_to_agents_raw = load_agent_totals(csv_path)
if not model_to_agents_raw:
print(f" no agent data in {csv_path}")
return
agent_name_map = parse_agent_map_args(args.agent_map)
model_to_agents = apply_agent_mapping(model_to_agents_raw, agent_name_map)
agent_order: Optional[List[str]] = None
if args.agent_order:
order_top_to_bottom = [
name.strip() for name in args.agent_order.split(",") if name.strip()
]
if order_top_to_bottom:
# Internally we stack from bottom to top, so reverse the
# user-specified top-to-bottom order.
agent_order = list(reversed(order_top_to_bottom))
plot_agent_time_share_bars(
project_name,
csv_path,
model_to_agents,
project_dir,
agent_order=agent_order,
)
if __name__ == "__main__":
main()