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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#!/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.02
    # Minimum gap between labels to avoid overlap
    min_gap = max_total_s * 0.036

    # 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.
    handles = []
    labels = []
    # Legend order follows bar stack order from top to bottom
    legend_order = list(reversed(agent_order))
    for agent in legend_order:
        handles.append(
            plt.Rectangle(
                (0, 0),
                1,
                1,
                facecolor=agent_colors[agent],
                edgecolor="none",
            )
        )
        labels.append(agent)

    # Legend layout: 2 columns so the first row has 2 items and the second row the remaining 1
    ncols_agents = 2 if len(labels) > 0 else 1

    if len(labels) > ncols_agents:
        nrows = math.ceil(len(labels) / ncols_agents)
        reordered_handles = [None] * len(handles)
        reordered_labels = [None] * len(labels)
        for i in range(nrows):
            for j in range(ncols_agents):
                k = i * ncols_agents + j
                if k >= len(labels):
                    continue
                m = j * nrows + i
                if m >= len(labels):
                    continue
                reordered_handles[m] = handles[k]
                reordered_labels[m] = labels[k]
        handles = reordered_handles
        labels = reordered_labels

    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()