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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
#!/usr/bin/env python3

"""Plot per-model non-LLM overhead breakdown across models for *A2A projects.

Usage:
    python plot_model_overhead_bars_a2a.py

This script scans all direct subdirectories under the current "Part2" folder
whose names end with "-A2A" (e.g. RecruitmentAssistant-A2A).
If a subdirectory contains a "performance_breakdown_summary_by_model.csv",
we read that file and, for that project, contribute one stacked bar in a
combined figure:

- One figure aggregating all A2A projects.
- On the x-axis, each A2A project is one bar group (same order as mix version):
    SQLAssistant-A2A,
    RecruitmentAssistant-A2A,
    LandingPageGenerator-A2A,
    SocialMediaManager-A2A,
    BookWriter-A2A.
- For each project, the bar is stacked by the following components (ms totals
  over all runs and all models in that project, then normalized within the bar):
    total_Tool_OVERHEAD,
    total_Framework_OVERHEAD,
    total_A2A_OVERHEAD,
    total_Server_OVERHEAD.
- Within a bar, these 4 components are normalized so that the total bar
  height is 1.0 (Latency Breakdown from 0 to 1).
- Each segment is annotated with its percentage of the bar (two decimals).

The resulting PDF is written into the Part2 folder as
"model_overhead_bars_a2a.pdf".
"""

import csv
from collections import defaultdict
from pathlib import Path
from typing import Dict, List
import math

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# Use a serif font similar to "New Roma time" for all text
plt.rcParams["font.family"] = "Times New Roman"

# 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",
}

# Short labels for project (A2A) names on the x-axis
PROJECT_LABELS: Dict[str, str] = {
    "SQLAssistant-A2A": "SQL Asst.",
    "RecruitmentAssistant-A2A": "Recruitment",
    "LandingPageGenerator-A2A": "Landing Pg.",
    "SocialMediaManager-A2A": "Social M. M.",
    "BookWriter-A2A": "Write Book",
    "__overall__": "Overall",
}

# Components to visualize (key in CSV -> logical name -> color)
COMPONENT_KEYS: List[str] = [
    "total_Tool_OVERHEAD",
    "total_Framework_OVERHEAD",
    "total_A2A_OVERHEAD",
    "total_Server_OVERHEAD",
]

COMPONENT_LABELS: Dict[str, str] = {
    "total_Tool_OVERHEAD": "Tool",
    "total_Framework_OVERHEAD": "Framework",
    "total_A2A_OVERHEAD": "A2A",
    "total_Server_OVERHEAD": "Server",
}

COMPONENT_COLORS: Dict[str, str] = {
    # Custom conference-style palette (low saturation, easily distinguishable)
    "total_Tool_OVERHEAD": "#88a4c9",
    "total_Framework_OVERHEAD": "#ff8696",
    "total_A2A_OVERHEAD": "#bbe6dd",
    "total_Server_OVERHEAD": "#fde8b2",
}


def find_model_summary_csvs_for_a2a(root: Path) -> List[Path]:
    """Find all performance_breakdown_summary_by_model.csv under *-A2A subdirs."""

    csv_paths: List[Path] = []
    for sub in root.iterdir():
        if not sub.is_dir():
            continue
        if not sub.name.endswith("-A2A"):
            continue
        candidate = sub / "performance_breakdown_summary_by_model.csv"
        if candidate.exists():
            csv_paths.append(candidate)
    csv_paths.sort()
    return csv_paths


