-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsc_utils.py
More file actions
2028 lines (1601 loc) · 92 KB
/
sc_utils.py
File metadata and controls
2028 lines (1601 loc) · 92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import copy
import json
import torch
import time
import ltl_utils
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mplsoccer as mpl
import networkx as nx
from pprint import pprint
from datetime import datetime
from tqdm import tqdm
from datetime import datetime
from typing import List
from typing import Dict
from typing import Tuple
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torch.utils.data import random_split
from scipy.spatial import ConvexHull
from scipy.spatial import Voronoi
from scipy.spatial import cKDTree
from scipy.spatial import voronoi_plot_2d
from scipy.spatial import convex_hull_plot_2d
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
LEFT_UP_CORNER = (-52.50, 34)
LEFT_BOTTOM_CORNER = (-52.50, -34)
RIGHT_UP_CORNER = (52.50, 34)
RIGHT_BOTTOM_CORNER = (52.50, -34)
class GameLoader:
"""
This class receives the path for the game data files and the name of a particular game
and loads the relevant information about the game.
"""
def __init__(self, base_path, game_name, name=None):
with open(f'{base_path}/{game_name}.json', 'r') as handle:
self.game_tracks = json.load(handle)
with open(f'{base_path}/{game_name}-match-info.json', 'r') as handle:
self.game_info = json.load(handle)
self.ball_id = self.game_info['ball']['trackable_object']
self.home_id = self.game_info['home_team']['id']
self.away_id = self.game_info['away_team']['id']
self.home_players = self.get_team_players(home=True)
self.away_players = self.get_team_players(home=False)
self.home_trackable_objects = list(map(lambda x: x['trackable_object'], self.home_players))
self.away_trackable_objects = list(map(lambda x: x['trackable_object'], self.away_players))
self.__interpolate_ball_coordinates()
self.__pass_detection()
# exit()
# self.__interpolate_pitch_state()
if name is not None:
player_track_object = self.get_trackable_object(name[0], name[1])
self.__interpolate_player_position(player_track_object, threshold=50, mode='linear')
self.__interpolate_ball_possessor()
def get_team_players(self, home :bool=True) -> List[Dict]:
"""
This function returns the name of the players of a team with their jersey numbers.
:param home (bool) - Default True: returns the players of the Home team if True,
returns the players of the Away team otherwise
"""
# specify the team for which we want to extract the team members
key = 'home_team' if home else 'away_team'
self.team_id = self.game_info[key]['id']
team_players = [item for item in self.game_info['players'] if item['team_id'] == self.team_id]
return team_players
def get_pitch_size(self) -> List:
"""
This function extracts the pitch size using the info file.
"""
length, width = self.game_info['pitch_length'], self.game_info['pitch_width']
return [length, width]
def get_ball_coords(self, instance_no: int) -> List:
for elem in self.game_tracks[instance_no]['data']:
if elem['trackable_object'] == self.ball_id:
return [elem['x'], elem['y'], elem['z']]
def get_player_coords(self, instance_no: int, trackable_object: int) -> List:
"""
This method receives an instance number and a trackable object corresponding
to a player and returns the player's coordinates if available
"""
exists, _ = self.player_exists(instance_no, trackable_object)
if exists:
home_info = self.get_team_instance_info(instance_no, True)
for player in home_info:
if player['trackable_object'] == trackable_object:
return [player['x'], player['y']]
away_info = self.get_team_instance_info(instance_no, False)
for player in away_info:
if player['trackable_object'] == trackable_object:
return [player['x'], player['y']]
else:
return None
def get_team_instance_info(self, instance_no: int, home: bool=True) -> List[Dict]:
"""
This method receives an instance number and an indicator specifying whether the
information of the homw team should be retreived or the away team. The method then
collects the team player information at the specified instance number.
:param instance_no (int): specified the frame/instance number
:param home (bool) - default True: specifies the team whose information should be
retrieved.
"""
track = self.game_tracks[instance_no]['data']
info = []
for item in track:
if home:
if item['trackable_object'] in self.home_trackable_objects:
info.append(item)
else:
if item['trackable_object'] in self.away_trackable_objects:
info.append(item)
return info
def get_trackable_object(self, first_name: str, last_name: str) -> int:
"""
This method receives the first name and last name of a player and returns his/her
trackable_object attribute
:param first_name (str): the player's first name
:param last_name (str): the player's last name
"""
for player in self.home_players:
if player['first_name'] == first_name and player['last_name'] == last_name:
return player['trackable_object']
for player in self.away_players:
if player['first_name'] == first_name and player['last_name'] == last_name:
return player['trackable_object']
raise Exception('[!] No player with such first name and last name exists!')
def get_team_from_trackable_object(self, trackable_object: int) -> str:
"""
This method receives a trackable object and returns either "home_team" if the
corresponding player belongs to the home team or "away_team" if the corresponding
player belongs to the away team.
:param trackable_object (int): the trackable object of a player
"""
for player in self.home_players:
if player['trackable_object'] == trackable_object:
return 'home_team'
for player in self.away_players:
if player['trackable_object'] == trackable_object:
return 'away_team'
raise Exception('[!] No player with such a trackable object exists!')
def assign_ball_based_on_distance(self, instance_no: int, prior: str=None):
"""
This function receives an instance of the tracking information and assigns the ball
to the player who is the closest to the ball
"""
assert prior == 'home team' or prior == 'away team' or prior is None
# finding the ball coordinates
ball_coordinates = self.get_ball_coords(instance_no)[:2]
# getting the players info in this particular instance
home_team_info = self.get_team_instance_info(instance_no, home=True)
away_team_info = self.get_team_instance_info(instance_no, home=False)
teams_info = home_team_info.copy()
teams_info.extend(away_team_info)
# find the closest home team player to the ball
all_players_info = [[player['x'], player['y']] for player in home_team_info]
all_players_info.extend([[player['x'], player['y']] for player in away_team_info])
all_players_info = np.array(all_players_info)
ball_coordinates = np.array([ball_coordinates] * len(all_players_info))
distances = np.sqrt(np.sum((all_players_info - ball_coordinates) ** 2, axis=1))
sorted_indices = np.argsort(distances)
target_team = None
if prior == 'home team':
target_team = 'home_team'
elif prior == 'away team':
target_team = 'away_team'
if target_team:
for index in sorted_indices:
if self.get_team_from_trackable_object(teams_info[index]['trackable_object']) == target_team:
self.game_tracks[instance_no]['possession']['trackable_object'] = teams_info[index]['trackable_object']
break
else:
if self.game_tracks[instance_no]['possession']['group'] is None:
self.game_tracks[instance_no]['possession']['group'] = self.get_team_from_trackable_object(teams_info[sorted_indices[0]]['trackable_object'])
self.game_tracks[instance_no]['possession']['trackable_object'] = teams_info[sorted_indices[0]]['trackable_object']
def is_ball_out_of_pitch(self, instance_no: int):
"""
At an instance, this method determines whether the ball is inside the pitch or not
"""
ball_coords = self.get_ball_coords(instance_no)
if LEFT_UP_CORNER[0] <= ball_coords[0] <= RIGHT_UP_CORNER[0] and LEFT_BOTTOM_CORNER[1] <= ball_coords[1] <= LEFT_UP_CORNER[1]:
return False
return True
def get_team_possession_from_trackable_object(self, instance_no):
"""
In some instances of the game, the ball possessor is known but the team
who possesses the ball is uknown.
"""
possessor_team = self.game_tracks[instance_no]['possession']['group']
possessor_player = self.game_tracks[instance_no]['possession']['trackable_object']
game_started_condition = len(self.get_team_instance_info(instance_no)) > 0
if possessor_team is None and possessor_player and game_started_condition is not None:
self.game_tracks[instance_no]['possession']['group'] = self.get_team_from_trackable_object(possessor_player)
def get_team_side(self, instance_no: int, home: bool=True) -> str:
"""
This method determines whether a team is attacking from left to right or
right to left at a particular instance.
"""
try:
period = self.game_tracks[instance_no]['period'] - 1
except:
if instance_no / 600 > 45:
period = 1
else:
period = 0
if home:
return self.game_info['home_team_side'][period]
else:
return self.game_info['home_team_side'][1 - period]
def player_exists(self, instance_no: int, trackable_object: int) -> bool:
"""
This method checks if a player with the given trackable object appears
in a particular instance of the game.
:param instance_no (int): the instance of the game at which we want to check
the existence of the player
"param trackable_object (int): the trackable object of the player
"""
track = self.game_tracks[instance_no]
possession = track['possession']['group']
exists = False
for item in track['data']:
if item['trackable_object'] == trackable_object:
exists = True
break
return exists, possession
def __ball_exists(self, instance_no: int) -> bool:
"""
This method determines whether the tracking information of the ball exists in a particular instance.
:param instance_no (int): an integer specifying the tracking instance number
"""
for elem in self.game_tracks[instance_no]['data']:
if elem['trackable_object'] == self.ball_id:
return True
return False
def __missing_possession_counter(self):
count = 0
for i in range(len(self.game_tracks)):
possessor_team = self.game_tracks[i]['possession']['group']
possessor_player = self.game_tracks[i]['possession']['trackable_object']
game_started_condition = len(self.get_team_instance_info(i)) > 0
if (possessor_team is None or possessor_player is None) and game_started_condition:
count += 1
return count
def __interpolate_ball_coordinates(self):
"""
This functions interpolates the ball position for every instance of the game at which
the ball coordinates is unknown
"""
# keep track of the index of the element in the ball_trajectory list
index = 0
# iterate through the sequence of ball coordinates
print('[*] Linearly interpolating the ball coordinates...')
while index < len(self.game_tracks):
# we need to find the number of consecutive frames which have NaN values
num_consecutive_nones = 0
# check if the ball info exists in this instance
ball_exists = self.__ball_exists(index)
if not ball_exists:
# fix the starting index (the last index which is not NaN)
start_index = index - 1
# swing the index until we get to a non-NaN value and increase
# the number of consecutive NaN frames
end_index = index
while not self.__ball_exists(end_index):
num_consecutive_nones += 1
end_index += 1
# define the steps for linear interpolation
steps = np.linspace(0, 1., num_consecutive_nones)
# fill the NaN values by interpolating the line connecting the two non-NaN values
init = np.array(self.get_ball_coords(start_index), dtype=np.float16)
finit = np.array(self.get_ball_coords(end_index), dtype=np.float16)
for j, step in enumerate(steps):
value = np.round((1 - step) * init + step * finit, 2).tolist()
self.game_tracks[start_index + j + 1]['data'].append({'track_id': self.ball_id,
'trackable_object': self.ball_id,
'is_visible': False,
'x': value[0],
'y': value[1],
'z': value[2]})
index = end_index
else:
index += 1
def __interpolate_pitch_state(self):
# constructing the network
neural_net = torch.nn.Sequential(
torch.nn.Linear(47, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 64),
torch.nn.ReLU(),
torch.nn.Linear(64, 44)
)
if os.path.exists('saved_models/pitch_state_interpolator.pt'):
print('[*] Loading the neural network')
neural_net.load_state_dict(torch.load('saved_models/pitch_state_interpolator.pt'))
# iterate through the game instances and fill in the gaps with the neural net
print('[*] Interpolating the pitch state using the neural network...')
for i in tqdm(range(1, len(self.game_tracks))):
# check the sufficient condition for state interpolation
if len(self.game_tracks[i]['data']) <= 1:
previous_data = self.game_tracks[i - 1]['data'].copy()
if len(previous_data) > 1:
previous_positions = []
for info in previous_data:
previous_positions.append(info['x'])
previous_positions.append(info['y'])
if 'z' in info.keys():
previous_positions.append(info['z'])
previous_positions = torch.tensor(previous_positions, dtype=torch.float32).view(1, -1)
current_estimate = copy.deepcopy(previous_data)
with torch.no_grad():
estimate = neural_net(previous_positions).squeeze(0).tolist()
for j in range(22):
current_estimate[j]['x'] = np.round(estimate[2 * j], decimals=2)
current_estimate[j]['y'] = np.round(estimate[2 * j + 1], decimals=2)
previous_ball_info = self.game_tracks[i]['data'][-1]
self.game_tracks[i]['data'] = current_estimate
self.game_tracks[i]['data'][-1] = previous_ball_info
else:
print('[!] No existing pitch state interpolator neural net found! Training a new neural network...')
os.makedirs('saved_models', exist_ok=True)
self.__train_neural_net(neural_net)
self.__interpolate_pitch_state()
def __train_neural_net(self, neural_net: torch.nn.Module):
# preparing the dataset for the neural network
temp_access = self.game_tracks
class PositionDataset(Dataset):
def __init__(self):
positions = []
timestamps = []
for instance in temp_access:
data = instance['data']
# extract the instances for which the positions of the players
# are known
sample = []
if len(data) > 1:
for info in data:
sample.append(info['x'])
sample.append(info['y'])
if 'z' in info.keys():
sample.append(info['z'])
positions.append(sample)
timestamps.append(datetime.strptime(instance['timestamp'], '%H:%M:%S.%f'))
self.intput_output = []
for i in range(len(positions) - 1):
if (timestamps[i + 1] - timestamps[i]).total_seconds() == 0.1:
inp = positions[i]
out = positions[i + 1][:44]
self.intput_output.append((inp, out))
def __len__(self):
return len(self.intput_output)
def __getitem__(self, index):
inp = torch.tensor(self.intput_output[index][0], dtype=torch.float32)
out = torch.tensor(self.intput_output[index][1], dtype=torch.float32)
sample = {'x': inp, 'y': out}
return sample
whole_dataset = PositionDataset()
train_len = int(0.8 * len(whole_dataset))
train_data, test_data = random_split(whole_dataset, [train_len, len(whole_dataset) - train_len])
train_loader = DataLoader(train_data, batch_size=64, shuffle=True)
test_loader = DataLoader(test_data, batch_size=64, shuffle=True)
# defining the optimizer
optimizer = torch.optim.Adam(neural_net.parameters(), lr=1e-4)
# defining the loss function
loss_fn = torch.nn.MSELoss()
# training phase
best_test_loss = float('inf')
train_losses = []
test_losses = []
for epoch in range(200):
start_time = time.time()
avg_train_loss = 0.
for sample in train_loader:
inp, out = sample['x'], sample['y']
optimizer.zero_grad()
output = neural_net(inp)
loss = loss_fn(output, out) + 0.1 * torch.norm(output - inp[:, :44])
loss.backward()
optimizer.step()
avg_train_loss += loss.item()
avg_train_loss /= len(train_loader)
train_losses.append(avg_train_loss)
with torch.no_grad():
avg_test_loss = 0.
for sample in test_loader:
inp, out = sample['x'], sample['y']
output = neural_net(inp)
loss = loss_fn(output, out)
avg_test_loss += loss.item()
avg_test_loss /= len(test_loader)
end_time = time.time()
test_losses.append(avg_test_loss)
elapsed = end_time - start_time
msg = f'[*] Epoch: {epoch:04d} - Avg Train Loss: {avg_train_loss:.3f} - Avg Test Loss: {avg_test_loss:.3f} ({elapsed:.1f}s)'
if avg_test_loss < best_test_loss:
best_test_loss = avg_test_loss
torch.save(neural_net.state_dict(), 'saved_models/pitch_state_interpolator.pt')
msg += ' - [CHECKPOINT]'
print(msg)
np.savetxt('train_losses.txt', train_losses)
np.savetxt('test_losses.txt', test_losses)
exit()
def __interpolate_ball_possessor(self):
"""
This function finds the ball possessor for the instances at which the possessor is unknwon.
Such instances usually happen in continuous sequences. For a found sequence, we look at the
events information and see whether there is a pass event happend before the sequence. If so,
we interpolate the ball possessor with the information of the pass receiver. Otherwise, we
take the simple approach and fill the information of the ball possessor using the concept of
Voronoi cells; i.e., the ball is assigned to the closest player.
"""
print('[*] Interpolating ball possession information')
initial_missings = self.__missing_possession_counter()
for i in tqdm(range(len(self.game_tracks))):
# get the information of the possessing team, possessing player, and whether the game has started
possessor_team = self.game_tracks[i]['possession']['group']
possessor_player = self.game_tracks[i]['possession']['trackable_object']
game_started_condition = len(self.get_team_instance_info(i)) > 0
# if the ball is outside the pitch the possession is assigned to neither teams
if self.is_ball_out_of_pitch(i):
self.game_tracks[i]['possession']['group'] = 'out'
self.game_tracks[i]['possession']['trackable_object'] = 'out'
# if team possession is unknown but possessing player is known, fill the team possession accordingly
self.get_team_possession_from_trackable_object(i)
# if team possession is known but possessing player is unknown, assign the possessing player
# based on their distance to the ball and with prior information that the possessing player
# must belong to the possessing team
if possessor_team is not None and possessor_player is None and game_started_condition:
self.assign_ball_based_on_distance(i, possessor_team)
# if both team possession and possessing player is unknown, assign the possessing team
# and the possessing player based on their distance to the ball
if possessor_team is None and possessor_player is None and game_started_condition:
self.assign_ball_based_on_distance(i)
finial_missing = self.__missing_possession_counter()
if finial_missing == 0:
print(f'\__[*] Successfully interpolated {initial_missings}/{len(self.game_tracks)} instances with missing possession information.')
def __interpolate_player_position(self, trackable_object, threshold=50, mode='linear'):
presence_indicator = []
for i in range(len(self.game_tracks)):
exists, _ = self.player_exists(i, trackable_object)
if exists:
presence_indicator.append(1)
else:
presence_indicator.append(0)
i = presence_indicator.index(1)
last_index = len(presence_indicator) - 1 - presence_indicator[::-1].index(1)
while i < last_index:
if presence_indicator[i] == 1 and presence_indicator[i + 1] == 0:
j = i + 2
count = 1
while j < last_index and presence_indicator[j] == presence_indicator[i + 1]:
count += 1
j += 1
if count < threshold:
player_first = self.get_player_coords(i, trackable_object)
player_last = self.get_player_coords(j, trackable_object)
avg_x = 0.5 * (player_first[0] + player_last[0])
avg_y = 0.5 * (player_first[1] + player_last[1])
denom_x = player_last[0] - player_first[0]
denom_y = player_last[1] - player_first[1]
coeff = 1
for ind in range(i + 1, j):
if mode == 'linear':
if denom_x == 0:
new_x = player_last[0]
else:
new_x = (coeff / denom_x) * (player_last[0] - player_first[0]) + player_first[0]
if denom_y == 0:
new_y = player_last[1]
else:
new_y = (coeff / denom_y) * (player_last[1] - player_first[1]) + player_first[1]
coeff += 1
else:
new_x = avg_x
new_y = avg_y
self.game_tracks[ind]['data'].append({'track_id': trackable_object,
'trackable_object': trackable_object,
'is_visible': False,
'x': new_x,
'y': new_y})
i = j
else:
i += 1
def __pass_detection(self) -> None:
"""
This method is supposed to extract the passes throughout the game. The speculation is
that the successfull pass instances are the ones that the team possession is known but
the possessing player is unknown. The second conjecture is that the intercepted passes
are the ones that neither the possessing team nor the possessing player are known.
"""
if os.path.exists('pass_instances.csv'):
return
pass_instances = pd.DataFrame(columns=['instance', 'outcome', 'possessing team'])
for i in tqdm(range(len(self.game_tracks))):
# get the information of the possessing team, possessing player, and whether the game has started
possessor_team = self.game_tracks[i]['possession']['group']
possessor_player = self.game_tracks[i]['possession']['trackable_object']
game_started_condition = len(self.get_team_instance_info(i)) > 0
# if the ball is outside the pitch the possession is assigned to neither teams
if self.is_ball_out_of_pitch(i):
self.game_tracks[i]['possession']['group'] = 'out'
self.game_tracks[i]['possession']['trackable_object'] = 'out'
# if team possession is unknown but possessing player is known, fill the team possession accordingly
self.get_team_possession_from_trackable_object(i)
# if team possession is known but possessing player is unknown, assign the possessing player
# based on their distance to the ball and with prior information that the possessing player
# must belong to the possessing team
if not self.is_ball_out_of_pitch(i):
if possessor_team is not None and possessor_player is None and game_started_condition:
pass_instances.loc[len(pass_instances.index)] = [i, 'success', possessor_team]
# if both team possession and possessing player is unknown, assign the possessing team
# and the possessing player based on their distance to the ball
if possessor_team is None and possessor_player is None and game_started_condition:
pass_instances.loc[len(pass_instances.index)] = [i, 'failed', None]
pass_instances.to_csv('pass_instances.csv', index=False)
class PlayerTracker:
"""
This class tracks the location of a target player along with the ball coordinates
for every instance that the player happens to exist.
"""
def __init__(self, game: GameLoader, first_name: str, last_name: str, home: bool=True) -> None:
"""
The initializer/constructor gets an instance of the GameLoader which contains
the players and all the tracking information, the jersey number of the target
player and whether the player belongs to the home team.
NOTE: if you do not know the jersey number of the player, you can invoke the
get_team_players() method of the game instance to see the players names
with their corresponding jersey numbers
:param game (GameLoader): an instance of the game.
:param jersey_number (int): the jersey number of the target player.
:param home (bool) - Default True: whether the player belongs to the home team
"""
self.game = game
self.first_name = first_name
self.last_name = last_name
self.home = home
self.player_trajectory = None
self.ball_trajectory = None
self.team_possession_trajectory = None
self.track_id = [player['trackable_object'] for player in self.game.get_team_players()
if player['first_name'] == first_name and player['last_name'] == last_name]
if len(self.track_id) == 0:
raise Exception('[!] No such player exists!')
else:
self.track_id = self.track_id[0]
self.present_instances = []
self.visible_polygons = []
def track(self) -> None:
"""
This function generates the trajectory of the movement of the player along
the game using the tracking data.
This function updates two attributes self.player_trajectory and self.ball_trajectory
"""
# create an empty list to record the coordinates of the player
player_trajectory = []
# if we also want to see the location of the ball at each frame
ball_trajectory = []
team_possession_trajectory = []
print('[*] Tracking the player and the ball...')
for index in tqdm(range(len(self.game.game_tracks))):
track = self.game.game_tracks[index]
# get the information of all players at an instance
players = track['data']
# check whether the target player has any record in this frame
target_player = list(filter(lambda x: x['trackable_object'] == self.track_id, players))
# if the player's record exists in this frame...
if len(target_player) > 0:
# find the player's coordinates at this frame
coords = [target_player[0]['x'], target_player[0]['y']]
# fill in the player's trajectory list
player_trajectory.append(coords)
# find the position of the ball
ball_trajectory.append(self.game.get_ball_coords(index))
# determining which team possesses the ball in this instance
team_possession_trajectory.append(track['possession'])
# keep the true index of the game instance for future use
self.present_instances.append(index)
self.player_trajectory = player_trajectory
self.ball_trajectory = ball_trajectory
self.team_possession_trajectory = team_possession_trajectory
def get_player_gaze(self) -> Tuple[List, List, List, List]:
"""
This function uses the player's trajectory and the ball trajectory already tracked
and generates the gaze vectors as the composition of movement vectors and player-to-ball
vectors.
"""
# a list to store the x coordinates of the gaze vectors tails
gaze_start_x = []
# a list to store the y cooordinates of the gaze vectors tails
gaze_start_y = []
# a list to store the x coordinates of the gaze vectors heads
gaze_end_x = []
# a list to store the y coordinates of the gaze vectors heads
gaze_end_y = []
# iterate through all the position coordinates of the player and the ball
for i in range(len(self.player_trajectory) - 1):
# find the length of the vector from the player to the ball (used to normalize the vectors)
length = np.sqrt((self.ball_trajectory[i][0] - self.player_trajectory[i][0]) ** 2 + (self.ball_trajectory[i][1] - self.player_trajectory[i][1]) ** 2)
# find the length of the movement vector of the player (used to normaluze the vectors)
p_length = np.sqrt((self.player_trajectory[i + 1][0] - self.player_trajectory[i][0]) ** 2 + (self.player_trajectory[i + 1][1] - self.player_trajectory[i][1]) ** 2)
# find the end-location of the normalized movement vectors and player-to-ball vectors
p_end_x = self.player_trajectory[i][0] + (self.player_trajectory[i + 1][0] - self.player_trajectory[i][0]) / p_length if p_length != 0 else self.player_trajectory[i][0]
p_end_y = self.player_trajectory[i][1] + (self.player_trajectory[i + 1][1] - self.player_trajectory[i][1]) / p_length if p_length != 0 else self.player_trajectory[i][1]
p_b_end_x = self.player_trajectory[i][0] + (self.ball_trajectory[i][0] - self.player_trajectory[i][0]) / length
p_b_end_y = self.player_trajectory[i][1] + (self.ball_trajectory[i][1] - self.player_trajectory[i][1]) / length
# constructing the gaze vectors
gaze_start_x.append(self.player_trajectory[i][0])
gaze_start_y.append(self.player_trajectory[i][1])
gaze_end_x.append(-self.player_trajectory[i][0] + (p_end_x + p_b_end_x))
gaze_end_y.append(-self.player_trajectory[i][1] + (p_end_y + p_b_end_y))
return gaze_start_x, gaze_start_y, gaze_end_x, gaze_end_y
def get_visible_polygon(self) -> List:
"""
This function uses the start and end coordinates of the gaze vectors and computes
the vertices of the visible polygon at each frame.
"""
# find the width and height of the pitch
# NOTE: the (0, 0) coordinate is placed at the centeral point of the pitch
size_x, size_y = self.game.get_pitch_size()
# define the x, y values of the left, right, upper, and lower boundaries
left_x, right_x, upper_y, lower_y = -size_x / 2, size_x / 2, size_y / 2, -size_y / 2
print('[*] Computing the gaze vectors of the player...')
start_x_list, start_y_list, end_x_list, end_y_list = self.get_player_gaze()
print('[*] Computing the visible polygons of the player...')
for index in range(len(start_x_list)):
start_x = start_x_list[index]
start_y = start_y_list[index]
end_x = end_x_list[index]
end_y = end_y_list[index]
# if the gaze vecotr is not a vertical vector
if end_x - start_x != 0:
gaze_slope = (end_y - start_y) / (end_x - start_x)
# if the gaze vector is vertical
else:
gaze_slope = None
# if the gaze vector is horizontal
if gaze_slope == 0:
# find the intersection of the gaze line with the boundary
point1 = (start_x, upper_y)
point2 = (start_x, lower_y)
# check if the player is moving to the left or right
left_facing = True if end_x < start_x else False
# if the player is moving to the left (consider the left polygon)
if left_facing:
# get the two other vertices of the visible polygon
point3 = (left_x, upper_y)
point4 = (left_x, lower_y)
else:
point3 = (right_x, upper_y)
point4 = (right_x, lower_y)
# if the gaze vector is vertical
elif gaze_slope is None:
# find the intersection of the gaze line with the boundary
point1 = (left_x, start_y)
point2 = (right_x, start_y)
# check if the player is moving downwards or upwards
down_facing = True if end_y < start_y else False
# if moving downwards (lower polygon)
if down_facing:
point3 = (left_x, lower_y)
point4 = (right_x, lower_y)
# if moving upwards (upper polygon)
else:
point3 = (left_x, upper_y)
point4 = (right_x, upper_y)
# if the gaze line is an oblique line
else:
# find the gaze line
line_slope = - 1 / gaze_slope
interception = start_y - line_slope * start_x
# find the intersection of the gaze line with the boundary
point1 = ((upper_y - interception) / line_slope, upper_y)
point2 = ((lower_y - interception) / line_slope, lower_y)
# check if the player is moving to the left or right
left_facing = True if end_x < start_x else False
# if the player is moving to the left (left polygon)
if left_facing:
point3 = (left_x, upper_y)
point4 = (left_x, lower_y)
# if the player is moving to the right (right polygon)
else:
point3 = (right_x, upper_y)
point4 = (right_x, lower_y)
self.visible_polygons.append([point1, point2, point3, point4])
def player_movement_arrows(self) -> Tuple[List, List, List, List]:
"""
This function uses the trajectory of the player and generates the movement
vectors from the trajectory.
"""
# a list to store the x coordinate of the tail of the movement vectors
start_x = []
# a list to store the y coordinate of the tail of the movement vectors
start_y = []
# a list to store the x coordinate of the head of the movement vectors
end_x = []
# a list to store the y coordinates of the head of the movement vectors
end_y = []
for index in range(len(self.player_trajectory) - 1):
start_x.append(self.player_trajectory[index][0])
start_y.append(self.player_trajectory[index][1])
end_x.append(self.player_trajectory[index + 1][0])
end_y.append(self.player_trajectory[index + 1][1])
return start_x, start_y, end_x, end_y
def ball_movement_arrows(self) -> Tuple[List, List, List, List]:
"""
This function uses the trajectory of the ball and generates the movement
vectors from the trajectory.
"""
ball_start_x = []
ball_start_y = []
ball_end_x = []
ball_end_y = []
for index in range(len(self.ball_trajectory) - 1):
ball_start_x.append(self.ball_trajectory[index][0])
ball_start_y.append(self.ball_trajectory[index][1])
ball_end_x.append(self.ball_trajectory[index + 1][0])
ball_end_y.append(self.ball_trajectory[index + 1][1])
return ball_start_x, ball_start_y, ball_end_x, ball_end_y
class AllTracker:
"""
This class tracks the ball throughout the game. The difference between this class
and PlayerTracker class is that Playertracker class tracks the ball only in the
frames that the target player is present. However, this class tracks the ball in
all the frames, and also keeps track of all the players in all frames.
This class is useful when someone wants to plot the general configuration of the pitch
in a particular snapshot, or determine who possesses the ball at a particular instance
of the game.
"""
def __init__(self, game: GameLoader) -> None:
"""
The initializer/constructor gets an instance of the GameLoader which contains
the players and all the tracking information.
"""
self.game = game
self.ball_trajectory = None
self.home_coordinates = None
self.away_coordinates = None
def track(self):
"""
This function iterates through all the frames, and at each frame it stores the coordinate of
the players appearing on the pitch divided into two separate lists home_coordinates and
away_coordinates. At each frame, the coordinates of the ball is also recorded and by the end
of iterations, the missing ball locations get linearly interpolated.
This function updates three attributes self.ball_trajectory, self.home_coordinates, self.away_coordinates
"""
# ball_trajectory is a list, each of which element is a list specifying the coordinate of the ball
# e.g., [[0, 0, 0], [1, 0, 0], ...]
ball_trajectory = []
# home_coordinates is a list, each of which element is again a list which contains the coordinates of
# the home players; e.g., [[[0, 0], [0, 1], [1, 0], .., [4, 6]], [[0, 1], [1, 2], [3, 5], ..., [8, 12]]]
home_coordinates = []
# similar to home_teams but for the away players
away_coordinates = []
print('[*] Tracking the players and the ball...')
for index in tqdm(range(len(self.game.game_tracks))):
# find the position of the ball
ball_trajectory.append(self.game.get_ball_coords(index))
# get the information of all players at an instance
home_players = self.game.get_team_instance_info(index, True)
away_players = self.game.get_team_instance_info(index, False)
home_coordinates.append(home_players)
away_coordinates.append(away_players)
self.ball_trajectory = ball_trajectory
self.home_coordinates = home_coordinates
self.away_coordinates = away_coordinates
def get_ball_possessor(self, instance_no):
trackable_object = self.game.game_tracks[instance_no]['possession']['trackable_object']
team = self.game.game_tracks[instance_no]['possession']['group']
home = True if team == 'home_team' else False
return home, trackable_object
def get_reachable_teammates(self, instance_no: int, first_name: str, last_name: str, home: bool=True) -> int:
"""
This function receives an instance number, a jersey number, the voronoi cells
associate to the instance of the game, and whether the player belongs to the
home team. The function then uses the Voronoi cells to construct an adjacency
matrix of the teammates. If there is a path between the target player and any
of the teammates, then that teammate is reachable.
:param instance_no (int): the number of instance at which we want to count the
reachable teammates.
:param jersey_number (int): the jersey number of the target player
:param voronoi_cells (Voronoi): the voronoi cells of the particular instance
of the game
:param home (bool) - Default True: determines whether the player belongs to
home team or away team.
"""