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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
#!/usr/bin/env python3
"""
Extract Majority Vote and consistency breakdown data for all 'react with code' agents.

This script computes:
- Pass@k: At least 1 trial succeeds
- Majority@k: Majority of trials succeed
- All@k: All trials succeed
- Consistency breakdown: Consistent Correct, Consistent Wrong, Inconsistent

Output is saved to paper_analysis/react with code/resources/figures/consistency/ as CSV files.
"""

import json
import sys
from pathlib import Path
from itertools import combinations
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm

# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from analysis_src.utils import (
    get_model_name,
    find_react_with_code_dirs,
    read_judge_outputs_from_dir,
    extract_trial_scores_from_judge_outputs,
    filter_scenarios_with_min_runs,
)

from analysis_src.model_styles import (
    get_model_style, MIN_FONT_SIZE, SINGLE_COLUMN_WIDTH, DOUBLE_COLUMN_WIDTH, PLOT_PARAMETERS
)

# Paths
LEADERBOARD_DIR = PROJECT_ROOT / "ITBench-SRE-Agent" / "ITBench-Trajectories" / "ReAct-Agent-Trajectories"
OUTPUT_DIR = PROJECT_ROOT / "ITBench-SRE-Agent" / "ITBench-Trajectories" / "output" / "consistency"

# Minimum runs per scenario required for inclusion
MIN_RUNS_PER_SCENARIO = 2

# Minimum scenarios needed after filtering
MIN_QUALIFYING_SCENARIOS = 20

# Success threshold for binary classification
SUCCESS_THRESHOLD = 0.5

def compute_majority_vote_metrics(
    scenario_trials: dict[str, list[float]],
    success_threshold: float = SUCCESS_THRESHOLD
) -> dict:
    """
    Compute majority vote and consistency metrics.
    
    Returns dict with:
    - pass_at_k: At least 1 trial succeeds
    - majority_at_k: Majority of trials succeed
    - all_at_k: All trials succeed
    - consistent_correct: All trials succeed
    - consistent_wrong: All trials fail
    - inconsistent: Mixed results
    """
    scenarios = list(scenario_trials.keys())
    n_trials_list = [len(trials) for trials in scenario_trials.values()]
    
    if not n_trials_list:
        return None
    
    k = min(n_trials_list)
    n_scenarios = len(scenarios)
    
    if n_scenarios == 0 or k < 1:
        return None
    
    pass_at_k = 0
    majority_at_k = 0
    all_at_k = 0
    consistent_correct = 0
    consistent_wrong = 0
    inconsistent = 0
    
    scenario_details = []
    all_scores = []
    
    for s in scenarios:
        trials = scenario_trials[s][:k]
        all_scores.extend(trials)
        successes = [1 if t >= success_threshold else 0 for t in trials]
        n_success = sum(successes)
        
        if n_success >= 1:
            pass_at_k += 1
        
        if n_success > k / 2:
            majority_at_k += 1
        
        if n_success == k:
            all_at_k += 1
            consistent_correct += 1
            consistency_type = "correct"
        elif n_success == 0:
            consistent_wrong += 1
            consistency_type = "wrong"
        else:
            inconsistent += 1
            consistency_type = "inconsistent"
        
        scenario_details.append({
            "scenario": s,
            "n_success": n_success,
            "n_trials": k,
            "majority_correct": n_success > k / 2,
            "consistency_type": consistency_type,
            "mean_score": np.mean(trials),
            "std_score": np.std(trials) if len(trials) > 1 else 0,
        })
    
    return {
        "n_scenarios": n_scenarios,
        "n_trials": k,
        "threshold": success_threshold,
        "pass_at_k": pass_at_k / n_scenarios,
        "majority_at_k": majority_at_k / n_scenarios,
        "all_at_k": all_at_k / n_scenarios,
        "consistent_correct": consistent_correct / n_scenarios,
        "consistent_wrong": consistent_wrong / n_scenarios,
        "inconsistent": inconsistent / n_scenarios,
        "n_pass": pass_at_k,
        "n_majority": majority_at_k,
        "n_all": all_at_k,
        "n_consistent_correct": consistent_correct,
        "n_consistent_wrong": consistent_wrong,
        "n_inconsistent": inconsistent,
        "overall_mean": np.mean(all_scores),
        "overall_std": np.std(all_scores),
        "scenario_details": scenario_details,
    }


