|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Win Change Rate Analysis: Measure how often the winner changes between consecutive rounds. |
| 4 | +
|
| 5 | +Shows that multi-player tournaments are more volatile with more frequent lead changes |
| 6 | +compared to 2-player tournaments. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import matplotlib.pyplot as plt |
| 13 | +import numpy as np |
| 14 | + |
| 15 | +from codeclash.analysis.viz.utils import ASSETS_DIR, FONT_BOLD |
| 16 | +from codeclash.constants import LOCAL_LOG_DIR |
| 17 | + |
| 18 | + |
| 19 | +def calculate_lead_changes(metadata_path: Path) -> dict: |
| 20 | + """Calculate how often the winner changes between consecutive rounds.""" |
| 21 | + with open(metadata_path) as f: |
| 22 | + metadata = json.load(f) |
| 23 | + |
| 24 | + # Extract winners in order |
| 25 | + winners = [] |
| 26 | + for round_id in sorted([int(k) for k in metadata.get("round_stats", {}).keys() if k != "0"]): |
| 27 | + stats = metadata["round_stats"][str(round_id)] |
| 28 | + winner = stats.get("winner") |
| 29 | + if winner: |
| 30 | + winners.append(winner) |
| 31 | + |
| 32 | + if len(winners) < 2: |
| 33 | + return None |
| 34 | + |
| 35 | + # Count changes |
| 36 | + changes = sum(1 for i in range(1, len(winners)) if winners[i] != winners[i - 1]) |
| 37 | + total_transitions = len(winners) - 1 |
| 38 | + change_rate = (changes / total_transitions * 100) if total_transitions > 0 else 0 |
| 39 | + |
| 40 | + return {"total_rounds": len(winners), "lead_changes": changes, "change_rate": change_rate} |
| 41 | + |
| 42 | + |
| 43 | +def analyze_win_change_rate(log_dir: Path, game_pattern: str = "CoreWar.r15.s1000"): |
| 44 | + """Compare lead change rates between 2-player and multi-player tournaments.""" |
| 45 | + |
| 46 | + # Collect 2-player data |
| 47 | + print("Analyzing 2-player tournaments...") |
| 48 | + lead_changes_2p = [] |
| 49 | + for metadata_path in log_dir.rglob(f"*{game_pattern}.p2.*/metadata.json"): |
| 50 | + result = calculate_lead_changes(metadata_path) |
| 51 | + if result: |
| 52 | + lead_changes_2p.append(result) |
| 53 | + |
| 54 | + # Collect 6-player data |
| 55 | + print("Analyzing 6-player tournaments...") |
| 56 | + lead_changes_6p = [] |
| 57 | + for metadata_path in log_dir.rglob(f"*{game_pattern}.p6.*/metadata.json"): |
| 58 | + result = calculate_lead_changes(metadata_path) |
| 59 | + if result: |
| 60 | + lead_changes_6p.append(result) |
| 61 | + |
| 62 | + # Extract change rates |
| 63 | + change_rates_2p = [x["change_rate"] for x in lead_changes_2p] |
| 64 | + change_rates_6p = [x["change_rate"] for x in lead_changes_6p] |
| 65 | + |
| 66 | + lead_count_2p = [x["lead_changes"] for x in lead_changes_2p] |
| 67 | + lead_count_6p = [x["lead_changes"] for x in lead_changes_6p] |
| 68 | + |
| 69 | + # Print statistics |
| 70 | + print("\n" + "=" * 70) |
| 71 | + print("LEAD CHANGES COMPARISON") |
| 72 | + print("=" * 70) |
| 73 | + |
| 74 | + print("\n2-Player Tournaments:") |
| 75 | + print(f" Tournaments analyzed: {len(lead_changes_2p)}") |
| 76 | + print(f" Average lead changes: {np.mean(lead_count_2p):.1f} per tournament") |
| 77 | + print(f" Average change rate: {np.mean(change_rates_2p):.1f}%") |
| 78 | + print(f" Median: {np.median(lead_count_2p):.0f} changes") |
| 79 | + print(f" Range: {np.min(lead_count_2p):.0f} - {np.max(lead_count_2p):.0f}") |
| 80 | + |
| 81 | + print("\n6-Player Tournaments:") |
| 82 | + print(f" Tournaments analyzed: {len(lead_changes_6p)}") |
| 83 | + print(f" Average lead changes: {np.mean(lead_count_6p):.1f} per tournament") |
| 84 | + print(f" Average change rate: {np.mean(change_rates_6p):.1f}%") |
| 85 | + print(f" Median: {np.median(lead_count_6p):.0f} changes") |
| 86 | + print(f" Range: {np.min(lead_count_6p):.0f} - {np.max(lead_count_6p):.0f}") |
| 87 | + |
| 88 | + print("\n" + "=" * 70) |
| 89 | + print("KEY INSIGHT") |
| 90 | + print("=" * 70) |
| 91 | + ratio = np.mean(change_rates_6p) / np.mean(change_rates_2p) |
| 92 | + print(f""" |
| 93 | +Lead change rate: |
| 94 | + • 6-Player: {np.mean(change_rates_6p):.1f}% of round transitions |
| 95 | + • 2-Player: {np.mean(change_rates_2p):.1f}% of round transitions |
| 96 | +
|
| 97 | +💡 Insight: 6-player tournaments are {ratio:.2f}x MORE VOLATILE! |
| 98 | + The lead changes {ratio:.2f}x as often in 6-player vs 2-player tournaments. |
| 99 | +
|
| 100 | +👉 Bottom line: Multi-player tournaments are much more dynamic and competitive, |
| 101 | + with no single player maintaining dominance throughout the tournament. |
| 102 | +""") |
| 103 | + |
| 104 | + # Create visualization |
| 105 | + fig, axes = plt.subplots(1, 2, figsize=(12, 5)) |
| 106 | + |
| 107 | + # Plot 1: Distribution of lead changes |
| 108 | + ax1 = axes[0] |
| 109 | + ax1.hist(lead_count_6p, bins=15, alpha=0.7, label="6-Player", color="steelblue", edgecolor="black") |
| 110 | + ax1.hist(lead_count_2p, bins=15, alpha=0.7, label="2-Player", color="coral", edgecolor="black") |
| 111 | + ax1.axvline( |
| 112 | + np.mean(lead_count_6p), |
| 113 | + color="steelblue", |
| 114 | + linestyle="--", |
| 115 | + linewidth=2, |
| 116 | + label=f"6P Mean: {np.mean(lead_count_6p):.1f}", |
| 117 | + ) |
| 118 | + ax1.axvline( |
| 119 | + np.mean(lead_count_2p), |
| 120 | + color="coral", |
| 121 | + linestyle="--", |
| 122 | + linewidth=2, |
| 123 | + label=f"2P Mean: {np.mean(lead_count_2p):.1f}", |
| 124 | + ) |
| 125 | + ax1.set_xlabel("Number of Lead Changes per Tournament", fontsize=18, fontproperties=FONT_BOLD) |
| 126 | + ax1.set_ylabel("Frequency", fontsize=18, fontproperties=FONT_BOLD) |
| 127 | + ax1.tick_params(axis="both", labelsize=14) |
| 128 | + ax1.legend(prop=FONT_BOLD, fontsize=12) |
| 129 | + ax1.grid(alpha=0.3) |
| 130 | + |
| 131 | + # Plot 2: Change rates comparison |
| 132 | + ax2 = axes[1] |
| 133 | + bp = ax2.boxplot( |
| 134 | + [change_rates_6p, change_rates_2p], tick_labels=["6-Player", "2-Player"], patch_artist=True, widths=0.6 |
| 135 | + ) |
| 136 | + bp["boxes"][0].set_facecolor("steelblue") |
| 137 | + bp["boxes"][1].set_facecolor("coral") |
| 138 | + ax2.set_ylabel("Lead Change Rate (%)", fontsize=18, fontproperties=FONT_BOLD) |
| 139 | + ax2.tick_params(axis="both", labelsize=14) |
| 140 | + ax2.grid(axis="y", alpha=0.3) |
| 141 | + |
| 142 | + # Add mean markers |
| 143 | + for i, data in enumerate([change_rates_6p, change_rates_2p], 1): |
| 144 | + ax2.plot(i, np.mean(data), "D", color="darkred", markersize=8, label="Mean" if i == 1 else "") |
| 145 | + ax2.legend(prop=FONT_BOLD, fontsize=12) |
| 146 | + |
| 147 | + # Set tick labels with custom font |
| 148 | + for label in ax2.get_xticklabels(): |
| 149 | + label.set_fontproperties(FONT_BOLD) |
| 150 | + |
| 151 | + plt.tight_layout() |
| 152 | + output_file = ASSETS_DIR / "win_change_rate_comparison.png" |
| 153 | + plt.savefig(output_file, dpi=300, bbox_inches="tight") |
| 154 | + print(f"\nVisualization saved to: {output_file}") |
| 155 | + plt.close() |
| 156 | + |
| 157 | + return {"2p": lead_changes_2p, "6p": lead_changes_6p} |
| 158 | + |
| 159 | + |
| 160 | +def main(): |
| 161 | + analyze_win_change_rate(LOCAL_LOG_DIR) |
| 162 | + |
| 163 | + |
| 164 | +if __name__ == "__main__": |
| 165 | + main() |
0 commit comments