├── FootballTDA.png ├── cv_output.pickle ├── requirements.txt ├── utils.py ├── .gitignore ├── README.md ├── sub_space_extraction.py ├── notebook_functions.py ├── soccer_basics.py ├── cross_validation.py ├── database.py ├── FootballTDA.ipynb ├── compute_statistics.py └── LICENSE /FootballTDA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/football-tda/HEAD/FootballTDA.png -------------------------------------------------------------------------------- /cv_output.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giotto-ai/football-tda/HEAD/cv_output.pickle -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | giotto-tda>=0.1.4 2 | pandas>=0.25.3 3 | pyarrow==0.15.1 4 | tqdm>=4.38.0 5 | wget>=3.2 6 | openml 7 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import pickle as pkl 2 | 3 | 4 | def read_pickle(path): 5 | with open(path, 'rb') as f: 6 | return pkl.load(f) 7 | 8 | 9 | def write_pickle(path, array): 10 | with open(path, 'wb') as f: 11 | pkl.dump(array, f) 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | # Ignore .idea file 3 | .idea 4 | 5 | # Ignore the notebook trash 6 | *.ipynb_checkpoints 7 | 8 | # Ignore some folders 9 | __pycache__/ 10 | 11 | # Ignore data 12 | *.pickle 13 | *.parquet 14 | database.sqlite 15 | 16 | !data/** 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![logo](https://raw.githubusercontent.com/giotto-ai/giotto-tda/master/doc/images/tda_logo.svg) 2 | 3 | # football-tda 4 | The purpose of this project is to show a possible application of TDA. Our use case is 5 | based on football and the goal (pun intended) is to try to forecast the outcome of a 6 | match. 7 | 8 | You can find our blog post at this 9 | [link](https://towardsdatascience.com/the-shape-of-football-games-1589dc4e652a). 10 | 11 | ## Data 12 | The dataset we used can be found [here](https://www.kaggle.com/hugomathien/soccer). 13 | It is a collection of more than 25,000 european football matches from 2008 to 2016. 14 | For each match, the starting eleven are available for both teams, as well as match 15 | statistics and bookmaker odds. 16 | 17 | The dataset also contains the attributes of more than 10,000 players taken from EA 18 | Sports' FIFA video game series, including weekly updates. 19 | 20 | ## Feature Creation 21 | The assumption we made is that each match can be modelled as the attributes of the 22 | starting eleven of the two teams. Since in this way the number of features was too 23 | high, an additional aggregation step was required (see the notebook for further 24 | details). 25 | 26 | Thus, each match can be considered as a vector in a vector space and the totality of 27 | matches can be viewed as a point cloud. 28 | 29 | For capturing local information surrounding a match, we computed persistent homology 30 | of its k-nearest neighbours and use it as a feature. 31 | 32 | ## Model 33 | We cross-validated a random forest classifier and train it to predict the outcome of 34 | a match. In order to validate our results, we used an elo-rating system and the odds 35 | of the market as baselines. 36 | 37 | ## Results 38 | Our results show that our model out-performs the elo-rating system and is 39 | comparable to the market. 40 | 41 | ## Notebook overview 42 | Given the promising results, we tried to simulate an entire championship with the 43 | ultimate purpose of evaluating the impact that a player would have had if hired by 44 | our favorite team. Therefore, we offer the possibility to select both the favorite 45 | player and the lucky team where to insert him. Then you can simulate the championship 46 | and check if your player improves the final ranking of his new team (little spoiler: 47 | Messi does!). 48 | 49 | Enjoy! 50 | 51 | ## Requirements 52 | In order to run the notebook, the following python packages are required: 53 | 54 | - giotto-tda 0.1.4 55 | - pandas 0.25.3 56 | - pyarrow 0.15.1 57 | - tqdm 4.38.0 58 | - wget 3.2 59 | - openml 60 | -------------------------------------------------------------------------------- /sub_space_extraction.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from gtda.diagrams import PairwiseDistance 3 | from joblib import Parallel, delayed 4 | from scipy.spatial.distance import squareform, pdist 5 | from sklearn.base import BaseEstimator 6 | from sklearn.base import TransformerMixin 7 | 8 | 9 | class SubSpaceExtraction(BaseEstimator, TransformerMixin): 10 | def __init__(self, 11 | dist_percentage=0.05, 12 | k_min=10, 13 | k_max=100, 14 | metric="euclidean", 15 | n_jobs=-1): 16 | self.n_jobs = n_jobs 17 | self.dist_percentage = dist_percentage 18 | self.k_min = k_min 19 | self.k_max = k_max 20 | self.metric = metric 21 | 22 | def _select_subspace(self, space, label, matrix_distances, ind_x): 23 | target_vector_dist = matrix_distances[ind_x] 24 | max_dist = np.max(target_vector_dist) * self.dist_percentage 25 | 26 | indexes = target_vector_dist < max_dist 27 | if np.sum(indexes) > self.k_max: 28 | indexes = np.argsort(target_vector_dist)[:self.k_max] 29 | elif np.sum(indexes) < self.k_min: 30 | indexes = np.argsort(target_vector_dist)[:self.k_min] 31 | 32 | return space[indexes], label[indexes] 33 | 34 | def fit_transform_resample(self, X, y): 35 | self.fit(X, y) 36 | return self.transform(X, y) 37 | 38 | def fit(self, X, y): 39 | return self 40 | 41 | def transform(self, X, y): 42 | """ The transform method takes as input an array of dimension (n_sample, n_features) and for each sample 43 | it creates the neighourood point clouds.""" 44 | def compute_all_distances(X, metric): 45 | if metric == "euclidean": 46 | return squareform(pdist(X, metric)) 47 | else: 48 | return PairwiseDistance(metric=metric, n_jobs=self.n_jobs).fit_transform(X) 49 | 50 | distance_matrix = compute_all_distances(X, self.metric) 51 | 52 | Xy_list = Parallel(n_jobs=self.n_jobs)(delayed(self._select_subspace)(X, y, distance_matrix, i) for i in range(len(X))) 53 | 54 | max_n_points = np.max([x[0].shape[0] for x in Xy_list]) 55 | 56 | X_new_dims = list(X.shape) 57 | X_new_dims.insert(1, max_n_points) 58 | 59 | X_new = np.empty(X_new_dims) 60 | y_new = np.full((X.shape[0], max_n_points), np.nan) 61 | 62 | for i, element in enumerate(Xy_list): 63 | X_new[i, :len(element[0])] = element[0] 64 | X_new[i, len(element[0]):] = element[0][-1] 65 | y_new[i, :len(element[1])] = element[1] 66 | 67 | return X_new, (y_new, X) 68 | 69 | -------------------------------------------------------------------------------- /notebook_functions.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | from openml.datasets import get_dataset 4 | 5 | from utils import read_pickle 6 | import soccer_basics 7 | 8 | from gtda.pipeline import Pipeline 9 | from sub_space_extraction import SubSpaceExtraction 10 | from gtda.homology import VietorisRipsPersistence 11 | 12 | from cross_validation import extract_features_for_prediction 13 | 14 | 15 | COLUMNS_TO_KEEP = ["home_best_attack", "home_best_defense", "home_avg_attack", "home_avg_defense", 16 | "home_std_attack", "home_std_defense", "gk_home_player_1", 17 | "away_avg_attack", "away_avg_defense", "away_std_attack", "away_std_defense", 18 | "away_best_attack", "away_best_defense", "gk_away_player_1" 19 | ] 20 | 21 | pl_team_names = ['Burnley', 'Leicester City', 'Chelsea', 'Manchester City', 'Southampton', 'Sunderland', 22 | 'Tottenham Hotspur', 'Liverpool', 'West Ham United', 'West Bromwich Albion', 'Hull City', 23 | 'Everton', 'Arsenal', 'Crystal Palace', 'Swansea City', 'Queens Park Ranger', 'Stoke City', 24 | 'Aston Villa', 'Manchester United', 'Newcastle United'] 25 | 26 | serie_a_team_names = ['Sassuolo', 'Atalanta', 'Chievo Verona', 'Empoli', 'Fiorentina', 'Palermo', 'Lazio', 'Milan', 27 | 'Udinese', 'Inter', 'Roma', 'Torino', 'Bologna', 'Napoli', 'Hellas Verona', 'Sampdoria', 28 | 'Juventus', 'Frosinone', 'Genoa', 'Carpi'] 29 | 30 | teams_with_messi = pd.DataFrame([('Chelsea', '%+d' % 0, ' 0.25', '0.84', '0.00', ' 0.41', '0.94', '0.00'), 31 | ('Manchester City', '%+d' % 1, '0.59', '0.97', '0.00', '0.58', '0.97', '0.00'), 32 | ('Arsenal', '%+d' % 0, '0.05', '0.56', '0.00', '0.17', '0.82', '0.00'), 33 | ('Manchester United', '%+d' % 1, ' 0.10', '0.69', '0.00', '0.17', '0.81', '0.00'), 34 | ('Tottenham', '%+d' % 1, '0.03', '0.44', '0.00', '0.06', '0.56', '0.00'), 35 | ('Liverpool', '%+d' % 3, '0.01', ' 0.17', '0.01', '0.10', '0.66', '0.00'), 36 | ('Southampton', '%+d' % 0, '0.00', '0.01', '0.14', '0.01', '0.19', '0.01'), 37 | ('Swansea City', '%+d' % 0, '0.00', '0.01', '0.16', '0.01', '0.04', '0.08'), 38 | ('Stoke City', '%+d' % 2, '0.00', '0.01', '0.15', '0.01', '0.16', '0.01'), 39 | ('Crystal Palace', '%+d' % 2, '0.00', '0.00', '0.29', '0.00', '0.05', '0.07'), 40 | ('Everton', '%+d' % 4, '0.01', '0.22', '0.01', '0.09', '0.20', '0.01'), 41 | ('West Ham United', '%+d' % 4, '0.00', '0.01', '0.18', '0.01', '0.11', '0.03'), 42 | ('West Bromwich', '%+d' % 5, '0.00', '0.01', '0.25', '0.00', '0.06', '0.07'), 43 | ('Leicester City', '%+d' % 5, '0.00', '0.00', '0.42', '0.19', '0.72', '0.00'), 44 | ('Newcastle United', '%+d' % 9, '0.00', '0.02', '0.11', '0.01', '0.24', '0.01'), 45 | ('Aston Villa', '%+d' % 8, '0.00', '0.01', '0.15', '0.01', '0.11', '0.02'), 46 | 47 | ('Sunderland', '%+d' % 9, '0.00', '0.01', '0.31', '0.00', '0.04', '0.08'), 48 | 49 | ('Hull City', '%+d' % 9, '0.00', '0.01', '0.30', '0.00', '0.03', '0.09'), 50 | ('Burnley', '%+d' % 10, '0.00', '0.00', '0.31', '0.00', '0.04', '0.11'), 51 | ('QPR', '%+d' % 11, '0.00', '0.00', '0.22', '0.00', '0.13', '0.02'), 52 | 53 | ], columns=['Team', 'Delta Pos.', 'Pr. Win', 'Pr. TOP 4', 'Pr. Rel.', 54 | 'Pr. Win. with Messi', 'Pr. TOP 4. with Messi', 'Pr. Rel. with Messi'] 55 | ) 56 | 57 | 58 | def compute_final_standings(prob_match_df, championship='premier league'): 59 | p1 = prob_match_df.home_team_prob.reset_index(drop=True) 60 | px = prob_match_df.draw_prob.reset_index(drop=True) 61 | p2 = prob_match_df.away_team_prob.reset_index(drop=True) 62 | x, y = soccer_basics.simulation_champion(prob_match_df, p1, px, p2, 1000) 63 | 64 | if championship == 'premier league': 65 | names = pl_team_names 66 | else: 67 | names = serie_a_team_names 68 | 69 | teams = np.sort(prob_match_df.home_team_api_id.unique()) 70 | soccer_basics.printer_ranks(x, y, teams, names) 71 | 72 | 73 | def get_pipeline(top_feat_params): 74 | pipeline = Pipeline([('extract_point_clouds', SubSpaceExtraction(**top_feat_params)), 75 | ('create_diagrams', VietorisRipsPersistence(n_jobs=-1))]) 76 | return pipeline 77 | 78 | 79 | def get_best_params(): 80 | cv_output = read_pickle('cv_output.pickle') 81 | best_model_params, top_feat_params, top_model_feat_params, *_ = cv_output 82 | 83 | return top_feat_params, top_model_feat_params 84 | 85 | 86 | def get_useful_cols(players_df): 87 | return players_df[COLUMNS_TO_KEEP] 88 | 89 | 90 | def load_dataset(): 91 | x_y = get_dataset(42188).get_data(dataset_format='array')[0] 92 | x_train_with_topo = x_y[:, :-1] 93 | y_train = x_y[:, -1] 94 | return x_train_with_topo, y_train 95 | 96 | 97 | def extract_x_test_features(x_train, y_train, players_df, pipeline): 98 | """Extract the topological features from the test set. This requires also the train set 99 | 100 | Parameters 101 | ---------- 102 | x_train: 103 | The x used in the training phase 104 | y_train: 105 | The y used in the training phase 106 | players_df: pd.DataFrame 107 | The DataFrame containing the matches with all the players, from which to extract the test set 108 | pipeline: Pipeline 109 | The Giotto pipeline 110 | 111 | Returns 112 | ------- 113 | x_test: 114 | The x_test with the topological features 115 | """ 116 | x_train_no_topo = x_train[:, :14] 117 | y_test = np.zeros(len(players_df)) # Artificial y_test for features computation 118 | x_test_topo = extract_features_for_prediction(x_train_no_topo, y_train, players_df.values, y_test, pipeline) 119 | 120 | return x_test_topo 121 | 122 | 123 | def get_team_ids(players_df): 124 | """Get the team ids contained in the players_df DataFrame 125 | 126 | Parameters 127 | ---------- 128 | players_df: pd.DataFrame 129 | The DataFrame containing all the matches 130 | """ 131 | return players_df[['home_team_api_id', 'away_team_api_id']] 132 | 133 | 134 | def get_probabilities(model, x_test, team_ids): 135 | """Get the probabilities on the outcome of the matches contained in the test set 136 | 137 | Parameters 138 | ---------- 139 | model: 140 | The model (must have the 'predict_proba' function) 141 | x_test: 142 | The test set 143 | team_ids: pd.DataFrame 144 | The DataFrame containing, for each match in the test set, the ids of the two teams 145 | Returns 146 | ------- 147 | probabilities: 148 | The probabilities for each match in the test set 149 | """ 150 | prob_pred = model.predict_proba(x_test) 151 | prob_match_df = pd.DataFrame(data=prob_pred, columns=['away_team_prob', 'draw_prob', 'home_team_prob']) 152 | prob_match_df = pd.concat([team_ids.reset_index(drop=True), prob_match_df], axis=1) 153 | return prob_match_df 154 | -------------------------------------------------------------------------------- /soccer_basics.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Nov 7 15:29:26 2019 5 | 6 | @author: dantitussalajan 7 | """ 8 | 9 | import numpy as np 10 | 11 | 12 | # adding some useful columns; data is dataframe that must contain the mentioned columnms -- see the parquet function 13 | # best add it for all data at the begining 14 | def useful_updates1(data): 15 | diff = np.sign(data['home_team_goal'] - data['away_team_goal']) 16 | # adding the results; 1=home win, 0=away win, 0.5=draw 17 | data['result'] = np.round((1 + diff) / 2, 1) 18 | # a market prediction column: 1=home has best odds, 0=away has best odds, 0.5=draw has best odds 19 | n = len(data) 20 | market_prediction = np.zeros(n) + 0.5 21 | for k in range(data.index[0], data.index[-1] + 1): 22 | r = np.argmin([data['B365A'][k], data['B365D'][k], data['B365H'][k]]) / 2 23 | market_prediction[k] = r 24 | data['market_prediction'] = market_prediction 25 | 26 | 27 | # add elo standard vanilla elo ratings 28 | # as there are online updates is best to compute it for all data again 29 | def get_elo(data, K, handicap): 30 | n = len(data) 31 | # elos is the array of elos -- size 300000 is a hack to cover all possible teams ids . it must be > than all team ids to work 32 | # no_matches is the number of matches played by the team before this match (in the data)$ 33 | # (this is needed because usually people use elos only after 30 matches -- rule of thumb) 34 | elos = np.zeros(300000) + 1500 35 | no_match = np.zeros(300000) 36 | # we construct the new columns... 37 | # the elo appearing in a match's row is the elo BEFORE the match 38 | elo_home = np.zeros(n) + 1500 39 | elo_away = np.zeros(n) + 1500 40 | match_home = np.zeros(n) 41 | match_away = np.zeros(n) 42 | for k in range(data.index[0], data.index[-1] + 1): 43 | # we are at match indexed by k 44 | # getting the teams in integer forms 45 | h = np.int(data['home_team_api_id'][k]) 46 | a = np.int(data['away_team_api_id'][k]) 47 | res = data['result'][k] 48 | # write elos and number of matches before the current match 49 | elo_home[k] = elos[h] 50 | elo_away[k] = elos[a] 51 | match_home[k] = no_match[h] 52 | match_away[k] = no_match[a] 53 | # get current elos/before the match to plug them in formulas 54 | elo_h = elos[h] 55 | elo_a = elos[a] 56 | # get the win/loss (no draw) probabilities coming from the current elo 57 | delta_h = elo_h - elo_a + handicap 58 | proba_h = 1 / (1 + np.power(10.0, -delta_h / 400)) 59 | # update the elo of the two teams in the elos array; notice that it will be written in the dataset next time the teams play 60 | ammount_changed = K * (res - proba_h) 61 | elos[h] += ammount_changed 62 | elos[h] = np.round(elos[h]) 63 | elos[a] -= ammount_changed 64 | elos[a] = np.round(elos[a]) 65 | # update the number of matches so far 66 | no_match[h] += 1 67 | no_match[a] += 1 68 | data['elo_home'] = elo_home.astype(int) 69 | data['elo_away'] = elo_away.astype(int) 70 | data['match_home'] = match_home.astype(int) 71 | data['match_away'] = match_away.astype(int) 72 | 73 | 74 | # add columns with market & elo probabilities 75 | # notice this must be the same handicap (in principle) from get_elo 76 | def useful_updates2(data, handicap): 77 | n = len(data) 78 | # market probabilities 79 | data['M1'] = (1 / data['B365H']) / (1 / data['B365H'] + 1 / data['B365D'] + 1 / data['B365A']) 80 | data['MX'] = (1 / data['B365D']) / (1 / data['B365H'] + 1 / data['B365D'] + 1 / data['B365A']) 81 | data['M2'] = (1 / data['B365A']) / (1 / data['B365H'] + 1 / data['B365D'] + 1 / data['B365A']) 82 | # elo probabilities 83 | E1 = np.zeros(n) + 1 / 3 84 | EX = np.zeros(n) + 1 / 3 85 | E2 = np.zeros(n) + 1 / 3 86 | for k in range(data.index[0], data.index[-1] + 1): 87 | # as Elo ratings do not include draws, we take the draw proba of the matket 88 | # the binary probabilities from the 89 | EX[k] = data['MX'][k] 90 | delta_h = data['elo_home'][k] - data['elo_away'][k] + handicap 91 | # the Elo initial probabilities 92 | proba_h = 1 / (1 + np.power(10.0, -delta_h / 400)) 93 | proba_a = 1 - proba_h 94 | # rescale 95 | E1[k] = proba_h * (1 - EX[k]) 96 | E2[k] = proba_a * (1 - EX[k]) 97 | data['E1'] = E1 98 | data['EX'] = EX 99 | data['E2'] = E2 100 | 101 | 102 | # Elo based prediction with >=30 matches condition 103 | 104 | def ternary_prediction(data, barrier): 105 | count_elo = 0 106 | ok_elo = 0 107 | a = np.sign(data.elo_home - data.elo_away) 108 | for k in range(data.index[0], data.index[-1]): 109 | if (data['match_home'][k] < barrier) or (data['match_away'][k] < barrier): 110 | continue 111 | count_elo += 1 112 | elo_prediction = (1 + a[k]) / float(2) 113 | if data['result'][k] == elo_prediction: 114 | ok_elo += 1 115 | print('accuracy', np.round(ok_elo / float(count_elo), 3)) 116 | 117 | 118 | # FROM NOW ON CHAMPIONSHIP SIMULATIONS 119 | 120 | # putting smaller ids for the team -- between 0-20 if data=one championship 121 | def team_index(data): 122 | n = len(data) 123 | teams = np.sort(data.home_team_api_id.unique()) 124 | home_team = np.zeros(n) 125 | away_team = np.zeros(n) 126 | for k in range(n): 127 | home_team[k] = np.where(teams == data['home_team_api_id'][k])[0][0] 128 | away_team[k] = np.where(teams == data['away_team_api_id'][k])[0][0] 129 | data['home_team'] = home_team.astype(int) 130 | data['away_team'] = away_team.astype(int) 131 | 132 | 133 | # reading 3 arrays of probabilities 134 | def read_probabilities(data, p1, px, p2): 135 | data['P1'] = p1 136 | data['PX'] = px 137 | data['P2'] = p2 138 | 139 | 140 | # n is data size, d+1 is the number of teams; simulation of one championship 141 | def one_champion(data, n, d): 142 | points = np.zeros(d + 1) 143 | for k in range(n): 144 | i = data['home_team'][k] 145 | j = data['away_team'][k] 146 | r = np.random.choice([3, 1, 0], p=[data['P1'][k], data['PX'][k], data['P2'][k]]) 147 | points[i] += r 148 | if r == 1: 149 | points[j] += 1 150 | else: 151 | points[j] += 3 - r 152 | return points.astype(int) 153 | 154 | 155 | # mapping the points to rankings 156 | def points_to_rankings(points): 157 | d = len(points) 158 | ranks = np.arange(d) 159 | # create an intermediate array 160 | M = np.max(points) 161 | interim = np.zeros(M + 1) 162 | for k in range(d): 163 | interim[points[k]] += 1 164 | # assigning ranks to the team 165 | # ranks[j]=i means team i is raked #j 166 | current_rank = 0 167 | for k in range(M, -1, -1): 168 | if interim[k] > 0: 169 | a = np.where(points == k)[0] 170 | # just a trick to get a random permutation of teams with k points 171 | b = np.random.choice(a, len(a), replace=False) 172 | ranks[current_rank:current_rank + len(a)] = b 173 | current_rank += len(a) 174 | return ranks.astype(int) 175 | 176 | 177 | # simultation, many replays, of a championships 178 | # batches of 100 championships 179 | def simulation_champion(data, p1, px, p2, experiment_size): 180 | n = len(data) 181 | team_index(data) 182 | read_probabilities(data, p1, px, p2) 183 | d = np.max(data.home_team) 184 | avg_points = np.zeros(d + 1) 185 | all_ranks = np.zeros((d + 1, d + 1)) 186 | for k in range(1, experiment_size + 1): 187 | if k % 100 == 0: 188 | print('simulation batch', k // 100) 189 | # print('simulation',k) 190 | points = one_champion(data, n, d) 191 | ranks = points_to_rankings(points) 192 | for j in range(d + 1): 193 | all_ranks[ranks[j]][j] += 1 194 | avg_points = avg_points * ((k - 1) / k) + points * (1 / k) 195 | return avg_points, all_ranks / experiment_size 196 | 197 | 198 | # print the expected rankings 199 | # x=expected points 200 | # y[i][j]=probability of team #i being ranked #j 201 | # teams are the ordered id teams 202 | # names must be the names of the teams, ordered by ids 203 | def printer_ranks(x, y, teams, names): 204 | d = len(x) 205 | z = np.flip(np.sort(x)) 206 | rankings = np.zeros(d) 207 | current_rank = 0 208 | for k in z: 209 | i = np.where(x == k)[0][0] 210 | rankings[current_rank] = i 211 | current_rank += 1 212 | # print(rankings) 213 | for j in range(d): 214 | i = np.int(rankings[j]) 215 | print(j + 1, names[i], np.round(x[i])) 216 | print('probabilities to win the title, to be top 4, to be last 3') 217 | for j in range(d): 218 | i = np.int(rankings[j]) 219 | print(j + 1, names[i], np.round(y[i][0], 3), np.round(np.sum(y[i][0:4]), 2), np.round(np.sum(y[i][-3:]), 2)) 220 | return rankings 221 | -------------------------------------------------------------------------------- /cross_validation.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | 4 | import gtda as o 5 | from gtda.pipeline import Pipeline 6 | from gtda.homology import VietorisRipsPersistence 7 | from gtda.diagrams import Amplitude 8 | from openml.datasets import get_dataset 9 | from tqdm import tqdm 10 | 11 | from itertools import chain, combinations 12 | 13 | from sklearn.ensemble import RandomForestClassifier 14 | 15 | from sub_space_extraction import SubSpaceExtraction 16 | from utils import write_pickle 17 | 18 | 19 | def extract_topological_features(diagrams): 20 | metrics = ['bottleneck', 'wasserstein', 'landscape', 'betti', 'heat'] 21 | new_features = [] 22 | for metric in metrics: 23 | amplitude = Amplitude(metric=metric) 24 | new_features.append(amplitude.fit_transform(diagrams)) 25 | new_features = np.concatenate(new_features, axis=1) 26 | return new_features 27 | 28 | 29 | def compute_match_result(df): 30 | return np.sign(df['home_team_goal'] - df['away_team_goal']) 31 | 32 | 33 | def extract_features_for_prediction(x_train, y_train, x_test, y_test, pipeline): 34 | shift = 10 35 | top_features = [] 36 | all_x_train = x_train 37 | all_y_train = y_train 38 | for i in tqdm(range(0, len(x_test), shift)): 39 | if i+shift > len(x_test): 40 | shift = len(x_test) - i 41 | batch = np.concatenate([all_x_train, x_test[i: i + shift]]) 42 | batch_y = np.concatenate([all_y_train, y_test[i: i + shift].reshape((-1,))]) 43 | diagrams_batch, _ = pipeline.fit_transform_resample(batch, batch_y) 44 | new_features_batch = extract_topological_features(diagrams_batch[-shift:]) 45 | top_features.append(new_features_batch) 46 | all_x_train = np.concatenate([all_x_train, batch[-shift:]]) 47 | all_y_train = np.concatenate([all_y_train, batch_y[-shift:]]) 48 | final_x_test = np.concatenate([x_test, np.concatenate(top_features, axis=0)], axis=1) 49 | return final_x_test 50 | 51 | 52 | def _check_no_repetitions(tuple_list): 53 | elems = [x[0] for x in tuple_list] 54 | return len(np.unique(elems)) == len(tuple_list) 55 | 56 | 57 | def _powerset(iterable): 58 | "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" 59 | s = list(iterable) # allows duplicate elements 60 | return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) 61 | 62 | 63 | def construct_model_param_dictionary(parameters): 64 | tuple_dictionary = [] 65 | 66 | for key in parameters.keys(): 67 | for value in parameters[key]: 68 | tuple_dictionary.append((key, value)) 69 | 70 | valid_combinations = [] 71 | for i, combo in enumerate(_powerset(tuple_dictionary), 1): 72 | if len(combo) == len(parameters): 73 | if _check_no_repetitions(combo): 74 | print(combo) 75 | valid_combinations.append(combo) 76 | 77 | return valid_combinations 78 | 79 | 80 | def best_combination(list_of_dictionaries): 81 | return sorted(list_of_dictionaries, key=lambda x: x["score"])[-1] 82 | 83 | 84 | class CrossValidation: 85 | def __init__(self, k_mins, k_maxs, dist_percentages, **model_parameters): 86 | self.dist_percentages = dist_percentages 87 | self.k_mins = k_mins 88 | self.k_maxs = k_maxs 89 | self.model_parameters = model_parameters 90 | 91 | def _validate_k_fold_top(self, model, x_train, y_train, x_test, y_test): 92 | validation_quantities = [] 93 | 94 | for k_min in self.k_mins: 95 | for k_max in self.k_maxs: 96 | for dist_percentage in self.dist_percentages: 97 | print(f"k_min, k_max, dist_percentage: {k_min}, {k_max}, {dist_percentage}") 98 | pipeline_list = [('extract_subspaces', SubSpaceExtraction(dist_percentage=dist_percentage, 99 | k_min=k_min, k_max=k_max, 100 | metric="euclidean", n_jobs=-1)), 101 | ('compute_diagrams', VietorisRipsPersistence(n_jobs=-1))] 102 | top_pipeline = Pipeline(pipeline_list) 103 | 104 | diagrams_train, _ = top_pipeline.fit_transform_resample(x_train, y_train) 105 | 106 | top_features_train = extract_topological_features(diagrams_train) 107 | 108 | x_train_model = np.concatenate([x_train, top_features_train], axis=1) 109 | model.fit(x_train_model, y_train) 110 | 111 | x_test_model = extract_features_for_prediction(x_train, y_train, x_test, y_test, top_pipeline) 112 | 113 | score = model.score(x_test_model, y_test) 114 | output_dictionary = {"k_min": k_min, "k_max": k_max, 115 | "dist_percentage": dist_percentage, "score": score} 116 | validation_quantities.append(output_dictionary) 117 | 118 | return validation_quantities 119 | 120 | def _validate_k_fold_model(self, x_train, y_train, x_test, y_test): 121 | validation_quantities = [] 122 | 123 | valid_combinations = construct_model_param_dictionary(self.model_parameters) 124 | for combination in valid_combinations: 125 | dictionary = {key: value for key, value in combination} 126 | 127 | model = RandomForestClassifier(**dictionary) 128 | model.fit(x_train, y_train) 129 | score = model.score(x_test, y_test) 130 | dictionary["score"] = score 131 | validation_quantities.append(dictionary) 132 | 133 | return validation_quantities 134 | 135 | def cross_validate(self, full_x, full_y, splitting_dates): 136 | train_split_date = splitting_dates[0] 137 | val_split_date = splitting_dates[1] 138 | end_date = splitting_dates[2] 139 | 140 | train_x = full_x[(full_x.date < train_split_date) | (full_x.date >= end_date)] 141 | train_y = full_y[(full_x.date < train_split_date) | (full_x.date >= end_date)] 142 | 143 | val_x = full_x[(full_x.date >= train_split_date) & (full_x.date < val_split_date)] 144 | val_y = full_y[(full_x.date >= train_split_date) & (full_x.date < val_split_date)] 145 | 146 | test_x = full_x[(full_x.date >= val_split_date) & (full_x.date < end_date)] 147 | test_y = full_y[(full_x.date >= val_split_date) & (full_x.date < end_date)] 148 | 149 | train_x.pop("date") 150 | val_x.pop("date") 151 | test_x.pop("date") 152 | 153 | train_x = train_x.values 154 | train_y = train_y.values 155 | val_x = val_x.values 156 | val_y = val_y.values 157 | test_x = test_x.values 158 | test_y = test_y.values 159 | 160 | print("START VALIDATING MODEL") 161 | models_cv = self._validate_k_fold_model(train_x, train_y, val_x, val_y) 162 | best_model_params = best_combination(models_cv) 163 | best_model_params.pop("score") 164 | best_model = RandomForestClassifier(**best_model_params) 165 | 166 | best_model.fit(train_x, train_y) 167 | 168 | score = best_model.score(test_x, test_y) 169 | print(f'score no_top {score}') 170 | print(f'best model parameters no_top {best_model_params}') 171 | 172 | print("START VALIDATING PARAMS") 173 | topo_cv = self._validate_k_fold_top(best_model, train_x, train_y, val_x, val_y) 174 | best_topo = best_combination(topo_cv) 175 | best_topo.pop("score") 176 | best_topo_pipeline_list = [('extract_subspaces', SubSpaceExtraction(**best_topo)), 177 | ('compute_diagrams', VietorisRipsPersistence(n_jobs=-1))] 178 | best_topo_pipeline = Pipeline(best_topo_pipeline_list) 179 | 180 | train_x_for_test = np.concatenate([train_x, val_x], axis=0) 181 | train_y_for_test = np.concatenate([train_y, val_y], axis=0) 182 | 183 | diagrams_train, _ = best_topo_pipeline.fit_transform_resample(train_x_for_test, train_y_for_test) 184 | 185 | print("EXTRACTING TOPOLOGICAL FEATURES TRAIN") 186 | top_features_train = extract_topological_features(diagrams_train) 187 | 188 | x_train_model = np.concatenate([train_x_for_test, top_features_train], axis=1) 189 | best_model.fit(x_train_model, train_y_for_test) 190 | 191 | print("EXTRACTING TOPOLOGICAL FEATURES TEST") 192 | x_test_model = extract_features_for_prediction(x_train_model, train_y_for_test, 193 | test_x, test_y, best_topo_pipeline) 194 | 195 | score_top = best_model.score(x_test_model, test_y) 196 | 197 | val_x_with_topo = extract_features_for_prediction(train_x, train_y, val_x, val_y, best_topo_pipeline) 198 | 199 | print('START VALIDATING MODEL WITH OPTIMAL TOPOLOGY') 200 | model_config_with_topo = self._validate_k_fold_model(x_train_model, train_y, val_x_with_topo, val_y) 201 | best_model_config_with_topo = best_combination(model_config_with_topo) 202 | best_model_config_with_topo.pop('score') 203 | 204 | best_model_with_topo = RandomForestClassifier(**best_model_config_with_topo) 205 | best_model_with_topo.fit(x_train_model, train_y_for_test) 206 | 207 | score_best_topo_and_model = best_model_with_topo.score(x_test_model, test_y) 208 | print(f'score best model and topo_feat {score_best_topo_and_model}') 209 | 210 | return best_model_params, best_topo, best_model_config_with_topo, score, score_top, score_best_topo_and_model 211 | 212 | 213 | if __name__ == "__main__": 214 | COLUMNS_TO_KEEP = ["date", "home_team_goal", "away_team_goal", 215 | "home_best_attack", "home_best_defense", "home_avg_attack", "home_avg_defense", 216 | "home_std_attack", "home_std_defense", "gk_home_player_1", 217 | "away_avg_attack", "away_avg_defense", "away_std_attack", "away_std_defense", 218 | "away_best_attack", "away_best_defense", "gk_away_player_1" 219 | ] 220 | 221 | train_split_date = pd.Timestamp("2013-08-01") 222 | val_split_date = pd.Timestamp("2014-08-01") 223 | end_date = pd.Timestamp("2015-08-01") 224 | 225 | k_mins = [25, 50, 75] 226 | k_maxs = [75, 125, 175] 227 | distances = [0.05, 0.10] 228 | model_params = {"n_estimators": [1000], "max_depth": [None, 10, 20], 'random_state': [52], 229 | "max_features": [None, 'sqrt', 'log2', 1/3, 1/2]} 230 | 231 | df = get_dataset(42197).get_data(dataset_format='dataframe')[0] 232 | df = df[COLUMNS_TO_KEEP] 233 | y = compute_match_result(df) 234 | df.pop('home_team_goal') 235 | df.pop('away_team_goal') 236 | 237 | cv = CrossValidation(k_mins=k_mins, k_maxs=k_maxs, dist_percentages=distances, **model_params) 238 | cv_output = cv.cross_validate(df, y, (train_split_date, val_split_date, end_date)) 239 | print(cv_output) 240 | write_pickle("cv_output.pickle", cv_output) 241 | -------------------------------------------------------------------------------- /database.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import pandas as pd 3 | import numpy as np 4 | import os 5 | 6 | from compute_statistics import * 7 | from openml.datasets import get_dataset 8 | 9 | import wget 10 | 11 | url = 'https://storage.googleapis.com/l2f-open-models/football_tda/database.sqlite' 12 | if not os.path.isfile('database.sqlite'): 13 | filename = wget.download(url) 14 | else: 15 | filename = 'database.sqlite' 16 | 17 | class Database: 18 | pl_players = 0 19 | pl_matches = 0 20 | pl_team = 0 21 | conn = 0 22 | season = "2014/2015" 23 | date_time_str = "2014-08-01 00:00:00" 24 | rank = 0 25 | league = 0 26 | all_players_stats_id = 42194 27 | all_players_name_id = 42199 28 | 29 | def __init__(self): 30 | """ prepare all table """ 31 | self.conn = sqlite3.connect(filename) 32 | self.pl_players = get_dataset(self.all_players_name_id).get_data(dataset_format='dataframe')[0] 33 | self.pl_players_attributes = get_dataset(self.all_players_stats_id).get_data(dataset_format='dataframe')[0] 34 | self.pl_players_attributes["date"] = pd.to_datetime(self.pl_players_attributes["date"]) 35 | self.pl_players_attributes_small = self.pl_players_attributes[ 36 | self.pl_players_attributes['date'] > self.date_time_str].groupby(['player_fifa_api_id']).agg( 37 | {'overall_rating': ['mean']}) 38 | 39 | def calculate_ranking(self): 40 | self.home = pd.read_sql("SELECT home_team_api_id, SUM(" 41 | " CASE " 42 | " WHEN home_team_goal > away_team_goal " 43 | " THEN 3" 44 | " WHEN home_team_goal = away_team_goal " 45 | " THEN 1 " 46 | " ELSE 0 END ) " 47 | " AS home_points " 48 | " FROM Match " 49 | " WHERE league_id " 50 | " IN ( SELECT id " 51 | " FROM League " 52 | " WHERE name = ? ) " 53 | " AND season = ? " 54 | " GROUP BY home_team_api_id ", 55 | self.conn, 56 | params=(self.league, self.season)).dropna() 57 | self.away = pd.read_sql("SELECT away_team_api_id, SUM(" 58 | " CASE " 59 | " WHEN home_team_goal < away_team_goal " 60 | " THEN 3" 61 | " WHEN home_team_goal = away_team_goal " 62 | " THEN 1 " 63 | " ELSE 0 END ) " 64 | " AS away_points " 65 | " FROM Match " 66 | " WHERE league_id " 67 | " IN ( SELECT id " 68 | " FROM League " 69 | " WHERE name = ? ) " 70 | " AND season = ? " 71 | " GROUP BY away_team_api_id ", 72 | self.conn, 73 | params=(self.league, self.season)).dropna() 74 | self.rank = self.away.set_index('away_team_api_id').join(self.home.set_index('home_team_api_id')) 75 | self.rank['total_point'] = self.rank['away_points'] + self.rank['home_points'] 76 | 77 | self.pl_team = pd.read_sql("SELECT DISTINCT M.away_team_api_id , TA.team_long_name, TA.team_short_name " 78 | "FROM Match AS M " 79 | "JOIN Team AS TA " 80 | "ON(M.away_team_api_id = TA.team_api_id) " 81 | "WHERE league_id " 82 | "IN( SELECT id " 83 | "FROM League " 84 | "WHERE name = ?) " 85 | "AND season = ? ", 86 | self.conn, params=(self.league, self.season)).dropna() 87 | 88 | self.pl_team = self.pl_team.set_index("away_team_api_id").join(self.rank['total_point']).sort_values( 89 | ['total_point'], ascending=False) 90 | 91 | def find_player_id_by_name(self, name): 92 | """ search the player in table and return the id""" 93 | 94 | for item in self.pl_players[['player_api_id', 'player_name', 'player_fifa_api_id']].values: 95 | if " " in str(item[1]): 96 | first_name, last_name = str(item[1]).split(" ", 1) 97 | if " " in name: 98 | f_name, l_name = str(name).split(" ", 1) 99 | 100 | if str.lower(last_name) == str.lower(l_name) and str.lower(first_name) == str.lower(f_name): 101 | return item[0] 102 | else: 103 | 104 | if str.lower(last_name) == str.lower(name): 105 | return item[0] 106 | 107 | 108 | else: 109 | 110 | if str.lower(item[1]) == str.lower(name): 111 | return item[0] 112 | 113 | return -1 114 | 115 | def switch_to_players_by_id(self, f_id, s_id): 116 | """ switch the two id player_api_id in the principal player and in the attribute player table in order to invert 117 | the match played by the two players""" 118 | 119 | i = 0 120 | 121 | for item in self.pl_players['player_api_id']: 122 | if item == f_id: 123 | # print(self.pl_players.at[i, 'player_api_id']) 124 | self.pl_players.at[i, 'player_api_id'] = s_id 125 | # print(self.pl_players.at[i, 'player_api_id']) 126 | if item == s_id: 127 | # print(self.pl_players.at[i, 'player_api_id']) 128 | self.pl_players.at[i, 'player_api_id'] = f_id 129 | # print(self.pl_players.at[i, 'player_api_id']) 130 | 131 | i = i + 1 132 | 133 | i = 0 134 | 135 | for item in self.pl_players_attributes['player_api_id']: 136 | if item == f_id: 137 | # print(self.pl_players.at[i, 'player_api_id']) 138 | self.pl_players_attributes.at[i, 'player_api_id'] = s_id 139 | # print(self.pl_players.at[i, 'player_api_id']) 140 | if item == s_id: 141 | # print(self.pl_players.at[i, 'player_api_id']) 142 | self.pl_players_attributes.at[i, 'player_api_id'] = f_id 143 | # print(self.pl_players.at[i, 'player_api_id']) 144 | 145 | i = i + 1 146 | 147 | self.pl_players.to_parquet('pl_players2.parquet') 148 | 149 | def switch_players_by_name(self, f_name, s_name): 150 | """ mask function that call Find player by id two times and then switch player by id""" 151 | 152 | f_id = self.find_player_id_by_name(f_name) 153 | s_id = self.find_player_id_by_name(s_name) 154 | 155 | self.switch_to_players_by_id(f_id, s_id) 156 | 157 | def select_player_from_team(self, team_name): 158 | """ Function that allow to select by terminal the player from a team. It computes the appearance of each player 159 | in the team it offers a testual interface""" 160 | 161 | team_id = pd.read_sql('SELECT team_api_id FROM Team WHERE team_long_name = ?', self.conn, 162 | params={team_name}) 163 | 164 | player_for_team_home = pd.read_sql('SELECT home_player_2, home_player_3, ' 165 | 'home_player_4, home_player_5, ' 166 | 'home_player_6, home_player_7, home_player_8, ' 167 | 'home_player_9, home_player_10, home_player_11 ' 168 | 'FROM Match WHERE home_team_api_id = ? AND season = ?', 169 | self.conn, 170 | params=(str(team_id['team_api_id'][0]), self.season)).dropna() 171 | 172 | player_for_team_away = pd.read_sql('SELECT away_player_2, away_player_3, ' 173 | 'away_player_4, away_player_5, ' 174 | 'away_player_6, away_player_7, away_player_8, ' 175 | 'away_player_9, away_player_10, away_player_11 ' 176 | 'FROM Match WHERE away_team_api_id = ? AND season = ?', 177 | self.conn, 178 | params=(str(team_id['team_api_id'][0]), self.season)).dropna() 179 | 180 | unique_away, counts_away = np.unique(player_for_team_away, return_counts=True) 181 | unique_home, counts_home = np.unique(player_for_team_home, return_counts=True) 182 | 183 | unique_home = np.array(unique_home).astype(np.int64) 184 | unique_away = np.array(unique_away).astype(np.int64) 185 | 186 | dataframe_home_appearance = pd.DataFrame({'appearance': counts_home}, index=unique_home) 187 | dataframe_away_appearance = pd.DataFrame({'appearance': counts_away}, index=unique_away) 188 | 189 | for item in unique_away: 190 | 191 | if item in dataframe_home_appearance['appearance']: 192 | 193 | dataframe_home_appearance.at[item, 'appearance'] = dataframe_home_appearance.at[item, 'appearance'] + \ 194 | dataframe_away_appearance.at[ 195 | item, 'appearance'] 196 | 197 | else: 198 | 199 | dataframe_home_appearance.loc[item] = dataframe_away_appearance.at[item, 'appearance'] 200 | 201 | players = dataframe_home_appearance.join(self.pl_players.set_index('player_api_id')).set_index( 202 | 'player_fifa_api_id').join(self.pl_players_attributes_small).sort_values(by=['appearance'], ascending=False) 203 | 204 | print(players[['player_name', 'appearance', ('overall_rating', 'mean')]].to_string(index=False)) 205 | 206 | def hire_player(self): 207 | league_input = str.lower(input('Choose one league between "serie a" and "Premier League".\n')) 208 | 209 | flag = True 210 | while flag: 211 | if league_input == "serie a" or league_input == 'italy serie a': 212 | self.league = 'Italy Serie A' 213 | self.season = "2015/2016" 214 | self.date_time_str = '2015-08-01 00:00:00' 215 | flag = False 216 | elif league_input == 'premier league' or league_input == 'england premier league': 217 | self.league = 'England Premier League' 218 | flag = False 219 | self.season = "2014/2015" 220 | self.date_time_str = '2014-08-01 00:00:00' 221 | else: 222 | print('Warning: we don\' have ', league_input, ' please choose between serie a and premier league\n') 223 | league_input = str.lower(input( 224 | 'Choose one league between serie a and Premier League. \n')) 225 | 226 | self.calculate_ranking() 227 | print(self.pl_team.to_string(index=False)) 228 | first_player = input('Which player do you want to insert? Please insert the name and surname \n') 229 | team = input('Which team? Please, mind to insert the full name \n ') 230 | self.select_player_from_team(team) 231 | second_player = input('Which player? Please insert the name and surname \n') 232 | # self.switch_players_by_name('Messi', second_player) 233 | # print('The players have been moved\n\n') 234 | # self.select_player_from_team(team) 235 | first_player_id = self.find_player_id_by_name(first_player) 236 | second_player_id = self.find_player_id_by_name(second_player) 237 | return replace_player_with_chosen_one(self.league, second_player_id, hired_player_id=first_player_id) 238 | -------------------------------------------------------------------------------- /FootballTDA.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# The shape of football games" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## The dataset" 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "metadata": {}, 20 | "source": [ 21 | "The original data can be found [here](https://www.kaggle.com/hugomathien/soccer). It contains briefly:" 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "## Tables" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "* Team: it contains three id keys to relate to other tables, and the long and short name of the team.\n", 36 | "* Team Attributes: historical players attributes updates for each team (not used in our model).\n", 37 | "* Player: general player information like `name`, `birthday`, `weight` and `height`.\n", 38 | "* Player_Attributes: historical players attributes updates. This table is linked to the `Player` table by `player_fifa_api_id`\n", 39 | "* Match: it is the most important table, where each row describes a match using `date`, `season`, `league`, the id of the two participant teams, the id of the starting 22 players and their position in the field. \n", 40 | "* League and Country: it contains the name of the league and its home country." 41 | ] 42 | }, 43 | { 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | " " 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": null, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "%load_ext autoreload\n", 57 | "%autoreload 2" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": null, 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "from database import Database \n", 67 | "from cross_validation import extract_features_for_prediction\n", 68 | "import pandas as pd\n", 69 | "import numpy as np\n", 70 | "from numpy import random\n", 71 | "import soccer_basics \n", 72 | "from random import expovariate, gauss\n", 73 | "from sklearn.ensemble import RandomForestClassifier\n", 74 | "from utils import read_pickle\n", 75 | "from notebook_functions import *" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [ 82 | "## Load the tables" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": {}, 88 | "source": [ 89 | "The class `database` is set to manage the tables in order to modify the teams. " 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "database = Database()" 99 | ] 100 | }, 101 | { 102 | "cell_type": "markdown", 103 | "metadata": {}, 104 | "source": [ 105 | "## Modify teams" 106 | ] 107 | }, 108 | { 109 | "cell_type": "markdown", 110 | "metadata": {}, 111 | "source": [ 112 | "The method `hire_player` is used to move your favorite player to a selected team to simulate how the championship would go. You just need to select the team where you want put the player and then select the player to be replaced. The list of teams is sorted by the total of points that each team has totaled during the championship. Players are sorted by the number of appearances they had that year. \n", 113 | "Let's see how things would have gone.\n", 114 | "\n", 115 | "**Note**: the higher the number of appearances of the player to be replaced, the greater the impact of the hired player!" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": { 122 | "scrolled": true 123 | }, 124 | "outputs": [], 125 | "source": [ 126 | "new_player_df = database.hire_player()" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": null, 132 | "metadata": { 133 | "scrolled": false 134 | }, 135 | "outputs": [], 136 | "source": [ 137 | "new_player_df.head()" 138 | ] 139 | }, 140 | { 141 | "cell_type": "markdown", 142 | "metadata": {}, 143 | "source": [ 144 | "Get the team ids, which are going to be used later " 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "metadata": {}, 151 | "outputs": [], 152 | "source": [ 153 | "team_ids = get_team_ids(new_player_df)" 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "metadata": {}, 159 | "source": [ 160 | "We want to make sure that the columns order is the same as in the training set." 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "new_players_df_stats = get_useful_cols(new_player_df)" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": null, 175 | "metadata": {}, 176 | "outputs": [], 177 | "source": [ 178 | "new_players_df_stats.head()" 179 | ] 180 | }, 181 | { 182 | "cell_type": "markdown", 183 | "metadata": {}, 184 | "source": [ 185 | "## Feature selection" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "In order to decide which attributes belong to which group, we created a correlation matrix. From this, we saw that there were two big groups, where player attributes were strongly correlated with each other. Therefore, we decided to split the attributes into two groups, one to summarise the attacking characteristics of a player while the other one the defensive ones.\n", 193 | "Finally, since the goalkeeper has completely different statistics with respect to the other players, we decided to take into account only the overall rating.\n", 194 | "Below, is possible to see the features used for each player:\n", 195 | "* **Attack**: \"positioning\", \"crossing\", \"finishing\", \"heading_accuracy\", \"short_passing\", \"reactions\", \"volleys\", \"dribbling\", \"curve\", \"free_kick_accuracy\", \"acceleration\", \"sprint_speed\", \"agility\", \"penalties\", \"vision\", \"shot_power\", \"long_shots\"\n", 196 | "* **Defense**: \"interceptions\", \"aggression\", \"marking\", \"standing_tackle\", \"sliding_tackle\", \"long_passing\"\n", 197 | "* **Goalkeeper**: \"overall_rating\"\n", 198 | "\n", 199 | "From this set of features, the next step we did was to, for each non-goalkeeper player, compute the mean of the attack attributes and the defensive ones.\n", 200 | "\n", 201 | "Finally, for each team in a given match, we compute the mean and the standard deviation for the attack and the defense from these stats of the team's players, as well as the best attack and best defense. \n" 202 | ] 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "metadata": {}, 207 | "source": [ 208 | "In this way a match is described by 14 features (GK overall value, best attack, std attack, mean attack, best defense, std defense, mean defense), that mapped the match in the space, following the characterizes of the two team." 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": {}, 214 | "source": [ 215 | "## Feature extraction" 216 | ] 217 | }, 218 | { 219 | "cell_type": "markdown", 220 | "metadata": {}, 221 | "source": [ 222 | "The aim of TDA is to catch the structure of the space underlying the data. In our project we assume that the neigborood of a data point hides meaningfull information which are correlated with the outcome of the match. Thus, we explored the data space looking for this kind of correlation." 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": null, 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "best_pipeline_params, best_model_feat_params = get_best_params()" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": null, 237 | "metadata": {}, 238 | "outputs": [], 239 | "source": [ 240 | "pipeline = get_pipeline(best_pipeline_params)" 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": null, 246 | "metadata": {}, 247 | "outputs": [], 248 | "source": [ 249 | "x_train, y_train = load_dataset()" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": { 256 | "scrolled": false 257 | }, 258 | "outputs": [], 259 | "source": [ 260 | "x_test = extract_x_test_features(x_train, y_train, new_players_df_stats, pipeline)" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": null, 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [ 269 | "rf_model = RandomForestClassifier(**best_model_feat_params)" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": null, 275 | "metadata": { 276 | "scrolled": false 277 | }, 278 | "outputs": [], 279 | "source": [ 280 | "rf_model.fit(x_train, y_train)" 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": null, 286 | "metadata": {}, 287 | "outputs": [], 288 | "source": [ 289 | "matches_probabilities = get_probabilities(rf_model, x_test, team_ids)" 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "execution_count": null, 295 | "metadata": { 296 | "scrolled": true 297 | }, 298 | "outputs": [], 299 | "source": [ 300 | "matches_probabilities.head()" 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": null, 306 | "metadata": {}, 307 | "outputs": [], 308 | "source": [ 309 | "compute_final_standings(matches_probabilities, 'premier league')" 310 | ] 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "metadata": {}, 315 | "source": [ 316 | "## Messi in each team\n", 317 | "Below, is possible to see the effect that Messi would have had on the final standings of the Premier League 2014/2015. The results are obtained by running 20 different simulations, eahc one with the player with the most number of appereances replaced by Messi." 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "teams_with_messi.set_index(np.arange(1, 21), drop=True)" 327 | ] 328 | }, 329 | { 330 | "cell_type": "markdown", 331 | "metadata": {}, 332 | "source": [ 333 | "# Benchmarks: Market's odds and Elo ratings" 334 | ] 335 | }, 336 | { 337 | "cell_type": "markdown", 338 | "metadata": {}, 339 | "source": [ 340 | "While the performance is not our main goal, we nevertheless set up two simple benchmarks to make sure our (topological) model is a reasonable approximation of the reality.\n", 341 | "\n", 342 | "The task we choose is simply the ternary match outcome prediction: will the home team win, the away team or will there be a draw?\n", 343 | "\n", 344 | "The first benchmark is obtained from Market's probabilities for the three outcomes -- they are obtained by simply inverting the odds (see soccer_basics.py for details).\n", 345 | "\n", 346 | "The second benchmark is by using instead Elo ratings, a standard tool for assessing teams' or players' strenghts: Elo rating system. For the related World Football Elo Ratings see: . For a deeper mathematical discussion around this concept, see National teams Elo rating, Elo's rating mathematics\n", 347 | "\n", 348 | "We calculate the benchmarks on the Premier League dataset.\n", 349 | "\n", 350 | "Our model is capable an accuracy of 0.531, which is comparable with market's performace. " 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "probabilities_with_odds = get_dataset(42198).get_data(dataset_format='dataframe')[0]" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": null, 365 | "metadata": { 366 | "scrolled": true 367 | }, 368 | "outputs": [], 369 | "source": [ 370 | "probabilities_with_odds.head()" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": null, 376 | "metadata": {}, 377 | "outputs": [], 378 | "source": [ 379 | "soccer_basics.useful_updates1(probabilities_with_odds)\n", 380 | "soccer_basics.get_elo(probabilities_with_odds, 20, 100)\n", 381 | "soccer_basics.useful_updates2(probabilities_with_odds, 100)" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "market's ternary prediction: 1, X or 2\n", 389 | "\n" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "metadata": {}, 396 | "outputs": [], 397 | "source": [ 398 | "print('market prediction, all data and 2014-2015 season')\n", 399 | "acc1 = len(probabilities_with_odds[probabilities_with_odds['result'] == \n", 400 | " probabilities_with_odds['market_prediction']]) / float(len(probabilities_with_odds))\n", 401 | "df = probabilities_with_odds.reset_index()\n", 402 | "\n", 403 | "print(np.round(acc1, 3))" 404 | ] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "metadata": {}, 409 | "source": [ 410 | "Elo based ternary prediction:\n", 411 | "\n" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": null, 417 | "metadata": {}, 418 | "outputs": [], 419 | "source": [ 420 | "print('Elo based prediction, all data and 2015, with 30 matches quarantine')\n", 421 | "soccer_basics.ternary_prediction(probabilities_with_odds, 30)" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": null, 427 | "metadata": {}, 428 | "outputs": [], 429 | "source": [] 430 | } 431 | ], 432 | "metadata": { 433 | "kernelspec": { 434 | "display_name": "Python 3", 435 | "language": "python", 436 | "name": "python3" 437 | }, 438 | "language_info": { 439 | "codemirror_mode": { 440 | "name": "ipython", 441 | "version": 3 442 | }, 443 | "file_extension": ".py", 444 | "mimetype": "text/x-python", 445 | "name": "python", 446 | "nbconvert_exporter": "python", 447 | "pygments_lexer": "ipython3", 448 | "version": "3.7.6" 449 | } 450 | }, 451 | "nbformat": 4, 452 | "nbformat_minor": 1 453 | } 454 | -------------------------------------------------------------------------------- /compute_statistics.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | from openml.datasets import get_dataset 4 | 5 | home_best_attack_col = "home_best_attack" 6 | home_best_defense_col = "home_best_defense" 7 | away_best_attack_col = "away_best_attack" 8 | away_best_defense_col = "away_best_defense" 9 | 10 | home_avg_attack_col = "home_avg_attack" 11 | home_avg_defense_col = "home_avg_defense" 12 | away_avg_attack_col = "away_avg_attack" 13 | away_avg_defense_col = "away_avg_defense" 14 | 15 | home_std_attack_col = "home_std_attack" 16 | home_std_defense_col = "home_std_defense" 17 | away_std_attack_col = "away_std_attack" 18 | away_std_defense_col = "away_std_defense" 19 | 20 | home_players_base_str = "home_player_{number}" 21 | away_players_base_str = "away_player_{number}" 22 | 23 | premier_league_matches_id = 42195 24 | serie_a_matches_id = 42196 25 | all_players_stats_id = 42194 26 | 27 | 28 | GK_COLUMNS = ["overall_rating"] 29 | 30 | ATTACK_COLUMNS = ["positioning", "crossing", "finishing", "heading_accuracy", "short_passing", 31 | "reactions", "volleys", "dribbling", "curve", "free_kick_accuracy", "acceleration", "sprint_speed", 32 | "agility", "penalties", "vision", "shot_power", "long_shots"] 33 | 34 | DEFENSE_COLUMNS = ["interceptions", "aggression", "marking", "standing_tackle", "sliding_tackle", "long_passing"] 35 | 36 | COLS_TO_KEEP = ['date', "home_team_api_id", "away_team_api_id", 37 | 'gk_home_player_1', 'gk_away_player_1', 'home_avg_attack', 'home_avg_defense', 38 | 'home_std_attack', 'home_std_defense', 'home_best_attack', 'home_best_defense', 39 | 'away_avg_attack', 'away_avg_defense', 'away_std_attack', 'away_std_defense', 40 | 'away_best_attack', 'away_best_defense'] 41 | 42 | gk_column = "gk" 43 | attack_column = "attack" 44 | defense_column = "defense" 45 | 46 | match_columns = ["id", "country_id", "league_id", "season", "stage", "date", "match_api_id", "home_team_api_id", 47 | "away_team_api_id", "home_team_goal", "away_team_goal", "home_player_X1", "home_player_X2", 48 | "home_player_X3", 49 | "home_player_X4", "home_player_X5", "home_player_X6", "home_player_X7", "home_player_X8", 50 | "home_player_X9", 51 | "home_player_X10", "home_player_X11", "away_player_X1", "away_player_X2", "away_player_X3", 52 | "away_player_X4", 53 | "away_player_X5", "away_player_X6", "away_player_X7", "away_player_X8", "away_player_X9", 54 | "away_player_X10", 55 | "away_player_X11", "home_player_Y1", "home_player_Y2", "home_player_Y3", "home_player_Y4", 56 | "home_player_Y5", 57 | "home_player_Y6", "home_player_Y7", "home_player_Y8", "home_player_Y9", "home_player_Y10", 58 | "home_player_Y11", 59 | "away_player_Y1", "away_player_Y2", "away_player_Y3", "away_player_Y4", "away_player_Y5", 60 | "away_player_Y6", 61 | "away_player_Y7", "away_player_Y8", "away_player_Y9", "away_player_Y10", "away_player_Y11", 62 | "home_player_1", 63 | "home_player_2", "home_player_3", "home_player_4", "home_player_5", "home_player_6", "home_player_7", 64 | "home_player_8", 65 | "home_player_9", "home_player_10", "home_player_11", "away_player_1", "away_player_2", "away_player_3", 66 | "away_player_4", 67 | "away_player_5", "away_player_6", "away_player_7", "away_player_8", "away_player_9", "away_player_10", 68 | "away_player_11", 69 | "goal", "shoton", "shotoff", "foulcommit", "card", "cross", "corner", "possession", "B365H", "B365D", 70 | "B365A" 71 | ] 72 | 73 | COLS_TO_DROP = ["shoton", "shotoff", "foulcommit", "card", "cross", "corner", "home_player_X1", "home_player_X2", 74 | "home_player_X3", "home_player_X4", "home_player_X5", "home_player_X6", "home_player_X7", 75 | "home_player_X8", 76 | "home_player_X9", "home_player_X10", "home_player_X11", "away_player_X1", "away_player_X2", 77 | "away_player_X3", 78 | "away_player_X4", "away_player_X5", "away_player_X6", "away_player_X7", "away_player_X8", 79 | "away_player_X9", 80 | "away_player_X10", "away_player_X11", "home_player_Y1", "home_player_Y2", "home_player_Y3", 81 | "home_player_Y4", 82 | "home_player_Y5", "home_player_Y6", "home_player_Y7", "home_player_Y8", "home_player_Y9", 83 | "home_player_Y10", 84 | "home_player_Y11", "away_player_Y1", "away_player_Y2", "away_player_Y3", "away_player_Y4", 85 | "away_player_Y5", 86 | "away_player_Y6", "away_player_Y7", "away_player_Y8", "away_player_Y9", "away_player_Y10", 87 | "away_player_Y11" 88 | ] 89 | 90 | 91 | def _aggregate_player_attributes(player_df, columns): 92 | """Compute the mean for all the players for the given columns 93 | 94 | Parameters 95 | ---------- 96 | player_df: pd.DataFrame 97 | The DataFrame containing the statistics of all the players 98 | columns: list 99 | The columns on which to calculate the mean 100 | 101 | Returns 102 | ------- 103 | player_df_with_stats: pd.DataFrame 104 | The original DataFrame with also the aggregate stats 105 | """ 106 | return player_df[columns].mean(axis=1, skipna=True) 107 | 108 | 109 | def add_aggregate_player_stats(player_df): 110 | """For all the players, compute the mean of the attack columns, the defensive columns and the gk columns 111 | 112 | Parameters 113 | ---------- 114 | player_df: pd.DataFrame 115 | The DataFrame containing the statistics of all the players 116 | 117 | Returns 118 | ------- 119 | player_df_with_stats: pd.DataFrame 120 | The original DataFrame with also the aggregate stats 121 | 122 | """ 123 | player_df[attack_column] = _aggregate_player_attributes(player_df, ATTACK_COLUMNS) 124 | player_df[defense_column] = _aggregate_player_attributes(player_df, DEFENSE_COLUMNS) 125 | player_df[gk_column] = _aggregate_player_attributes(player_df, GK_COLUMNS) 126 | return player_df 127 | 128 | 129 | def retrieve_latest_stats_by_player(player_df, player_id, str_date): 130 | """Retrieve the latest statistics for a given player, based on a target date 131 | 132 | Parameters 133 | ---------- 134 | player_df: pd.DataFrame 135 | The DataFrame containing the statistics of all the players 136 | player_id: int 137 | The id of the target player 138 | str_date: str 139 | The target date 140 | 141 | Returns 142 | ------- 143 | latest_stats: pd.DataFrame 144 | The DataFrame containing the latest stats with respect to the str_date 145 | """ 146 | date = pd.Timestamp(str_date) 147 | player_id_df = player_df[player_df.player_api_id == player_id] 148 | player_id_df.loc[:, "date"] = pd.to_datetime(player_id_df.loc[:, "date"]) 149 | sorted_df = player_id_df.sort_values(by=['date'], ascending=False) 150 | all_stats_before_date = sorted_df[sorted_df.date < date].dropna(axis=0) 151 | return all_stats_before_date.iloc[0, :] 152 | 153 | 154 | def compute_stats(match, base_player_column, stat_name): 155 | """For all the players of one of the two teams (goalkeeper excluded), compute the average, std and best of the 156 | stat_name statistics (either attack or defense) 157 | 158 | Parameters 159 | ---------- 160 | match: pd.Series 161 | A series containing the match 162 | base_player_column: str 163 | The base format of the column (in our dataset, either 'home_player_{number}' or 'away_player_{number}') 164 | stat_name: str 165 | The name of the statistic for which compute the avg, std and best (in our case, either 'attack' or 'defense' 166 | 167 | Returns 168 | ------- 169 | stats: tuple 170 | A tuple containing the average, the std and the best of the chosen statistic 171 | """ 172 | player_stats = [] 173 | for player_number in range(2, 12): 174 | base_player_col = base_player_column.format(number=player_number) 175 | stat_player_col = stat_name + "_" + base_player_col 176 | player_stats.append(match[stat_player_col]) 177 | 178 | avg = np.nanmean(player_stats) 179 | std = 100 - (np.nanstd(player_stats) / np.nanmean(player_stats)) * 100 180 | best = np.nanmax(player_stats) 181 | 182 | return avg, std, best 183 | 184 | 185 | def _aggregate_stats_per_match(match): 186 | """For a single match, compute the aggregate statistics of both teams and add the corresponding columns 187 | 188 | Parameters 189 | ---------- 190 | match: pd.Series 191 | A single match 192 | 193 | Returns 194 | ------- 195 | match_with_attributes: pd.Series 196 | The match containing the aggregate statistics 197 | """ 198 | avg_home_attack, std_home_attack, best_home_attack = compute_stats(match, home_players_base_str, "attack") 199 | avg_home_defense, std_home_defense, best_home_defense = compute_stats(match, home_players_base_str, "defense") 200 | avg_away_attack, std_away_attack, best_away_attack = compute_stats(match, away_players_base_str, "attack") 201 | avg_away_defense, std_away_defense, best_away_defense = compute_stats(match, away_players_base_str, "defense") 202 | 203 | match[home_avg_attack_col] = avg_home_attack 204 | match[home_avg_defense_col] = avg_home_defense 205 | match[away_avg_attack_col] = avg_away_attack 206 | match[away_avg_defense_col] = avg_away_defense 207 | 208 | match[home_std_attack_col] = std_home_attack 209 | match[home_std_defense_col] = std_home_defense 210 | match[away_std_attack_col] = std_away_attack 211 | match[away_std_defense_col] = std_away_defense 212 | 213 | match[home_best_attack_col] = best_home_attack 214 | match[home_best_defense_col] = best_home_defense 215 | match[away_best_attack_col] = best_away_attack 216 | match[away_best_defense_col] = best_away_defense 217 | 218 | return match 219 | 220 | 221 | def compute_aggregate_stats_per_team(df_matches): 222 | """For all the matches, compute the aggregate statistics of all the teams and add the corresponding columns 223 | 224 | Parameters 225 | ---------- 226 | df_matches: pd.DataFrame 227 | The DataFrame containing all the matches 228 | 229 | Returns 230 | ------- 231 | df_matches_with_stats: pd.DataFrame 232 | The matches containing the aggregate statistics 233 | """ 234 | matches_with_stats = [] 235 | 236 | for index, match in df_matches.iterrows(): 237 | matches_with_stats.append(_aggregate_stats_per_match(match)) 238 | 239 | return pd.DataFrame(matches_with_stats) 240 | 241 | 242 | def _insert_players_team(match, base_player_column, df_players): 243 | for player_number in range(1, 12): 244 | player_col = base_player_column.format(number=player_number) 245 | player_id = match[player_col] 246 | match_date = match['date'] 247 | try: 248 | latest_player_stats = retrieve_latest_stats_by_player(df_players, player_id, match_date) 249 | gk_value = latest_player_stats[gk_column] 250 | attack_value = latest_player_stats[attack_column] 251 | defense_value = latest_player_stats[defense_column] 252 | except IndexError: 253 | gk_value = np.nan 254 | attack_value = np.nan 255 | defense_value = np.nan 256 | 257 | if player_number == 1: 258 | new_gk_column = gk_column + "_" + player_col 259 | match[new_gk_column] = gk_value 260 | else: 261 | new_attack_column = attack_column + "_" + player_col 262 | match[new_attack_column] = attack_value 263 | new_defense_column = defense_column + "_" + player_col 264 | match[new_defense_column] = defense_value 265 | return match 266 | 267 | 268 | def _insert_player_stats(df_matches, df_players): 269 | matches_with_stats = [] 270 | 271 | for index, match in df_matches.iterrows(): 272 | match_with_home_stats = _insert_players_team(match, home_players_base_str, df_players) 273 | match_full_stats = _insert_players_team(match_with_home_stats, away_players_base_str, df_players) 274 | matches_with_stats.append(match_full_stats) 275 | 276 | return pd.DataFrame(matches_with_stats) 277 | 278 | 279 | def _load_matches(league): 280 | """Load the DataFrame according to the league 281 | 282 | Parameters 283 | ---------- 284 | league: str 285 | The name of the league 286 | 287 | Returns 288 | ------- 289 | matches_df: pd.DataFrame 290 | The requested matches 291 | """ 292 | if league == "England Premier League": 293 | target_id = premier_league_matches_id 294 | else: 295 | target_id = serie_a_matches_id 296 | 297 | matches_df = get_dataset(target_id).get_data(dataset_format='dataframe')[0] 298 | matches_df["date"] = pd.to_datetime(matches_df["date"]) 299 | return matches_df 300 | 301 | 302 | def _load_players(): 303 | """Load the DataFrame containing the players' attributes 304 | 305 | Returns 306 | ------- 307 | players_df: pd.DataFrame 308 | The DataFrame containing the players 309 | """ 310 | players_df = get_dataset(all_players_stats_id).get_data(dataset_format='dataframe')[0] 311 | players_df["date"] = pd.to_datetime(players_df["date"]) 312 | return players_df 313 | 314 | 315 | def replace_player_with_chosen_one(league, replaced_player_id, hired_player_id=30981): 316 | """Replace the player with id 'replaced_player_id' with the id of the chosen champion for all the matches 317 | 318 | Parameters 319 | ---------- 320 | league: str 321 | The string corresponding to the name of the league 322 | replaced_player_id: int 323 | The id of the player to be replaced 324 | hired_player_id: int 325 | The id of the chosen player 326 | 327 | Returns 328 | ------- 329 | df_matches_with_new_player: pd.DataFrame 330 | The matches with the new player 331 | """ 332 | 333 | df_matches = _load_matches(league) 334 | df_players = _load_players() 335 | 336 | df_players_with_stats = add_aggregate_player_stats(df_players) 337 | 338 | df_matches_with_new_player = df_matches.replace(replaced_player_id, hired_player_id) 339 | 340 | df_matches_stats_with_new_player = _insert_player_stats(df_matches_with_new_player, df_players_with_stats) 341 | 342 | df_matches_full_stats_with_new_player = compute_aggregate_stats_per_team(df_matches_stats_with_new_player) 343 | 344 | df_matches_useful_stats_with_new_player = df_matches_full_stats_with_new_player 345 | 346 | return df_matches_useful_stats_with_new_player 347 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 L2F SA. 2 | Licensed under the GNU Affero General Public License (the "License"); 3 | you may not use this file except in compliance with the License. 4 | You may obtain a copy of the License below or at https://www.gnu.org/licenses/agpl-3.0.html 5 | 6 | Unless required by applicable law or agreed to in writing, software 7 | distributed under the License is distributed on an "AS IS" BASIS, 8 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | See the License for the specific language governing permissions and 10 | limitations under the License. 11 | 12 | GNU AFFERO GENERAL PUBLIC LICENSE 13 | Version 3, 19 November 2007 14 | 15 | Copyright (C) 2007 Free Software Foundation, Inc. 16 | Everyone is permitted to copy and distribute verbatim copies 17 | of this license document, but changing it is not allowed. 18 | 19 | Preamble 20 | 21 | The GNU Affero General Public License is a free, copyleft license for 22 | software and other kinds of works, specifically designed to ensure 23 | cooperation with the community in the case of network server software. 24 | 25 | The licenses for most software and other practical works are designed 26 | to take away your freedom to share and change the works. By contrast, 27 | our General Public Licenses are intended to guarantee your freedom to 28 | share and change all versions of a program--to make sure it remains free 29 | software for all its users. 30 | 31 | When we speak of free software, we are referring to freedom, not 32 | price. Our General Public Licenses are designed to make sure that you 33 | have the freedom to distribute copies of free software (and charge for 34 | them if you wish), that you receive source code or can get it if you 35 | want it, that you can change the software or use pieces of it in new 36 | free programs, and that you know you can do these things. 37 | 38 | Developers that use our General Public Licenses protect your rights 39 | with two steps: (1) assert copyright on the software, and (2) offer 40 | you this License which gives you legal permission to copy, distribute 41 | and/or modify the software. 42 | 43 | A secondary benefit of defending all users' freedom is that 44 | improvements made in alternate versions of the program, if they 45 | receive widespread use, become available for other developers to 46 | incorporate. Many developers of free software are heartened and 47 | encouraged by the resulting cooperation. However, in the case of 48 | software used on network servers, this result may fail to come about. 49 | The GNU General Public License permits making a modified version and 50 | letting the public access it on a server without ever releasing its 51 | source code to the public. 52 | 53 | The GNU Affero General Public License is designed specifically to 54 | ensure that, in such cases, the modified source code becomes available 55 | to the community. It requires the operator of a network server to 56 | provide the source code of the modified version running there to the 57 | users of that server. Therefore, public use of a modified version, on 58 | a publicly accessible server, gives the public access to the source 59 | code of the modified version. 60 | 61 | An older license, called the Affero General Public License and 62 | published by Affero, was designed to accomplish similar goals. This is 63 | a different license, not a version of the Affero GPL, but Affero has 64 | released a new version of the Affero GPL which permits relicensing under 65 | this license. 66 | 67 | The precise terms and conditions for copying, distribution and 68 | modification follow. 69 | 70 | TERMS AND CONDITIONS 71 | 72 | 0. Definitions. 73 | 74 | "This License" refers to version 3 of the GNU Affero General Public License. 75 | 76 | "Copyright" also means copyright-like laws that apply to other kinds of 77 | works, such as semiconductor masks. 78 | 79 | "The Program" refers to any copyrightable work licensed under this 80 | License. Each licensee is addressed as "you". "Licensees" and 81 | "recipients" may be individuals or organizations. 82 | 83 | To "modify" a work means to copy from or adapt all or part of the work 84 | in a fashion requiring copyright permission, other than the making of an 85 | exact copy. The resulting work is called a "modified version" of the 86 | earlier work or a work "based on" the earlier work. 87 | 88 | A "covered work" means either the unmodified Program or a work based 89 | on the Program. 90 | 91 | To "propagate" a work means to do anything with it that, without 92 | permission, would make you directly or secondarily liable for 93 | infringement under applicable copyright law, except executing it on a 94 | computer or modifying a private copy. Propagation includes copying, 95 | distribution (with or without modification), making available to the 96 | public, and in some countries other activities as well. 97 | 98 | To "convey" a work means any kind of propagation that enables other 99 | parties to make or receive copies. Mere interaction with a user through 100 | a computer network, with no transfer of a copy, is not conveying. 101 | 102 | An interactive user interface displays "Appropriate Legal Notices" 103 | to the extent that it includes a convenient and prominently visible 104 | feature that (1) displays an appropriate copyright notice, and (2) 105 | tells the user that there is no warranty for the work (except to the 106 | extent that warranties are provided), that licensees may convey the 107 | work under this License, and how to view a copy of this License. If 108 | the interface presents a list of user commands or options, such as a 109 | menu, a prominent item in the list meets this criterion. 110 | 111 | 1. Source Code. 112 | 113 | The "source code" for a work means the preferred form of the work 114 | for making modifications to it. "Object code" means any non-source 115 | form of a work. 116 | 117 | A "Standard Interface" means an interface that either is an official 118 | standard defined by a recognized standards body, or, in the case of 119 | interfaces specified for a particular programming language, one that 120 | is widely used among developers working in that language. 121 | 122 | The "System Libraries" of an executable work include anything, other 123 | than the work as a whole, that (a) is included in the normal form of 124 | packaging a Major Component, but which is not part of that Major 125 | Component, and (b) serves only to enable use of the work with that 126 | Major Component, or to implement a Standard Interface for which an 127 | implementation is available to the public in source code form. A 128 | "Major Component", in this context, means a major essential component 129 | (kernel, window system, and so on) of the specific operating system 130 | (if any) on which the executable work runs, or a compiler used to 131 | produce the work, or an object code interpreter used to run it. 132 | 133 | The "Corresponding Source" for a work in object code form means all 134 | the source code needed to generate, install, and (for an executable 135 | work) run the object code and to modify the work, including scripts to 136 | control those activities. However, it does not include the work's 137 | System Libraries, or general-purpose tools or generally available free 138 | programs which are used unmodified in performing those activities but 139 | which are not part of the work. For example, Corresponding Source 140 | includes interface definition files associated with source files for 141 | the work, and the source code for shared libraries and dynamically 142 | linked subprograms that the work is specifically designed to require, 143 | such as by intimate data communication or control flow between those 144 | subprograms and other parts of the work. 145 | 146 | The Corresponding Source need not include anything that users 147 | can regenerate automatically from other parts of the Corresponding 148 | Source. 149 | 150 | The Corresponding Source for a work in source code form is that 151 | same work. 152 | 153 | 2. Basic Permissions. 154 | 155 | All rights granted under this License are granted for the term of 156 | copyright on the Program, and are irrevocable provided the stated 157 | conditions are met. This License explicitly affirms your unlimited 158 | permission to run the unmodified Program. The output from running a 159 | covered work is covered by this License only if the output, given its 160 | content, constitutes a covered work. This License acknowledges your 161 | rights of fair use or other equivalent, as provided by copyright law. 162 | 163 | You may make, run and propagate covered works that you do not 164 | convey, without conditions so long as your license otherwise remains 165 | in force. You may convey covered works to others for the sole purpose 166 | of having them make modifications exclusively for you, or provide you 167 | with facilities for running those works, provided that you comply with 168 | the terms of this License in conveying all material for which you do 169 | not control copyright. Those thus making or running the covered works 170 | for you must do so exclusively on your behalf, under your direction 171 | and control, on terms that prohibit them from making any copies of 172 | your copyrighted material outside their relationship with you. 173 | 174 | Conveying under any other circumstances is permitted solely under 175 | the conditions stated below. Sublicensing is not allowed; section 10 176 | makes it unnecessary. 177 | 178 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 179 | 180 | No covered work shall be deemed part of an effective technological 181 | measure under any applicable law fulfilling obligations under article 182 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 183 | similar laws prohibiting or restricting circumvention of such 184 | measures. 185 | 186 | When you convey a covered work, you waive any legal power to forbid 187 | circumvention of technological measures to the extent such circumvention 188 | is effected by exercising rights under this License with respect to 189 | the covered work, and you disclaim any intention to limit operation or 190 | modification of the work as a means of enforcing, against the work's 191 | users, your or third parties' legal rights to forbid circumvention of 192 | technological measures. 193 | 194 | 4. Conveying Verbatim Copies. 195 | 196 | You may convey verbatim copies of the Program's source code as you 197 | receive it, in any medium, provided that you conspicuously and 198 | appropriately publish on each copy an appropriate copyright notice; 199 | keep intact all notices stating that this License and any 200 | non-permissive terms added in accord with section 7 apply to the code; 201 | keep intact all notices of the absence of any warranty; and give all 202 | recipients a copy of this License along with the Program. 203 | 204 | You may charge any price or no price for each copy that you convey, 205 | and you may offer support or warranty protection for a fee. 206 | 207 | 5. Conveying Modified Source Versions. 208 | 209 | You may convey a work based on the Program, or the modifications to 210 | produce it from the Program, in the form of source code under the 211 | terms of section 4, provided that you also meet all of these conditions: 212 | 213 | a) The work must carry prominent notices stating that you modified 214 | it, and giving a relevant date. 215 | 216 | b) The work must carry prominent notices stating that it is 217 | released under this License and any conditions added under section 218 | 7. This requirement modifies the requirement in section 4 to 219 | "keep intact all notices". 220 | 221 | c) You must license the entire work, as a whole, under this 222 | License to anyone who comes into possession of a copy. This 223 | License will therefore apply, along with any applicable section 7 224 | additional terms, to the whole of the work, and all its parts, 225 | regardless of how they are packaged. This License gives no 226 | permission to license the work in any other way, but it does not 227 | invalidate such permission if you have separately received it. 228 | 229 | d) If the work has interactive user interfaces, each must display 230 | Appropriate Legal Notices; however, if the Program has interactive 231 | interfaces that do not display Appropriate Legal Notices, your 232 | work need not make them do so. 233 | 234 | A compilation of a covered work with other separate and independent 235 | works, which are not by their nature extensions of the covered work, 236 | and which are not combined with it such as to form a larger program, 237 | in or on a volume of a storage or distribution medium, is called an 238 | "aggregate" if the compilation and its resulting copyright are not 239 | used to limit the access or legal rights of the compilation's users 240 | beyond what the individual works permit. Inclusion of a covered work 241 | in an aggregate does not cause this License to apply to the other 242 | parts of the aggregate. 243 | 244 | 6. Conveying Non-Source Forms. 245 | 246 | You may convey a covered work in object code form under the terms 247 | of sections 4 and 5, provided that you also convey the 248 | machine-readable Corresponding Source under the terms of this License, 249 | in one of these ways: 250 | 251 | a) Convey the object code in, or embodied in, a physical product 252 | (including a physical distribution medium), accompanied by the 253 | Corresponding Source fixed on a durable physical medium 254 | customarily used for software interchange. 255 | 256 | b) Convey the object code in, or embodied in, a physical product 257 | (including a physical distribution medium), accompanied by a 258 | written offer, valid for at least three years and valid for as 259 | long as you offer spare parts or customer support for that product 260 | model, to give anyone who possesses the object code either (1) a 261 | copy of the Corresponding Source for all the software in the 262 | product that is covered by this License, on a durable physical 263 | medium customarily used for software interchange, for a price no 264 | more than your reasonable cost of physically performing this 265 | conveying of source, or (2) access to copy the 266 | Corresponding Source from a network server at no charge. 267 | 268 | c) Convey individual copies of the object code with a copy of the 269 | written offer to provide the Corresponding Source. This 270 | alternative is allowed only occasionally and noncommercially, and 271 | only if you received the object code with such an offer, in accord 272 | with subsection 6b. 273 | 274 | d) Convey the object code by offering access from a designated 275 | place (gratis or for a charge), and offer equivalent access to the 276 | Corresponding Source in the same way through the same place at no 277 | further charge. You need not require recipients to copy the 278 | Corresponding Source along with the object code. If the place to 279 | copy the object code is a network server, the Corresponding Source 280 | may be on a different server (operated by you or a third party) 281 | that supports equivalent copying facilities, provided you maintain 282 | clear directions next to the object code saying where to find the 283 | Corresponding Source. Regardless of what server hosts the 284 | Corresponding Source, you remain obligated to ensure that it is 285 | available for as long as needed to satisfy these requirements. 286 | 287 | e) Convey the object code using peer-to-peer transmission, provided 288 | you inform other peers where the object code and Corresponding 289 | Source of the work are being offered to the general public at no 290 | charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, family, 298 | or household purposes, or (2) anything designed or sold for incorporation 299 | into a dwelling. In determining whether a product is a consumer product, 300 | doubtful cases shall be resolved in favor of coverage. For a particular 301 | product received by a particular user, "normally used" refers to a 302 | typical or common use of that class of product, regardless of the status 303 | of the particular user or of the way in which the particular user 304 | actually uses, or expects or is expected to use, the product. A product 305 | is a consumer product regardless of whether the product has substantial 306 | commercial, industrial or non-consumer uses, unless such uses represent 307 | the only significant mode of use of the product. 308 | 309 | "Installation Information" for a User Product means any methods, 310 | procedures, authorization keys, or other information required to install 311 | and execute modified versions of a covered work in that User Product from 312 | a modified version of its Corresponding Source. The information must 313 | suffice to ensure that the continued functioning of the modified object 314 | code is in no case prevented or interfered with solely because 315 | modification has been made. 316 | 317 | If you convey an object code work under this section in, or with, or 318 | specifically for use in, a User Product, and the conveying occurs as 319 | part of a transaction in which the right of possession and use of the 320 | User Product is transferred to the recipient in perpetuity or for a 321 | fixed term (regardless of how the transaction is characterized), the 322 | Corresponding Source conveyed under this section must be accompanied 323 | by the Installation Information. But this requirement does not apply 324 | if neither you nor any third party retains the ability to install 325 | modified object code on the User Product (for example, the work has 326 | been installed in ROM). 327 | 328 | The requirement to provide Installation Information does not include a 329 | requirement to continue to provide support service, warranty, or updates 330 | for a work that has been modified or installed by the recipient, or for 331 | the User Product in which it has been modified or installed. Access to a 332 | network may be denied when the modification itself materially and 333 | adversely affects the operation of the network or violates the rules and 334 | protocols for communication across the network. 335 | 336 | Corresponding Source conveyed, and Installation Information provided, 337 | in accord with this section must be in a format that is publicly 338 | documented (and with an implementation available to the public in 339 | source code form), and must require no special password or key for 340 | unpacking, reading or copying. 341 | 342 | 7. Additional Terms. 343 | 344 | "Additional permissions" are terms that supplement the terms of this 345 | License by making exceptions from one or more of its conditions. 346 | Additional permissions that are applicable to the entire Program shall 347 | be treated as though they were included in this License, to the extent 348 | that they are valid under applicable law. If additional permissions 349 | apply only to part of the Program, that part may be used separately 350 | under those permissions, but the entire Program remains governed by 351 | this License without regard to the additional permissions. 352 | 353 | When you convey a copy of a covered work, you may at your option 354 | remove any additional permissions from that copy, or from any part of 355 | it. (Additional permissions may be written to require their own 356 | removal in certain cases when you modify the work.) You may place 357 | additional permissions on material, added by you to a covered work, 358 | for which you have or can give appropriate copyright permission. 359 | 360 | Notwithstanding any other provision of this License, for material you 361 | add to a covered work, you may (if authorized by the copyright holders of 362 | that material) supplement the terms of this License with terms: 363 | 364 | a) Disclaiming warranty or limiting liability differently from the 365 | terms of sections 15 and 16 of this License; or 366 | 367 | b) Requiring preservation of specified reasonable legal notices or 368 | author attributions in that material or in the Appropriate Legal 369 | Notices displayed by works containing it; or 370 | 371 | c) Prohibiting misrepresentation of the origin of that material, or 372 | requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | 375 | d) Limiting the use for publicity purposes of names of licensors or 376 | authors of the material; or 377 | 378 | e) Declining to grant rights under trademark law for use of some 379 | trade names, trademarks, or service marks; or 380 | 381 | f) Requiring indemnification of licensors and authors of that 382 | material by anyone who conveys the material (or modified versions of 383 | it) with contractual assumptions of liability to the recipient, for 384 | any liability that these contractual assumptions directly impose on 385 | those licensors and authors. 386 | 387 | All other non-permissive additional terms are considered "further 388 | restrictions" within the meaning of section 10. If the Program as you 389 | received it, or any part of it, contains a notice stating that it is 390 | governed by this License along with a term that is a further 391 | restriction, you may remove that term. If a license document contains 392 | a further restriction but permits relicensing or conveying under this 393 | License, you may add to a covered work material governed by the terms 394 | of that license document, provided that the further restriction does 395 | not survive such relicensing or conveying. 396 | 397 | If you add terms to a covered work in accord with this section, you 398 | must place, in the relevant source files, a statement of the 399 | additional terms that apply to those files, or a notice indicating 400 | where to find the applicable terms. 401 | 402 | Additional terms, permissive or non-permissive, may be stated in the 403 | form of a separately written license, or stated as exceptions; 404 | the above requirements apply either way. 405 | 406 | 8. Termination. 407 | 408 | You may not propagate or modify a covered work except as expressly 409 | provided under this License. Any attempt otherwise to propagate or 410 | modify it is void, and will automatically terminate your rights under 411 | this License (including any patent licenses granted under the third 412 | paragraph of section 11). 413 | 414 | However, if you cease all violation of this License, then your 415 | license from a particular copyright holder is reinstated (a) 416 | provisionally, unless and until the copyright holder explicitly and 417 | finally terminates your license, and (b) permanently, if the copyright 418 | holder fails to notify you of the violation by some reasonable means 419 | prior to 60 days after the cessation. 420 | 421 | Moreover, your license from a particular copyright holder is 422 | reinstated permanently if the copyright holder notifies you of the 423 | violation by some reasonable means, this is the first time you have 424 | received notice of violation of this License (for any work) from that 425 | copyright holder, and you cure the violation prior to 30 days after 426 | your receipt of the notice. 427 | 428 | Termination of your rights under this section does not terminate the 429 | licenses of parties who have received copies or rights from you under 430 | this License. If your rights have been terminated and not permanently 431 | reinstated, you do not qualify to receive new licenses for the same 432 | material under section 10. 433 | 434 | 9. Acceptance Not Required for Having Copies. 435 | 436 | You are not required to accept this License in order to receive or 437 | run a copy of the Program. Ancillary propagation of a covered work 438 | occurring solely as a consequence of using peer-to-peer transmission 439 | to receive a copy likewise does not require acceptance. However, 440 | nothing other than this License grants you permission to propagate or 441 | modify any covered work. These actions infringe copyright if you do 442 | not accept this License. Therefore, by modifying or propagating a 443 | covered work, you indicate your acceptance of this License to do so. 444 | 445 | 10. Automatic Licensing of Downstream Recipients. 446 | 447 | Each time you convey a covered work, the recipient automatically 448 | receives a license from the original licensors, to run, modify and 449 | propagate that work, subject to this License. You are not responsible 450 | for enforcing compliance by third parties with this License. 451 | 452 | An "entity transaction" is a transaction transferring control of an 453 | organization, or substantially all assets of one, or subdividing an 454 | organization, or merging organizations. If propagation of a covered 455 | work results from an entity transaction, each party to that 456 | transaction who receives a copy of the work also receives whatever 457 | licenses to the work the party's predecessor in interest had or could 458 | give under the previous paragraph, plus a right to possession of the 459 | Corresponding Source of the work from the predecessor in interest, if 460 | the predecessor has it or can get it with reasonable efforts. 461 | 462 | You may not impose any further restrictions on the exercise of the 463 | rights granted or affirmed under this License. For example, you may 464 | not impose a license fee, royalty, or other charge for exercise of 465 | rights granted under this License, and you may not initiate litigation 466 | (including a cross-claim or counterclaim in a lawsuit) alleging that 467 | any patent claim is infringed by making, using, selling, offering for 468 | sale, or importing the Program or any portion of it. 469 | 470 | 11. Patents. 471 | 472 | A "contributor" is a copyright holder who authorizes use under this 473 | License of the Program or a work on which the Program is based. The 474 | work thus licensed is called the contributor's "contributor version". 475 | 476 | A contributor's "essential patent claims" are all patent claims 477 | owned or controlled by the contributor, whether already acquired or 478 | hereafter acquired, that would be infringed by some manner, permitted 479 | by this License, of making, using, or selling its contributor version, 480 | but do not include claims that would be infringed only as a 481 | consequence of further modification of the contributor version. For 482 | purposes of this definition, "control" includes the right to grant 483 | patent sublicenses in a manner consistent with the requirements of 484 | this License. 485 | 486 | Each contributor grants you a non-exclusive, worldwide, royalty-free 487 | patent license under the contributor's essential patent claims, to 488 | make, use, sell, offer for sale, import and otherwise run, modify and 489 | propagate the contents of its contributor version. 490 | 491 | In the following three paragraphs, a "patent license" is any express 492 | agreement or commitment, however denominated, not to enforce a patent 493 | (such as an express permission to practice a patent or covenant not to 494 | sue for patent infringement). To "grant" such a patent license to a 495 | party means to make such an agreement or commitment not to enforce a 496 | patent against the party. 497 | 498 | If you convey a covered work, knowingly relying on a patent license, 499 | and the Corresponding Source of the work is not available for anyone 500 | to copy, free of charge and under the terms of this License, through a 501 | publicly available network server or other readily accessible means, 502 | then you must either (1) cause the Corresponding Source to be so 503 | available, or (2) arrange to deprive yourself of the benefit of the 504 | patent license for this particular work, or (3) arrange, in a manner 505 | consistent with the requirements of this License, to extend the patent 506 | license to downstream recipients. "Knowingly relying" means you have 507 | actual knowledge that, but for the patent license, your conveying the 508 | covered work in a country, or your recipient's use of the covered work 509 | in a country, would infringe one or more identifiable patents in that 510 | country that you have reason to believe are valid. 511 | 512 | If, pursuant to or in connection with a single transaction or 513 | arrangement, you convey, or propagate by procuring conveyance of, a 514 | covered work, and grant a patent license to some of the parties 515 | receiving the covered work authorizing them to use, propagate, modify 516 | or convey a specific copy of the covered work, then the patent license 517 | you grant is automatically extended to all recipients of the covered 518 | work and works based on it. 519 | 520 | A patent license is "discriminatory" if it does not include within 521 | the scope of its coverage, prohibits the exercise of, or is 522 | conditioned on the non-exercise of one or more of the rights that are 523 | specifically granted under this License. You may not convey a covered 524 | work if you are a party to an arrangement with a third party that is 525 | in the business of distributing software, under which you make payment 526 | to the third party based on the extent of your activity of conveying 527 | the work, and under which the third party grants, to any of the 528 | parties who would receive the covered work from you, a discriminatory 529 | patent license (a) in connection with copies of the covered work 530 | conveyed by you (or copies made from those copies), or (b) primarily 531 | for and in connection with specific products or compilations that 532 | contain the covered work, unless you entered into that arrangement, 533 | or that patent license was granted, prior to 28 March 2007. 534 | 535 | Nothing in this License shall be construed as excluding or limiting 536 | any implied license or other defenses to infringement that may 537 | otherwise be available to you under applicable patent law. 538 | 539 | 12. No Surrender of Others' Freedom. 540 | 541 | If conditions are imposed on you (whether by court order, agreement or 542 | otherwise) that contradict the conditions of this License, they do not 543 | excuse you from the conditions of this License. If you cannot convey a 544 | covered work so as to satisfy simultaneously your obligations under this 545 | License and any other pertinent obligations, then as a consequence you may 546 | not convey it at all. For example, if you agree to terms that obligate you 547 | to collect a royalty for further conveying from those to whom you convey 548 | the Program, the only way you could satisfy both those terms and this 549 | License would be to refrain entirely from conveying the Program. 550 | 551 | 13. Remote Network Interaction; Use with the GNU General Public License. 552 | 553 | Notwithstanding any other provision of this License, if you modify the 554 | Program, your modified version must prominently offer all users 555 | interacting with it remotely through a computer network (if your version 556 | supports such interaction) an opportunity to receive the Corresponding 557 | Source of your version by providing access to the Corresponding Source 558 | from a network server at no charge, through some standard or customary 559 | means of facilitating copying of software. This Corresponding Source 560 | shall include the Corresponding Source for any work covered by version 3 561 | of the GNU General Public License that is incorporated pursuant to the 562 | following paragraph. 563 | 564 | Notwithstanding any other provision of this License, you have 565 | permission to link or combine any covered work with a work licensed 566 | under version 3 of the GNU General Public License into a single 567 | combined work, and to convey the resulting work. The terms of this 568 | License will continue to apply to the part which is the covered work, 569 | but the work with which it is combined will remain governed by version 570 | 3 of the GNU General Public License. 571 | 572 | 14. Revised Versions of this License. 573 | 574 | The Free Software Foundation may publish revised and/or new versions of 575 | the GNU Affero General Public License from time to time. Such new versions 576 | will be similar in spirit to the present version, but may differ in detail to 577 | address new problems or concerns. 578 | 579 | Each version is given a distinguishing version number. If the 580 | Program specifies that a certain numbered version of the GNU Affero General 581 | Public License "or any later version" applies to it, you have the 582 | option of following the terms and conditions either of that numbered 583 | version or of any later version published by the Free Software 584 | Foundation. If the Program does not specify a version number of the 585 | GNU Affero General Public License, you may choose any version ever published 586 | by the Free Software Foundation. 587 | 588 | If the Program specifies that a proxy can decide which future 589 | versions of the GNU Affero General Public License can be used, that proxy's 590 | public statement of acceptance of a version permanently authorizes you 591 | to choose that version for the Program. 592 | 593 | Later license versions may give you additional or different 594 | permissions. However, no additional obligations are imposed on any 595 | author or copyright holder as a result of your choosing to follow a 596 | later version. 597 | 598 | 15. Disclaimer of Warranty. 599 | 600 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 601 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 602 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 603 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 604 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 605 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 606 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 607 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 608 | 609 | 16. Limitation of Liability. 610 | 611 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 612 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 613 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 614 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 615 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 616 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 617 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 618 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 619 | SUCH DAMAGES. 620 | 621 | 17. Interpretation of Sections 15 and 16. 622 | 623 | If the disclaimer of warranty and limitation of liability provided 624 | above cannot be given local legal effect according to their terms, 625 | reviewing courts shall apply local law that most closely approximates 626 | an absolute waiver of all civil liability in connection with the 627 | Program, unless a warranty or assumption of liability accompanies a 628 | copy of the Program in return for a fee. 629 | 630 | END OF TERMS AND CONDITIONS 631 | 632 | How to Apply These Terms to Your New Programs 633 | 634 | If you develop a new program, and you want it to be of the greatest 635 | possible use to the public, the best way to achieve this is to make it 636 | free software which everyone can redistribute and change under these terms. 637 | 638 | To do so, attach the following notices to the program. It is safest 639 | to attach them to the start of each source file to most effectively 640 | state the exclusion of warranty; and each file should have at least 641 | the "copyright" line and a pointer to where the full notice is found. 642 | 643 | 644 | Copyright (C) 645 | 646 | This program is free software: you can redistribute it and/or modify 647 | it under the terms of the GNU Affero General Public License as published 648 | by the Free Software Foundation, either version 3 of the License, or 649 | (at your option) any later version. 650 | 651 | This program is distributed in the hope that it will be useful, 652 | but WITHOUT ANY WARRANTY; without even the implied warranty of 653 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 654 | GNU Affero General Public License for more details. 655 | 656 | You should have received a copy of the GNU Affero General Public License 657 | along with this program. If not, see . 658 | 659 | Also add information on how to contact you by electronic and paper mail. 660 | 661 | If your software can interact with users remotely through a computer 662 | network, you should also make sure that it provides a way for users to 663 | get its source. For example, if your program is a web application, its 664 | interface could display a "Source" link that leads users to an archive 665 | of the code. There are many ways you could offer source, and different 666 | solutions will be better for different programs; see section 13 for the 667 | specific requirements. 668 | 669 | You should also get your employer (if you work as a programmer) or school, 670 | if any, to sign a "copyright disclaimer" for the program, if necessary. 671 | For more information on this, and how to apply and follow the GNU AGPL, see 672 | . 673 | --------------------------------------------------------------------------------