# Metrics to extract
METRICS = [
    ("root_cause_entity_f1", "F1"),
    ("root_cause_entity_precision", "Precision"),
    ("root_cause_entity_recall", "Recall"),
]


def extract_all_data() -> dict[str, tuple[pd.DataFrame, pd.DataFrame]]:
    """
    Extract majority vote data for all agents, for multiple metrics.

    Returns:
    - dict mapping metric_name -> (summary_df, scenario_df)
    """
    agent_dirs = find_react_with_code_dirs(LEADERBOARD_DIR)
    print(f"Found {len(agent_dirs)} 'react with code' agent directories:")
    for d in agent_dirs:
        print(f"  - {d.name}")

    # Read all judge outputs once
    agent_data = {}
    valid_models = []
    skipped_models = []

    for agent_dir in tqdm(agent_dirs, desc="Reading agent data"):
        model_name = get_model_name(agent_dir.name)

        print(f"\nReading: {agent_dir.name}")
        scenario_data = read_judge_outputs_from_dir(agent_dir)

        if not scenario_data:
            print(f"  SKIPPING {model_name}: No judge outputs found")
            skipped_models.append((model_name, "No data"))
            continue

        # Filter scenarios with minimum runs
        scenario_data = filter_scenarios_with_min_runs(scenario_data, MIN_RUNS_PER_SCENARIO)
        n_qualifying = len(scenario_data)

        if n_qualifying < MIN_QUALIFYING_SCENARIOS:
            print(f"  SKIPPING {model_name}: Only {n_qualifying} scenarios with {MIN_RUNS_PER_SCENARIO}+ runs")
            skipped_models.append((model_name, f"{n_qualifying} qualifying"))
            continue

        print(f"  Processing: {model_name} ({n_qualifying} scenarios)")
        valid_models.append(model_name)
        agent_data[model_name] = scenario_data
    
    if skipped_models:
        print(f"\n⚠️  Skipped {len(skipped_models)} models:")
        for name, reason in skipped_models:
            print(f"    - {name}: {reason}")
    
    print(f"\n✓ Included {len(valid_models)} models: {valid_models}")
    
    # Extract for each metric
    results = {}

    for metric_key, metric_label in tqdm(METRICS, desc="Processing metrics"):
        print(f"\n--- Extracting for metric: {metric_label} ({metric_key}) ---")

        summary_records = []
        scenario_records = []

        for model_name, scenario_data in tqdm(agent_data.items(), desc=f"  {metric_label}", leave=False):
            # Extract scores for this metric
            scenario_trials = extract_trial_scores_from_judge_outputs(scenario_data, metric_key)
            
            # Compute majority vote metrics
            metrics = compute_majority_vote_metrics(scenario_trials)
            
            if metrics is None:
                continue
            
            # Add to summary
            summary_records.append({
                "model": model_name,
                "metric": metric_label,
                "n_scenarios": metrics["n_scenarios"],
                "n_trials": metrics["n_trials"],
                "pass_at_k": metrics["pass_at_k"],
                "majority_at_k": metrics["majority_at_k"],
                "all_at_k": metrics["all_at_k"],
                "consistent_correct": metrics["consistent_correct"],
                "consistent_wrong": metrics["consistent_wrong"],
                "inconsistent": metrics["inconsistent"],
                "overall_mean": metrics["overall_mean"],
                "overall_std": metrics["overall_std"],
            })
            
            # Add per-scenario data
            for detail in metrics["scenario_details"]:
                scenario_records.append({
                    "model": model_name,
                    "metric": metric_label,
                    "scenario": detail["scenario"],
                    "n_success": detail["n_success"],
                    "n_trials": detail["n_trials"],
                    "majority_correct": detail["majority_correct"],
                    "consistency_type": detail["consistency_type"],
                    "mean_score": detail["mean_score"],
                    "std_score": detail["std_score"],
                })
        
        summary_df = pd.DataFrame(summary_records)
        scenario_df = pd.DataFrame(scenario_records)
        results[metric_label] = (summary_df, scenario_df)
    
    return results


