import numpy as np
import math
from itertools import combinations
from collections import defaultdict
# --- Configuration ---
MAX_GOALS_FOR_PROB_DISPLAY = 6 # Max goals for displaying score probability matrix (optional)
ELO_K_FACTOR = 32 # K-factor for Elo rating updates
# Assumed average probability of a draw in a typical match
# This is used to apportion win/loss probabilities from the Elo expectation
# You might adjust this based on the league's characteristics
PROB_DRAW_ESTIMATE = 0.25
# Define the clubs: initial Elo and their average goal-scoring potential (lambda)
# Lambda is for the Poisson score simulation
# Elo is for win probability calculation and dynamic updates
CLUBS_DATA = {
"Alpha FC": {"elo": 1500, "lambda": 1.5},
"Bravo United": {"elo": 1450, "lambda": 1.2},
"Charlie Rovers": {"elo": 1550, "lambda": 1.8},
"Delta City": {"elo": 1400, "lambda": 1.0},
}
CLUBS = list(CLUBS_DATA.keys())
# --- Elo Helper Functions ---
def calculate_elo_expected_score(elo1, elo2):
"""
Calculates the expected score for player 1 based on Elo ratings.
Expected score (E1) is the probability of player 1 winning + 0.5 * probability of draw.
More simply, it's often interpreted as P(Player1 wins) in a two-outcome system.
"""
return 1 / (1 + 10**((elo2 - elo1) / 400))
def calculate_elo_outcome_probabilities(elo1, elo2, global_draw_prob=PROB_DRAW_ESTIMATE):
"""
Estimates Win/Draw/Loss probabilities based on Elo difference,
adjusting for a global draw probability.
"""
expected1_no_draw = calculate_elo_expected_score(elo1, elo2) # P(Team1 wins if no draw)
# Distribute the non-draw probability based on Elo expectation
prob1_wins = expected1_no_draw * (1 - global_draw_prob)
prob2_wins = (1 - expected1_no_draw) * (1 - global_draw_prob)
prob_draw = global_draw_prob
# Normalize to ensure sum is 1 (minor adjustments might be needed due to float precision)
total_prob = prob1_wins + prob2_wins + prob_draw
if total_prob == 0: return 0.33, 0.34, 0.33 # Should not happen with valid Elos
return prob1_wins / total_prob, prob_draw / total_prob, prob2_wins / total_prob
def update_elo_ratings(elo1, elo2, score1, score2, k_factor=ELO_K_FACTOR):
"""
Updates Elo ratings for two teams based on match outcome.
score1, score2 are goals.
"""
actual_score1 = 0.0
if score1 > score2:
actual_score1 = 1.0 # Team 1 won
elif score1 == score2:
actual_score1 = 0.5 # Draw
# If score1 < score2, actual_score1 remains 0.0 (Team 1 lost)
expected_score1 = calculate_elo_expected_score(elo1, elo2)
new_elo1 = elo1 + k_factor * (actual_score1 - expected_score1)
# Elo is zero-sum, so elo2 changes by the negative of elo1's change with respect to expected_score2
# expected_score2 = 1 - expected_score1
# actual_score2 = 1 - actual_score1
# new_elo2 = elo2 + k_factor * (actual_score2 - expected_score2)
# new_elo2 = elo2 + k_factor * ((1 - actual_score1) - (1 - expected_score1))
# new_elo2 = elo2 + k_factor * (-actual_score1 + expected_score1)
new_elo2 = elo2 - k_factor * (actual_score1 - expected_score1) # Simpler: Elo2 change is opposite of Elo1
return round(new_elo1), round(new_elo2)
# --- Poisson Helper Functions (for score simulation) ---
def poisson_probability(k, lam):
"""Calculates the probability of k events (goals) given average rate lam."""
if k < 0: return 0
# Handle potentially large k for factorial by using log gamma if available
try:
return (lam**k * math.exp(-lam)) / math.factorial(k)
except OverflowError: # Fallback for very large k, though unlikely for goals
# This part is more robust for very large numbers but usually not needed for goals
log_prob = k * math.log(lam) - lam - math.lgamma(k + 1)
return math.exp(log_prob)
def simulate_match_score(lambda1, lambda2):
"""
Simulates the exact score of a match using Poisson distribution
based on the teams' predefined average goal scoring rates.
"""
goals1 = np.random.poisson(lambda1)
goals2 = np.random.poisson(lambda2)
return goals1, goals2
# --- League Table Functions ---
def update_league_table(table, team1_name, team1_goals, team2_name, team2_goals):
"""Updates the league table based on match results."""
# Team 1 stats
table[team1_name]['P'] += 1
table[team1_name]['GF'] += team1_goals
table[team1_name]['GA'] += team2_goals
table[team1_name]['GD'] = table[team1_name]['GF'] - table[team1_name]['GA']
# Team 2 stats
table[team2_name]['P'] += 1
table[team2_name]['GF'] += team2_goals
table[team2_name]['GA'] += team1_goals
table[team2_name]['GD'] = table[team2_name]['GF'] - table[team2_name]['GA']
# Points
if team1_goals > team2_goals:
table[team1_name]['W'] += 1
table[team1_name]['Pts'] += 3
table[team2_name]['L'] += 1
elif team2_goals > team1_goals:
table[team2_name]['W'] += 1
table[team2_name]['Pts'] += 3
table[team1_name]['L'] += 1
else:
table[team1_name]['D'] += 1
table[team1_name]['Pts'] += 1
table[team2_name]['D'] += 1
table[team2_name]['Pts'] += 1
def print_league_table(table, club_data_for_elo):
"""Prints the final league table, sorted by points, GD, GF."""
sorted_table_items = sorted(
table.items(),
key=lambda item: (item[1]['Pts'], item[1]['GD'], item[1]['GF']),
reverse=True
)
print("\n--- Final League Table ---")
header = f"{'Pos':<4} {'Club':<15} {'P':>3} {'W':>3} {'D':>3} {'L':>3} {'GF':>3} {'GA':>3} {'GD':>4} {'Pts':>4} {'Elo':>5}"
print(header)
print("-" * len(header))
for i, (club_name, stats) in enumerate(sorted_table_items):
elo_rating = club_data_for_elo[club_name]['elo']
print(f"{i+1:<4} {club_name:<15} {stats['P']:>3} {stats['W']:>3} {stats['D']:>3} {stats['L']:>3} "
f"{stats['GF']:>3} {stats['GA']:>3} {stats['GD']:>4} {stats['Pts']:>4} {elo_rating:>5}")
# --- Main Simulation Logic ---
def run_season():
# Make a copy of CLUBS_DATA to store dynamic Elo ratings for the season
current_club_data = {name: data.copy() for name, data in CLUBS_DATA.items()}
league_table = defaultdict(lambda: {'P': 0, 'W': 0, 'D': 0, 'L': 0, 'GF': 0, 'GA': 0, 'GD': 0, 'Pts': 0})
# Generate fixtures (each team plays each other once)
fixtures = list(combinations(CLUBS, 2))
print("--- Season Simulation ---")
match_number = 1
for team1_name, team2_name in fixtures:
print(f"\n--- Match {match_number}: {team1_name} (Elo: {current_club_data[team1_name]['elo']}) vs {team2_name} (Elo: {current_club_data[team2_name]['elo']}) ---")
elo1 = current_club_data[team1_name]['elo']
elo2 = current_club_data[team2_name]['elo']
# 1. Calculate and display win probabilities using Elo
prob1_win, prob_draw, prob2_win = calculate_elo_outcome_probabilities(elo1, elo2)
print("Elo-based Probabilities:")
print(f" {team1_name} Win: {prob1_win:.2%}")
print(f" Draw: {prob_draw:.2%}")
print(f" {team2_name} Win: {prob2_win:.2%}")
# 2. Simulate exact score using Poisson with predefined team lambdas
lambda1 = current_club_data[team1_name]['lambda']
lambda2 = current_club_data[team2_name]['lambda']
goals1, goals2 = simulate_match_score(lambda1, lambda2)
print(f"Poisson Simulated Result: {team1_name} {goals1} - {goals2} {team2_name}")
# 3. Update Elo ratings based on the simulated result
new_elo1, new_elo2 = update_elo_ratings(elo1, elo2, goals1, goals2)
print(f"Elo Update: {team1_name}: {elo1} -> {new_elo1} ({new_elo1-elo1:+}) | {team2_name}: {elo2} -> {new_elo2} ({new_elo2-elo2:+})")
current_club_data[team1_name]['elo'] = new_elo1
current_club_data[team2_name]['elo'] = new_elo2
# 4. Update league table
update_league_table(league_table, team1_name, goals1, team2_name, goals2)
match_number += 1
# 5. Print final table
print_league_table(league_table, current_club_data)
# --- Run the simulation ---
if __name__ == "__main__":
run_season()