def load_model_components(csv_path: Path) -> Dict[str, Dict[str, float]]:
    """Load per-model component times from a summary CSV.

    Returns:
        data[model][component_key] = value_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()
            if not model:
                continue
            for key in COMPONENT_KEYS:
                try:
                    val = float(row.get(key, "0") or 0)
                except ValueError:
                    val = 0.0
                data[model][key] = val
    return data


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 compute_a2a_component_shares(
    csv_paths: List[Path],
) -> Dict[str, Dict[str, float]]:
    """Compute component shares for each A2A project.

    For each project, we first sum the component times across all models,
    then normalize by the total non-LLM overhead (sum of 4 components).
    """

    project_shares: Dict[str, Dict[str, float]] = {}
    project_weights: Dict[str, float] = {}

    for csv_path in csv_paths:
        project_name = csv_path.parent.name
        model_to_components = load_model_components(csv_path)
        if not model_to_components:
            print(f"  no model data in {csv_path}, leaving empty placeholder")
            project_shares[project_name] = {k: 0.0 for k in COMPONENT_KEYS}
            continue

        sums = {k: 0.0 for k in COMPONENT_KEYS}
        total_ms_sum = 0.0

        # Aggregate over models
        for model in MODEL_ORDER:
            comps = model_to_components.get(model)
            if not comps:
                continue
            ms_vals = [float(comps.get(k, 0.0) or 0.0) for k in COMPONENT_KEYS]
            total_ms = sum(ms_vals)
            if total_ms <= 0.0:
                continue
            total_ms_sum += total_ms
            for key, val in zip(COMPONENT_KEYS, ms_vals):
                sums[key] += val

        if total_ms_sum <= 0.0:
            print(
                f"  all models have zero non-LLM overhead for {project_name}; "
                "leaving empty placeholder"
            )
            project_shares[project_name] = {k: 0.0 for k in COMPONENT_KEYS}
            project_weights[project_name] = 0.0
            continue

        project_shares[project_name] = {k: (v / total_ms_sum) for k, v in sums.items()}
        project_weights[project_name] = total_ms_sum

    return project_shares, project_weights


def plot_model_overhead_bars_a2a(
    project_names: List[str],
    project_shares: Dict[str, Dict[str, float]],
    out_dir: Path,
) -> None:
    """Plot stacked bars for all A2A projects (one bar per project).

    - Each bar corresponds to one A2A project.
    - Each bar is stacked by the four non-LLM overhead components listed
      in COMPONENT_KEYS, normalized to height 1.0.
    - Each segment is annotated with its percentage value.
    """

    x = list(range(len(project_names)))

    # Prepare per-component shares per project (already normalized)
    shares_by_comp: Dict[str, List[float]] = {k: [] for k in COMPONENT_KEYS}
    for name in project_names:
        shares = project_shares.get(name, {})
        for key in COMPONENT_KEYS:
            shares_by_comp[key].append(float(shares.get(key, 0.0) or 0.0))

    fig, ax = plt.subplots(figsize=(max(7.5, 1.0 * len(project_names)), 7))

    # Build stacked bars
    bottoms = [0.0 for _ in x]
    bar_handles = {}
    bar_width = 0.98
    for key in COMPONENT_KEYS:
        heights = shares_by_comp[key]
        color = COMPONENT_COLORS[key]
        bars = ax.bar(
            x,
            heights,
            bottom=bottoms,
            color=color,
            edgecolor="none",  # no bar borders
            width=bar_width,
        )
        bar_handles[key] = bars
        # Update bottoms for next component
        bottoms = [b + h for b, h in zip(bottoms, heights)]

    # Reduce inner left/right whitespace inside the axes: make the outer
    # bars almost touch the plot boundaries.
    margin = (1.0 - bar_width) / 2.0
    ax.set_xlim(-0.5 + margin, len(project_names) - 0.5 - margin)

    # Annotate percentage values for each segment (skip zeros)
    min_gap = 0.04  # minimum vertical gap between labels (in data coords 0-1)
    for idx, name in enumerate(project_names):
        shares = [
            float(project_shares.get(name, {}).get(k, 0.0) or 0.0)
            for k in COMPONENT_KEYS
        ]
        active_indices = [i for i, s in enumerate(shares) if s > 0.0]
        if not active_indices:
            continue
        active_shares = [shares[i] for i in active_indices]
        active_percents = compute_percent_labels(active_shares)

        # Build label entries: [y_center, x_center, text]
        label_entries = []
        for local_pos, comp_idx in enumerate(active_indices):
            key = COMPONENT_KEYS[comp_idx]
            share = shares[comp_idx]
            percent = active_percents[local_pos]
            if share <= 0.0:
                continue
            bars = bar_handles[key]
            bar = bars[idx]
            x_center = bar.get_x() + bar.get_width() / 2.0
            y_center = bar.get_y() + bar.get_height() / 2.0
            label_entries.append([y_center, x_center, f"{percent:.2f}"])

        # Nudge overlapping labels apart
        if len(label_entries) > 1:
            for _ in range(50):
                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)
                        label_entries[i - 1][0] = y_prev - needed / 2.0
                        label_entries[i][0] = y_curr + needed / 2.0
                        changed = True
                if not changed:
                    break

        for y_center, x_center, text in label_entries:
            ax.text(
                x_center,
                y_center,
                text,
                ha="center",
                va="center",
                fontsize=22,
                fontweight="bold",
            )

    # X axis labels: one per A2A project (use short labels where available)
    tick_labels = [PROJECT_LABELS.get(name, name) for name in project_names]
    ax.set_xticks(x)
    ax.set_xticklabels(tick_labels, rotation=30, ha="right")

    # Enlarge tick label fonts on both axes
    ax.tick_params(axis="x", labelsize=18, pad=6)
    ax.tick_params(axis="y", labelsize=24)
    for label in ax.get_xticklabels():
        label.set_fontweight("bold")
    for label in ax.get_yticklabels():
        label.set_fontweight("bold")

    ax.set_ylim(0.0, 1.0)
    ax.set_ylabel("(%)", fontsize=21, fontweight="bold", labelpad=-10)

    # Show y-axis ticks as plain integers
    ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y * 100:.0f}"))

    # Legend at top, horizontal, with inline "Component" label.
    # Use border-free patches in the legend as well.
    handles = [
        plt.Rectangle((0, 0), 1, 1, facecolor="none", edgecolor="none"),
    ]
    labels = ["Component"]
    # Legend order follows bar stack order from top to bottom:
    # Server (top), A2A, Framework, Tool (bottom).
    legend_order_keys = list(reversed(COMPONENT_KEYS))
    for key in legend_order_keys:
        handles.append(
            plt.Rectangle(
                (0, 0),
                1,
                1,
                facecolor=COMPONENT_COLORS[key],
                edgecolor="none",
            )
        )
        labels.append(COMPONENT_LABELS[key])

    legend = ax.legend(
        handles,
        labels,
        fontsize=19,
        loc="upper left",
        bbox_to_anchor=(-0.06, 1.09),
        ncol=len(labels),  # all legend items in a single horizontal row
        frameon=False,
        columnspacing=0.8,
        handletextpad=0.5,
        handlelength=0.3,
        prop={"weight": "bold", "size": 19},
    )

    # Make the heading label slightly larger
    legend_texts = legend.get_texts()
    if legend_texts:
        legend_texts[0].set_fontsize(20)
        legend_texts[0].set_fontweight("bold")

    # Tighten layout and crop extra whitespace (especially left/right)
    fig.tight_layout(pad=0.0)

    out_file = out_dir / "model_overhead_bars_a2a.pdf"
    fig.savefig(out_file, dpi=200, bbox_inches="tight", pad_inches=0.02)
    plt.close(fig)
    print(f"saved figure: {out_file}")


def main() -> None:
    # Assume this script is placed in Part2 directory
    part2_dir = Path(__file__).resolve().parent

    # Collect all *-A2A subdirectories under Part2 (whether they have data or not)
    a2a_dirs = [
        sub for sub in part2_dir.iterdir() if sub.is_dir() and sub.name.endswith("-A2A")
    ]
    a2a_dirs.sort(key=lambda p: p.name)

    if not a2a_dirs:
        print("no *-A2A subdirs found under Part2")
        return

    csv_paths = []
    for d in a2a_dirs:
        csv_path = d / "performance_breakdown_summary_by_model.csv"
        if not csv_path.exists():
            print(
                f"no performance_breakdown_summary_by_model.csv in {d}, "
                "leaving empty placeholder"
            )
        csv_paths.append(csv_path)

    # Filter out those without actual CSV files for computing shares
    existing_csv_paths = [p for p in csv_paths if p.exists()]

    if not existing_csv_paths:
        print("no model data in any *-A2A project; nothing to plot")
        return

    project_shares, project_weights = compute_a2a_component_shares(existing_csv_paths)

    project_names = [d.name for d in a2a_dirs]

    total_weight = 0.0
    for name in project_names:
        total_weight += float(project_weights.get(name, 0.0) or 0.0)

    if total_weight > 0.0:
        overall = {k: 0.0 for k in COMPONENT_KEYS}
        for name in project_names:
            weight = float(project_weights.get(name, 0.0) or 0.0)
            if weight <= 0.0:
                continue
            shares = project_shares.get(name, {})
            for key in COMPONENT_KEYS:
                overall[key] += float(shares.get(key, 0.0) or 0.0) * weight

        for key in COMPONENT_KEYS:
            overall[key] = overall[key] / total_weight

        project_shares["__overall__"] = overall
        project_names_with_overall = project_names + ["__overall__"]
    else:
        project_names_with_overall = project_names

    plot_model_overhead_bars_a2a(project_names_with_overall, project_shares, part2_dir)


if __name__ == "__main__":
    main()