def save_data(results: dict[str, tuple[pd.DataFrame, pd.DataFrame]]):
    """Save extracted data to CSV files for each metric."""
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    
    # Also save combined data for backward compatibility
    all_summaries = []
    all_scenarios = []
    
    for metric_label, (summary_df, scenario_df) in results.items():
        metric_suffix = metric_label.lower()
        
        summary_path = OUTPUT_DIR / f"majority_vote_data_{metric_suffix}.csv"
        scenario_path = OUTPUT_DIR / f"majority_vote_scenarios_{metric_suffix}.csv"
        
        summary_df.to_csv(summary_path, index=False)
        scenario_df.to_csv(scenario_path, index=False)
        
        print(f"\nData saved for {metric_label}:")
        print(f"  - {summary_path}")
        print(f"  - {scenario_path}")
        
        all_summaries.append(summary_df)
        all_scenarios.append(scenario_df)
    
    # Save combined (default to F1 for backward compatibility)
    if "F1" in results:
        f1_summary, f1_scenario = results["F1"]
        # Save without metric column for backward compat
        f1_summary_compat = f1_summary.drop(columns=["metric"], errors="ignore")
        f1_scenario_compat = f1_scenario.drop(columns=["metric"], errors="ignore")
        f1_summary_compat.to_csv(OUTPUT_DIR / "majority_vote_data.csv", index=False)
        f1_scenario_compat.to_csv(OUTPUT_DIR / "majority_vote_scenarios.csv", index=False)
        print(f"\nBackward-compatible files (F1) saved to:")
        print(f"  - {OUTPUT_DIR / 'majority_vote_data.csv'}")
        print(f"  - {OUTPUT_DIR / 'majority_vote_scenarios.csv'}")


def print_summary(results: dict[str, tuple[pd.DataFrame, pd.DataFrame]]):
    """Print summary table for each metric."""
    for metric_label, (summary_df, _) in results.items():
        print("\n" + "="*80)
        print(f"Majority Vote Summary ({metric_label}, threshold={SUCCESS_THRESHOLD})")
        print("="*80)
        
        df = summary_df.sort_values("majority_at_k", ascending=False)
        
        print(f"\n{'Model':<20} {'Maj@k':>8} {'Pass@k':>8} {'All@k':>8} {'Cons✓':>8} {'Cons✗':>8} {'Incons':>8}")
        print("-" * 80)
        for _, row in df.iterrows():
            print(f"{row['model']:<20} "
                  f"{row['majority_at_k']*100:>7.1f}% "
                  f"{row['pass_at_k']*100:>7.1f}% "
                  f"{row['all_at_k']*100:>7.1f}% "
                  f"{row['consistent_correct']*100:>7.1f}% "
                  f"{row['consistent_wrong']*100:>7.1f}% "
                  f"{row['inconsistent']*100:>7.1f}%")

