richardyoung commited on
Commit
9a0283b
·
verified ·
1 Parent(s): 78e16fe

Upload analyze_comprehensive_final.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. analyze_comprehensive_final.py +646 -0
analyze_comprehensive_final.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Final Comprehensive Analysis Script
4
+ Analyzes the comprehensive test results: 256 models × 20 tests
5
+ Generates all figures and tables for the paper
6
+ """
7
+
8
+ import pandas as pd
9
+ import numpy as np
10
+ import matplotlib.pyplot as plt
11
+ import seaborn as sns
12
+ from pathlib import Path
13
+ from datetime import datetime
14
+ import json
15
+
16
+ # Set style for publication-quality figures
17
+ plt.style.use('seaborn-v0_8-whitegrid')
18
+ sns.set_palette("husl")
19
+
20
+ def load_results():
21
+ """Load the comprehensive test results."""
22
+ excel_file = 'comprehensive_20_tests_results_20251014_153008.xlsx'
23
+ json_file = 'comprehensive_20_tests_results_20251014_153008.json'
24
+
25
+ print("="*80)
26
+ print("LOADING COMPREHENSIVE TEST RESULTS")
27
+ print("="*80)
28
+ print(f"\nLoading from: {excel_file}")
29
+
30
+ # Load Excel file
31
+ xls = pd.ExcelFile(excel_file)
32
+
33
+ # Load all sheets
34
+ all_results = pd.read_excel(xls, 'All Results')
35
+ model_rankings = pd.read_excel(xls, 'Model Rankings', index_col=0)
36
+ test_difficulty = pd.read_excel(xls, 'Test Difficulty')
37
+ category_performance = pd.read_excel(xls, 'Category Performance', index_col=0)
38
+
39
+ print(f" Total results: {len(all_results)}")
40
+ print(f" Models tested: {all_results['model'].nunique()}")
41
+ print(f" Tests conducted: {all_results['test_id'].nunique()}")
42
+
43
+ # Load JSON for additional metadata
44
+ with open(json_file, 'r') as f:
45
+ json_data = json.load(f)
46
+
47
+ return all_results, model_rankings, test_difficulty, category_performance, json_data
48
+
49
+ def print_summary_statistics(all_results, json_data):
50
+ """Print comprehensive summary statistics."""
51
+ print("\n" + "="*80)
52
+ print("SUMMARY STATISTICS")
53
+ print("="*80)
54
+
55
+ metadata = json_data['metadata']
56
+ summary = json_data['summary']
57
+
58
+ print(f"\nDataset Overview:")
59
+ print(f" Total Models: {metadata['total_models']}")
60
+ print(f" Total Tests: {metadata['total_tests']}")
61
+ print(f" Total Evaluations: {metadata['total_results']}")
62
+ print(f" Timestamp: {metadata['timestamp']}")
63
+
64
+ print(f"\nOverall Performance:")
65
+ print(f" Overall Pass Rate: {summary['overall_pass_rate']:.1f}%")
66
+ print(f" Best Model: {summary['best_model']} ({summary['best_model_score']:.1f}%)")
67
+ print(f" Hardest Test: Test {summary['hardest_test']} ({summary['hardest_test_pass_rate']:.1f}% pass rate)")
68
+
69
+ # API success rate
70
+ success_rate = (all_results['status'] == 'success').mean() * 100
71
+ print(f" API Success Rate: {success_rate:.1f}%")
72
+
73
+ # Response time statistics
74
+ avg_response_time = all_results[all_results['response_time'] > 0]['response_time'].mean()
75
+ print(f" Average Response Time: {avg_response_time:.2f}s")
76
+
77
+ def print_top_models(model_rankings):
78
+ """Print top performing models."""
79
+ print("\n" + "="*80)
80
+ print("TOP 20 PERFORMING MODELS")
81
+ print("="*80)
82
+
83
+ print(f"\n{'Rank':<6} {'Pass Rate':<12} {'Model'}")
84
+ print("-" * 80)
85
+
86
+ for idx, (model, row) in enumerate(model_rankings.head(20).iterrows(), 1):
87
+ pass_rate = row['Pass Rate (%)']
88
+ print(f"{idx:<6} {pass_rate:>6.1f}% {model}")
89
+
90
+ def print_test_difficulty(test_difficulty):
91
+ """Print test difficulty analysis."""
92
+ print("\n" + "="*80)
93
+ print("TEST DIFFICULTY ANALYSIS (HARDEST TO EASIEST)")
94
+ print("="*80)
95
+
96
+ print(f"\n{'ID':<4} {'Pass Rate':<12} {'Category':<25} {'Test Name'}")
97
+ print("-" * 95)
98
+
99
+ # Sort by pass rate (ascending = hardest first)
100
+ sorted_tests = test_difficulty.sort_values('Pass Rate (%)')
101
+
102
+ for _, row in sorted_tests.iterrows():
103
+ test_id = int(row['Test ID'])
104
+ pass_rate = row['Pass Rate (%)']
105
+ category = row['category'][:23] if pd.notna(row['category']) else ''
106
+ name = row['name'][:45]
107
+ print(f"{test_id:<4} {pass_rate:>6.1f}% {category:<25} {name}")
108
+
109
+ def print_category_analysis(category_performance):
110
+ """Print category performance analysis."""
111
+ print("\n" + "="*80)
112
+ print("PERFORMANCE BY CATEGORY")
113
+ print("="*80)
114
+
115
+ # Sort by pass rate
116
+ sorted_cats = category_performance.sort_values('Pass Rate (%)')
117
+
118
+ print(f"\n{'Category':<30} {'Pass Rate'}")
119
+ print("-" * 45)
120
+
121
+ for category, row in sorted_cats.iterrows():
122
+ pass_rate = row['Pass Rate (%)']
123
+ print(f"{category:<30} {pass_rate:>6.1f}%")
124
+
125
+ def analyze_by_provider(all_results):
126
+ """Analyze performance by model provider."""
127
+ print("\n" + "="*80)
128
+ print("PROVIDER ANALYSIS")
129
+ print("="*80)
130
+
131
+ # Extract provider from model name
132
+ all_results['provider'] = all_results['model'].apply(
133
+ lambda x: x.split('/')[0] if '/' in x else 'other'
134
+ )
135
+
136
+ # Calculate provider statistics
137
+ provider_stats = all_results.groupby('provider').agg({
138
+ 'passed': 'mean',
139
+ 'model': 'nunique',
140
+ 'test_id': 'count'
141
+ }).round(3)
142
+
143
+ provider_stats.columns = ['pass_rate', 'num_models', 'total_tests']
144
+ provider_stats['pass_rate'] = provider_stats['pass_rate'] * 100
145
+ provider_stats = provider_stats.sort_values('pass_rate', ascending=False)
146
+
147
+ # Filter to providers with at least 3 models
148
+ provider_stats_filtered = provider_stats[provider_stats['num_models'] >= 3]
149
+
150
+ print(f"\n{'Provider':<20} {'Pass Rate':<12} {'Models':<10} {'Tests'}")
151
+ print("-" * 55)
152
+
153
+ for provider, row in provider_stats_filtered.head(15).iterrows():
154
+ print(f"{provider:<20} {row['pass_rate']:>6.1f}% {int(row['num_models']):<10} {int(row['total_tests'])}")
155
+
156
+ return provider_stats_filtered
157
+
158
+ def create_heatmap(all_results, output_file='fig1_heatmap.pdf'):
159
+ """Create heatmap of model performance on all tests."""
160
+ print("\n" + "="*80)
161
+ print("CREATING FIGURE 1: PERFORMANCE HEATMAP (Top 50 Models)")
162
+ print("="*80)
163
+
164
+ # Create pivot table
165
+ pivot = all_results.pivot_table(
166
+ index='model',
167
+ columns='test_id',
168
+ values='passed',
169
+ aggfunc='first'
170
+ )
171
+
172
+ # Select top 50 models by overall performance
173
+ model_scores = pivot.mean(axis=1).sort_values(ascending=False)
174
+ top_50_models = model_scores.head(50).index
175
+ pivot_top50 = pivot.loc[top_50_models]
176
+
177
+ # Create figure
178
+ fig, ax = plt.subplots(figsize=(14, 12))
179
+
180
+ # Create heatmap
181
+ sns.heatmap(
182
+ pivot_top50,
183
+ cmap=['#d73027', '#91cf60'], # Red for fail, green for pass
184
+ cbar_kws={'label': 'Pass (1) / Fail (0)', 'ticks': [0, 1]},
185
+ xticklabels=True,
186
+ yticklabels=True,
187
+ vmin=0,
188
+ vmax=1,
189
+ linewidths=0.3,
190
+ linecolor='gray',
191
+ ax=ax
192
+ )
193
+
194
+ plt.title('Model Performance on 20 Diagnostic Tests (Top 50 Models)',
195
+ fontsize=16, fontweight='bold', pad=20)
196
+ plt.xlabel('Test ID', fontsize=12)
197
+ plt.ylabel('Model', fontsize=12)
198
+ plt.yticks(fontsize=7)
199
+ plt.xticks(fontsize=10)
200
+ plt.tight_layout()
201
+
202
+ plt.savefig(output_file, dpi=300, bbox_inches='tight')
203
+ print(f"✅ Saved: {output_file}")
204
+ plt.close()
205
+
206
+ def create_provider_chart(provider_stats, output_file='fig2_provider.pdf'):
207
+ """Create bar chart of provider performance."""
208
+ print("\n" + "="*80)
209
+ print("CREATING FIGURE 2: PROVIDER COMPARISON")
210
+ print("="*80)
211
+
212
+ # Select top 12 providers
213
+ top_providers = provider_stats.head(12)
214
+
215
+ # Create figure
216
+ fig, ax = plt.subplots(figsize=(12, 7))
217
+
218
+ # Create bar plot
219
+ x_pos = np.arange(len(top_providers))
220
+ colors = sns.color_palette('husl', len(top_providers))
221
+ bars = ax.bar(x_pos, top_providers['pass_rate'], color=colors, edgecolor='black', linewidth=0.5)
222
+
223
+ # Customize plot
224
+ ax.set_xlabel('Model Provider', fontsize=13, fontweight='bold')
225
+ ax.set_ylabel('Average Pass Rate (%)', fontsize=13, fontweight='bold')
226
+ ax.set_title('Performance by Model Provider (≥3 models)',
227
+ fontsize=16, fontweight='bold', pad=20)
228
+ ax.set_xticks(x_pos)
229
+ ax.set_xticklabels(top_providers.index, rotation=45, ha='right', fontsize=11)
230
+ ax.set_ylim([0, max(top_providers['pass_rate']) * 1.15])
231
+ ax.grid(axis='y', alpha=0.3)
232
+
233
+ # Add value labels on bars
234
+ for bar in bars:
235
+ height = bar.get_height()
236
+ ax.text(bar.get_x() + bar.get_width()/2., height + 1,
237
+ f'{height:.1f}%', ha='center', va='bottom', fontsize=10, fontweight='bold')
238
+
239
+ # Add average line
240
+ avg_rate = top_providers['pass_rate'].mean()
241
+ ax.axhline(y=avg_rate, color='red', linestyle='--', alpha=0.7, linewidth=2,
242
+ label=f'Average: {avg_rate:.1f}%')
243
+ ax.legend(fontsize=11)
244
+
245
+ plt.tight_layout()
246
+ plt.savefig(output_file, dpi=300, bbox_inches='tight')
247
+ print(f"✅ Saved: {output_file}")
248
+ plt.close()
249
+
250
+ def create_difficulty_chart(test_difficulty, output_file='fig3_difficulty.pdf'):
251
+ """Create horizontal bar chart of test difficulty."""
252
+ print("\n" + "="*80)
253
+ print("CREATING FIGURE 3: TEST DIFFICULTY RANKING")
254
+ print("="*80)
255
+
256
+ # Sort by difficulty (ascending pass rate = harder)
257
+ sorted_tests = test_difficulty.sort_values('Pass Rate (%)')
258
+
259
+ # Create shortened labels
260
+ labels = []
261
+ for _, row in sorted_tests.iterrows():
262
+ test_id = int(row['Test ID'])
263
+ name = row['name']
264
+ # Shorten long names
265
+ if len(name) > 35:
266
+ name = name[:32] + '...'
267
+ labels.append(f"T{test_id}: {name}")
268
+
269
+ pass_rates = sorted_tests['Pass Rate (%)'].values
270
+
271
+ # Create figure
272
+ fig, ax = plt.subplots(figsize=(12, 10))
273
+
274
+ # Color based on difficulty
275
+ colors = []
276
+ for rate in pass_rates:
277
+ if rate < 10:
278
+ colors.append('#8B0000') # Dark red - extremely hard
279
+ elif rate < 20:
280
+ colors.append('#d73027') # Red - very hard
281
+ elif rate < 40:
282
+ colors.append('#fdae61') # Orange - hard
283
+ elif rate < 60:
284
+ colors.append('#fee08b') # Yellow - medium
285
+ elif rate < 80:
286
+ colors.append('#a6d96a') # Light green - easy
287
+ else:
288
+ colors.append('#1a9850') # Dark green - very easy
289
+
290
+ # Create horizontal bar plot
291
+ y_pos = np.arange(len(labels))
292
+ bars = ax.barh(y_pos, pass_rates, color=colors, edgecolor='black', linewidth=0.5)
293
+
294
+ # Customize plot
295
+ ax.set_xlabel('Pass Rate (%)', fontsize=13, fontweight='bold')
296
+ ax.set_ylabel('Test', fontsize=13, fontweight='bold')
297
+ ax.set_title('Test Difficulty Ranking (Hardest to Easiest)',
298
+ fontsize=16, fontweight='bold', pad=20)
299
+ ax.set_yticks(y_pos)
300
+ ax.set_yticklabels(labels, fontsize=9)
301
+ ax.set_xlim([0, 105])
302
+ ax.grid(axis='x', alpha=0.3)
303
+
304
+ # Add value labels
305
+ for bar, rate in zip(bars, pass_rates):
306
+ width = bar.get_width()
307
+ ax.text(width + 1.5, bar.get_y() + bar.get_height()/2.,
308
+ f'{rate:.1f}%', ha='left', va='center', fontsize=9, fontweight='bold')
309
+
310
+ # Add vertical reference lines
311
+ ax.axvline(x=50, color='black', linestyle='--', alpha=0.3, linewidth=1)
312
+ ax.axvline(x=25, color='red', linestyle=':', alpha=0.3, linewidth=1)
313
+ ax.axvline(x=75, color='green', linestyle=':', alpha=0.3, linewidth=1)
314
+
315
+ # Add legend for difficulty colors
316
+ from matplotlib.patches import Patch
317
+ legend_elements = [
318
+ Patch(facecolor='#8B0000', label='Extremely Hard (<10%)'),
319
+ Patch(facecolor='#d73027', label='Very Hard (10-20%)'),
320
+ Patch(facecolor='#fdae61', label='Hard (20-40%)'),
321
+ Patch(facecolor='#fee08b', label='Medium (40-60%)'),
322
+ Patch(facecolor='#a6d96a', label='Easy (60-80%)'),
323
+ Patch(facecolor='#1a9850', label='Very Easy (>80%)')
324
+ ]
325
+ ax.legend(handles=legend_elements, loc='lower right', fontsize=9)
326
+
327
+ plt.tight_layout()
328
+ plt.savefig(output_file, dpi=300, bbox_inches='tight')
329
+ print(f"✅ Saved: {output_file}")
330
+ plt.close()
331
+
332
+ def create_category_chart(category_performance, output_file='fig4_category.pdf'):
333
+ """Create bar chart of category performance."""
334
+ print("\n" + "="*80)
335
+ print("CREATING FIGURE 4: CATEGORY PERFORMANCE")
336
+ print("="*80)
337
+
338
+ # Sort by pass rate
339
+ sorted_cats = category_performance.sort_values('Pass Rate (%)')
340
+
341
+ # Create figure
342
+ fig, ax = plt.subplots(figsize=(10, 6))
343
+
344
+ # Create bar plot
345
+ x_pos = np.arange(len(sorted_cats))
346
+ colors = plt.cm.RdYlGn(sorted_cats['Pass Rate (%)'] / 100)
347
+ bars = ax.bar(x_pos, sorted_cats['Pass Rate (%)'], color=colors, edgecolor='black', linewidth=0.8)
348
+
349
+ # Customize plot
350
+ ax.set_xlabel('Category', fontsize=13, fontweight='bold')
351
+ ax.set_ylabel('Pass Rate (%)', fontsize=13, fontweight='bold')
352
+ ax.set_title('Performance by Test Category',
353
+ fontsize=16, fontweight='bold', pad=20)
354
+ ax.set_xticks(x_pos)
355
+ ax.set_xticklabels(sorted_cats.index, rotation=45, ha='right', fontsize=11)
356
+ ax.set_ylim([0, 100])
357
+ ax.grid(axis='y', alpha=0.3)
358
+
359
+ # Add value labels
360
+ for bar in bars:
361
+ height = bar.get_height()
362
+ ax.text(bar.get_x() + bar.get_width()/2., height + 2,
363
+ f'{height:.1f}%', ha='center', va='bottom', fontsize=11, fontweight='bold')
364
+
365
+ plt.tight_layout()
366
+ plt.savefig(output_file, dpi=300, bbox_inches='tight')
367
+ print(f"✅ Saved: {output_file}")
368
+ plt.close()
369
+
370
+ def generate_latex_tables(model_rankings, test_difficulty, category_performance, provider_stats):
371
+ """Generate LaTeX tables for the paper."""
372
+ print("\n" + "="*80)
373
+ print("GENERATING LATEX TABLES")
374
+ print("="*80)
375
+
376
+ output_file = 'paper_tables.tex'
377
+
378
+ with open(output_file, 'w') as f:
379
+ # Table 1: Top Models
380
+ f.write("% Table 1: Top 15 Performing Models\n")
381
+ f.write("\\begin{table}[htbp]\n")
382
+ f.write("\\centering\n")
383
+ f.write("\\caption{Top 15 Performing Models on 20 Diagnostic Tests}\n")
384
+ f.write("\\label{tab:top_models}\n")
385
+ f.write("\\begin{tabular}{rlr}\n")
386
+ f.write("\\toprule\n")
387
+ f.write("Rank & Model & Pass Rate \\\\\n")
388
+ f.write("\\midrule\n")
389
+
390
+ for idx, (model, row) in enumerate(model_rankings.head(15).iterrows(), 1):
391
+ model_escaped = model.replace('_', '\\_').replace('&', '\\&')
392
+ pass_rate = row['Pass Rate (%)']
393
+ f.write(f"{idx} & \\texttt{{{model_escaped}}} & {pass_rate:.1f}\\% \\\\\n")
394
+
395
+ f.write("\\bottomrule\n")
396
+ f.write("\\end{tabular}\n")
397
+ f.write("\\end{table}\n\n")
398
+
399
+ # Table 2: Test Difficulty
400
+ f.write("% Table 2: Test Difficulty (Hardest 10)\n")
401
+ f.write("\\begin{table}[htbp]\n")
402
+ f.write("\\centering\n")
403
+ f.write("\\caption{Test Difficulty Analysis (10 Hardest Tests)}\n")
404
+ f.write("\\label{tab:test_difficulty}\n")
405
+ f.write("\\begin{tabular}{clrl}\n")
406
+ f.write("\\toprule\n")
407
+ f.write("ID & Test Name & Pass Rate & Category \\\\\n")
408
+ f.write("\\midrule\n")
409
+
410
+ sorted_tests = test_difficulty.sort_values('Pass Rate (%)')
411
+ for _, row in sorted_tests.head(10).iterrows():
412
+ test_id = int(row['Test ID'])
413
+ name = row['name'][:40]
414
+ name_escaped = name.replace('_', '\\_').replace('&', '\\&')
415
+ pass_rate = row['Pass Rate (%)']
416
+ category = row['category'][:20] if pd.notna(row['category']) else ''
417
+ category_escaped = category.replace('_', '\\_').replace('&', '\\&')
418
+ f.write(f"{test_id} & {name_escaped} & {pass_rate:.1f}\\% & {category_escaped} \\\\\n")
419
+
420
+ f.write("\\bottomrule\n")
421
+ f.write("\\end{tabular}\n")
422
+ f.write("\\end{table}\n\n")
423
+
424
+ # Table 3: Category Performance
425
+ f.write("% Table 3: Category Performance\n")
426
+ f.write("\\begin{table}[htbp]\n")
427
+ f.write("\\centering\n")
428
+ f.write("\\caption{Performance by Test Category}\n")
429
+ f.write("\\label{tab:category_performance}\n")
430
+ f.write("\\begin{tabular}{lr}\n")
431
+ f.write("\\toprule\n")
432
+ f.write("Category & Pass Rate \\\\\n")
433
+ f.write("\\midrule\n")
434
+
435
+ sorted_cats = category_performance.sort_values('Pass Rate (%)')
436
+ for category, row in sorted_cats.iterrows():
437
+ category_escaped = category.replace('_', '\\_').replace('&', '\\&')
438
+ pass_rate = row['Pass Rate (%)']
439
+ f.write(f"{category_escaped} & {pass_rate:.1f}\\% \\\\\n")
440
+
441
+ f.write("\\bottomrule\n")
442
+ f.write("\\end{tabular}\n")
443
+ f.write("\\end{table}\n\n")
444
+
445
+ # Table 4: Provider Comparison
446
+ f.write("% Table 4: Provider Comparison (Top 10)\n")
447
+ f.write("\\begin{table}[htbp]\n")
448
+ f.write("\\centering\n")
449
+ f.write("\\caption{Performance by Model Provider}\n")
450
+ f.write("\\label{tab:provider_comparison}\n")
451
+ f.write("\\begin{tabular}{lrrr}\n")
452
+ f.write("\\toprule\n")
453
+ f.write("Provider & Models & Pass Rate & Tests \\\\\n")
454
+ f.write("\\midrule\n")
455
+
456
+ for provider, row in provider_stats.head(10).iterrows():
457
+ provider_escaped = provider.replace('_', '\\_').replace('&', '\\&')
458
+ num_models = int(row['num_models'])
459
+ pass_rate = row['pass_rate']
460
+ total_tests = int(row['total_tests'])
461
+ f.write(f"{provider_escaped} & {num_models} & {pass_rate:.1f}\\% & {total_tests} \\\\\n")
462
+
463
+ f.write("\\bottomrule\n")
464
+ f.write("\\end{tabular}\n")
465
+ f.write("\\end{table}\n")
466
+
467
+ print(f"✅ Saved: {output_file}")
468
+
469
+ def generate_summary_report(all_results, model_rankings, test_difficulty, category_performance, provider_stats, json_data):
470
+ """Generate comprehensive summary report."""
471
+ print("\n" + "="*80)
472
+ print("GENERATING FINAL SUMMARY REPORT")
473
+ print("="*80)
474
+
475
+ output_file = 'FINAL_RESULTS_SUMMARY.md'
476
+
477
+ with open(output_file, 'w') as f:
478
+ f.write("# Comprehensive LLM Instruction Following Evaluation\n")
479
+ f.write(f"## Final Results Summary\n\n")
480
+ f.write(f"**Analysis Date:** {datetime.now().strftime('%Y-%m-%d %H:%M')}\n\n")
481
+ f.write(f"**Data Source:** {json_data['metadata']['timestamp']}\n\n")
482
+
483
+ f.write("---\n\n")
484
+ f.write("## Executive Summary\n\n")
485
+
486
+ metadata = json_data['metadata']
487
+ summary = json_data['summary']
488
+
489
+ f.write(f"This evaluation tested **{metadata['total_models']} large language models** ")
490
+ f.write(f"on **{metadata['total_tests']} diagnostic prompts**, ")
491
+ f.write(f"resulting in **{metadata['total_results']} individual test evaluations**.\n\n")
492
+
493
+ f.write(f"### Key Findings\n\n")
494
+ f.write(f"- **Overall Pass Rate:** {summary['overall_pass_rate']:.1f}%\n")
495
+ f.write(f"- **Best Performing Model:** {summary['best_model']} ({summary['best_model_score']:.1f}%)\n")
496
+ f.write(f"- **Hardest Test:** Test {summary['hardest_test']} ({summary['hardest_test_pass_rate']:.1f}% pass rate)\n")
497
+
498
+ # API success rate
499
+ success_rate = (all_results['status'] == 'success').mean() * 100
500
+ f.write(f"- **API Success Rate:** {success_rate:.1f}%\n\n")
501
+
502
+ f.write("---\n\n")
503
+ f.write("## Top 20 Performing Models\n\n")
504
+ f.write("| Rank | Model | Pass Rate |\n")
505
+ f.write("|------|-------|----------:|\n")
506
+
507
+ for idx, (model, row) in enumerate(model_rankings.head(20).iterrows(), 1):
508
+ pass_rate = row['Pass Rate (%)']
509
+ f.write(f"| {idx} | {model} | {pass_rate:.1f}% |\n")
510
+
511
+ f.write("\n---\n\n")
512
+ f.write("## Test Difficulty Analysis\n\n")
513
+ f.write("### Hardest Tests (Lowest Pass Rates)\n\n")
514
+ f.write("| ID | Test Name | Category | Pass Rate |\n")
515
+ f.write("|----|-----------|----------|----------:|\n")
516
+
517
+ sorted_tests = test_difficulty.sort_values('Pass Rate (%)')
518
+ for _, row in sorted_tests.head(10).iterrows():
519
+ test_id = int(row['Test ID'])
520
+ name = row['name']
521
+ category = row['category'] if pd.notna(row['category']) else 'N/A'
522
+ pass_rate = row['Pass Rate (%)']
523
+ f.write(f"| {test_id} | {name} | {category} | {pass_rate:.1f}% |\n")
524
+
525
+ f.write("\n### Easiest Tests (Highest Pass Rates)\n\n")
526
+ f.write("| ID | Test Name | Category | Pass Rate |\n")
527
+ f.write("|----|-----------|----------|----------:|\n")
528
+
529
+ for _, row in sorted_tests.tail(10).iterrows():
530
+ test_id = int(row['Test ID'])
531
+ name = row['name']
532
+ category = row['category'] if pd.notna(row['category']) else 'N/A'
533
+ pass_rate = row['Pass Rate (%)']
534
+ f.write(f"| {test_id} | {name} | {category} | {pass_rate:.1f}% |\n")
535
+
536
+ f.write("\n---\n\n")
537
+ f.write("## Performance by Category\n\n")
538
+ f.write("| Category | Pass Rate |\n")
539
+ f.write("|----------|----------:|\n")
540
+
541
+ sorted_cats = category_performance.sort_values('Pass Rate (%)')
542
+ for category, row in sorted_cats.iterrows():
543
+ pass_rate = row['Pass Rate (%)']
544
+ f.write(f"| {category} | {pass_rate:.1f}% |\n")
545
+
546
+ f.write("\n**Key Insight:** String manipulation tests are by far the hardest category, ")
547
+ f.write("while constraint compliance tests are the easiest.\n\n")
548
+
549
+ f.write("---\n\n")
550
+ f.write("## Performance by Provider\n\n")
551
+ f.write("Top providers (with ≥3 models):\n\n")
552
+ f.write("| Provider | Models | Pass Rate | Total Tests |\n")
553
+ f.write("|----------|--------|-----------|------------:|\n")
554
+
555
+ for provider, row in provider_stats.head(15).iterrows():
556
+ num_models = int(row['num_models'])
557
+ pass_rate = row['pass_rate']
558
+ total_tests = int(row['total_tests'])
559
+ f.write(f"| {provider} | {num_models} | {pass_rate:.1f}% | {total_tests} |\n")
560
+
561
+ f.write("\n---\n\n")
562
+ f.write("## Statistical Insights\n\n")
563
+
564
+ # Calculate additional statistics
565
+ model_pass_rates = all_results.groupby('model')['passed'].mean() * 100
566
+ test_pass_rates = all_results.groupby('test_id')['passed'].mean() * 100
567
+
568
+ f.write(f"### Model Performance Distribution\n\n")
569
+ f.write(f"- **Mean Pass Rate:** {model_pass_rates.mean():.1f}%\n")
570
+ f.write(f"- **Median Pass Rate:** {model_pass_rates.median():.1f}%\n")
571
+ f.write(f"- **Standard Deviation:** {model_pass_rates.std():.1f}%\n")
572
+ f.write(f"- **Models with 100% Pass Rate:** {(model_pass_rates == 100).sum()}\n")
573
+ f.write(f"- **Models with 0% Pass Rate:** {(model_pass_rates == 0).sum()}\n\n")
574
+
575
+ f.write(f"### Test Difficulty Distribution\n\n")
576
+ f.write(f"- **Mean Test Pass Rate:** {test_pass_rates.mean():.1f}%\n")
577
+ f.write(f"- **Median Test Pass Rate:** {test_pass_rates.median():.1f}%\n")
578
+ f.write(f"- **Standard Deviation:** {test_pass_rates.std():.1f}%\n")
579
+ f.write(f"- **Tests with >80% Pass Rate:** {(test_pass_rates > 80).sum()}\n")
580
+ f.write(f"- **Tests with <20% Pass Rate:** {(test_pass_rates < 20).sum()}\n\n")
581
+
582
+ f.write("---\n\n")
583
+ f.write("## Files Generated\n\n")
584
+ f.write("- `fig1_heatmap.pdf` - Performance heatmap (top 50 models)\n")
585
+ f.write("- `fig2_provider.pdf` - Provider comparison chart\n")
586
+ f.write("- `fig3_difficulty.pdf` - Test difficulty ranking\n")
587
+ f.write("- `fig4_category.pdf` - Category performance chart\n")
588
+ f.write("- `paper_tables.tex` - LaTeX tables for paper\n")
589
+ f.write("- `FINAL_RESULTS_SUMMARY.md` - This summary document\n\n")
590
+
591
+ f.write("---\n\n")
592
+ f.write("## Conclusions\n\n")
593
+ f.write("1. **Model Performance Varies Widely:** Pass rates range from 0% to 100%, ")
594
+ f.write("indicating significant differences in instruction-following capabilities.\n\n")
595
+
596
+ f.write("2. **String Manipulation is Hardest:** Tests requiring precise string manipulation ")
597
+ f.write("have the lowest pass rates, suggesting this is a key challenge for current LLMs.\n\n")
598
+
599
+ f.write("3. **Provider Differences:** Significant variation exists between model providers, ")
600
+ f.write("with top providers achieving much higher pass rates.\n\n")
601
+
602
+ f.write("4. **Few Perfect Models:** Only a small number of models achieve 100% pass rate, ")
603
+ f.write("indicating that even top models struggle with some tests.\n\n")
604
+
605
+ f.write("5. **API Reliability:** High API success rate indicates robust testing methodology.\n\n")
606
+
607
+ print(f"✅ Saved: {output_file}")
608
+
609
+ def main():
610
+ """Main analysis function."""
611
+ print("\n" + "="*80)
612
+ print("COMPREHENSIVE FINAL ANALYSIS")
613
+ print(f"Analysis Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
614
+ print("="*80 + "\n")
615
+
616
+ # Load results
617
+ all_results, model_rankings, test_difficulty, category_performance, json_data = load_results()
618
+
619
+ # Print summary statistics
620
+ print_summary_statistics(all_results, json_data)
621
+ print_top_models(model_rankings)
622
+ print_test_difficulty(test_difficulty)
623
+ print_category_analysis(category_performance)
624
+
625
+ # Analyze by provider
626
+ provider_stats = analyze_by_provider(all_results)
627
+
628
+ # Create all visualizations
629
+ create_heatmap(all_results)
630
+ create_provider_chart(provider_stats)
631
+ create_difficulty_chart(test_difficulty)
632
+ create_category_chart(category_performance)
633
+
634
+ # Generate LaTeX tables
635
+ generate_latex_tables(model_rankings, test_difficulty, category_performance, provider_stats)
636
+
637
+ # Generate summary report
638
+ generate_summary_report(all_results, model_rankings, test_difficulty, category_performance, provider_stats, json_data)
639
+
640
+ print("\n" + "="*80)
641
+ print("✅ COMPREHENSIVE ANALYSIS COMPLETE")
642
+ print("="*80)
643
+ print("\nAll figures, tables, and reports have been generated successfully!")
644
+
645
+ if __name__ == "__main__":
646
+ main()