def plot_majority_vs_performance(df: pd.DataFrame):
    """
    Figure: Majority@k vs Performance scatter plot.
    """
    plt.rcParams.update({PLOT_PARAMETERS})
    
    fig, ax = plt.subplots(figsize=(SINGLE_COLUMN_WIDTH, DOUBLE_COLUMN_WIDTH))
    
    # Axis limits
    x_min, x_max = 0, 1.0
    y_min, y_max = 0, 100
    
    # Gradient shading toward top-right (ideal)
    for i in range(5):
        alpha = 0.02 + i * 0.02
        x_start = 0.1 + i * 0.15
        y_start = 10 + i * 15
        rect = plt.Rectangle((x_start, y_start), x_max - x_start, y_max - y_start,
                              color='#2ecc71', alpha=alpha, zorder=0)
        ax.add_patch(rect)
    
    # Arrow pointing to ideal
    ax.annotate('', xy=(0.85, 85), xytext=(0.55, 55),
                arrowprops=dict(arrowstyle='->', color='#27ae60', alpha=0.7, lw=1.5),
                zorder=2)
    ax.text(0.58, 58, 'better', fontsize=MIN_FONT_SIZE, style='italic',
            color='#27ae60', alpha=0.8, rotation=45, zorder=2)
    
    # Mark ideal corner
    ax.scatter([1.0], [100], marker='*', s=100, c='#27ae60', alpha=0.5, zorder=2)
    ax.text(0.92, 95, 'ideal', fontsize=MIN_FONT_SIZE - 1, color='#27ae60', 
            alpha=0.7, ha='right')
    
    # Scatter points with model-specific colors and markers
    for _, row in df.iterrows():
        style = get_model_style(row["model"])
        ax.scatter(row["overall_mean"], row["majority_at_k"] * 100,
                   c=style['color'], marker=style['marker'],
                   s=80, edgecolors='black', linewidth=0.5, zorder=10)
    
    # Labels with smart positioning
    for _, row in df.iterrows():
        model = row["model"]
        x_pos = row["overall_mean"]
        y_pos = row["majority_at_k"] * 100
        
        dx, dy = 0.03, 2
        ha, va = "left", "center"
        
        if x_pos > 0.7:
            dx = -0.03
            ha = "right"
        if y_pos > 80:
            dy = -3
            va = "top"
        
        ax.text(x_pos + dx, y_pos + dy, model, fontsize=MIN_FONT_SIZE - 1, 
                ha=ha, va=va, zorder=11)
    
    ax.set_xlabel("Performance (RC Entity F1)")
    ax.set_ylabel("Majority@k (%)")
    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    
    plt.tight_layout()
    plt.show()
    fig.savefig(OUTPUT_DIR / "fig_majority_vs_performance.pdf")
    fig.savefig(OUTPUT_DIR / "fig_majority_vs_performance.png")
    plt.close(fig)
    print("Saved: fig_majority_vs_performance.pdf/png")


def plot_pass_vs_majority(df: pd.DataFrame, metric: str = "F1", suffix: str = ""):
    """
    Figure: Scatter plot of Pass@k (x-axis) vs Majority@k (y-axis).
    
    Args:
        df: DataFrame with pass_at_k and majority_at_k columns
        metric: Name of metric for labeling (F1, Precision, Recall)
        suffix: Suffix for output filename (e.g., "_precision")
    """
    fig, ax = plt.subplots(figsize=(SINGLE_COLUMN_WIDTH, SINGLE_COLUMN_WIDTH))
    
    ax_min, ax_max = 0, 100
    
    # Diagonal line
    ax.plot([ax_min, ax_max], [ax_min, ax_max], color='#444444', linestyle='--', 
            linewidth=1.5, alpha=0.6, zorder=1)
    
    # Consistency region labels
    ax.text(8, 92, 'more\nconsistent', fontsize=MIN_FONT_SIZE + 1, color='#333333', 
            ha='left', va='top', style='italic')
    ax.text(92, 8, 'less\nconsistent', fontsize=MIN_FONT_SIZE + 1, color='#333333', 
            ha='right', va='bottom', style='italic')
    
    # Collect and plot points
    points = {}
    for _, row in df.iterrows():
        style = get_model_style(row["model"])
        x = row["pass_at_k"] * 100
        y = row["majority_at_k"] * 100
        ax.scatter(x, y, c=style['color'], marker=style['marker'],
                   s=50, edgecolors='black', linewidth=0.5, zorder=10)
        points[row["model"]] = {'x': x, 'y': y}
    
    line_color = '#444444'
    line_width = 1.2
    
    # Place labels with manual positioning
    for model, p in points.items():
        x, y = p['x'], p['y']
        
        if 'GPT-OSS-120B' in model:
            # Label to the right, slightly below
            ax.text(x + 3, y - 2, model, fontsize=MIN_FONT_SIZE, ha='left', va='center', zorder=11)
        
        elif 'Gemini 2.5 Pro' in model:
            # TEAL CIRCLE: label slightly below and to the right
            ax.text(x + 3, y + 2, model, fontsize=MIN_FONT_SIZE, ha='left', va='bottom', zorder=11)
        
        elif 'o4-mini' in model:
            # YELLOW SQUARE: shorter line goes right then to label
            label_x = x + 12
            label_y = y
            # Horizontal line right (shorter)
            ax.plot([x, label_x], [y, y], color=line_color, linewidth=line_width, alpha=0.8, zorder=5)
            ax.text(label_x + 1, label_y, model, fontsize=MIN_FONT_SIZE, ha='left', va='center', zorder=11)
        
        elif 'GPT-5.1' in model:
            # GREEN SQUARE: line from left edge, goes left then up
            label_x = 5
            label_y = 25
            start_x = x - 2  # Left edge of the square marker
            # Horizontal line left from left edge midpoint
            ax.plot([start_x, label_x], [y, y], color=line_color, linewidth=line_width, alpha=0.8, zorder=5)
            # Vertical line up to label height
            ax.plot([label_x, label_x], [y, label_y], color=line_color, linewidth=line_width, alpha=0.8, zorder=5)
            ax.text(label_x, label_y + 1, model, fontsize=MIN_FONT_SIZE, ha='left', va='bottom', zorder=11)
        
        elif 'Claude Opus' in model:
            # Label to the right
            ax.text(x + 5, y, model, fontsize=MIN_FONT_SIZE, ha='left', va='center', zorder=11)
        
        elif 'Gemini 3 Pro' in model:
            # Label BELOW the circle, offset left
            ax.text(x - 18, y - 6, model, fontsize=MIN_FONT_SIZE, ha='left', va='top', zorder=11)
        
        elif 'Gemini 3 Flash' in model:
            # Label at x=95 to avoid diagonal line
            ax.text(105, y + 4, model, fontsize=MIN_FONT_SIZE, ha='right', va='bottom', zorder=11)
        
        elif 'Kimi K2' in model:
            # Label to the right
            ax.text(x + 3, y, model, fontsize=MIN_FONT_SIZE, ha='left', va='center', zorder=11)
        
        else:
            # Default: label to the right
            ax.text(x + 3, y, model, fontsize=MIN_FONT_SIZE, ha='left', va='center', zorder=11)
    
    ax.set_xlabel(f"Pass@k (%) [{metric}]")
    ax.set_ylabel(f"Majority@k (%) [{metric}]")
    ax.set_xlim(ax_min, ax_max)
    ax.set_ylim(ax_min, ax_max)
    ax.set_aspect('equal')
    
    plt.title("Consistency: Pass@k vs. Majority@k")
    plt.tight_layout()
    plt.show()
    filename = f"fig_pass_vs_majority{suffix}"
    fig.savefig(OUTPUT_DIR / f"{filename}.png")
    plt.close(fig)
    print(f"Saved: {filename}.png")

def main():
    print("Extracting majority vote data for 'react with code' agents...")
    print(f"Reading from directories: {LEADERBOARD_DIR}")
    print(f"Output directory: {OUTPUT_DIR}")
    print(f"Success threshold: {SUCCESS_THRESHOLD}")
    print(f"Minimum runs per scenario: {MIN_RUNS_PER_SCENARIO}")
    print(f"Metrics: {[m[1] for m in METRICS]}")
    
    results = extract_all_data()
    
    if not results:
        print("No data extracted!")
        return
    
    save_data(results)
    print_summary(results)


if __name__ == "__main__":
    main()