-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2255 lines (1871 loc) · 89.6 KB
/
Copy pathmain.py
File metadata and controls
2255 lines (1871 loc) · 89.6 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 numpy as np
import scipy.stats
import scipy.interpolate
import scipy.optimize
import matplotlib
import matplotlib.pyplot as plt
import time
import NBA_Parser
import sqlite3
from itertools import islice
from datetime import datetime
import multiprocessing as mp
import os
import sys
def GenPermLog(arr: np.ndarray, n: int) -> np.ndarray:
a = np.atleast_2d(arr)
b = np.arange(arr.shape[0])
for i in range(n):
c = np.random.permutation(b)
d = np.take(a, c, 1)
a = np.concatenate((a, d))
return a
# def GenPermReg(arr: np.ndarray) -> np.ndarray:
# a = np.atleast_2d(arr)
# b = np.tile(a, (8000, 1))
#
# for i in range(1, 8000):
# np.random.shuffle(b[i])
#
# return b
def GenPermReg(arr):
b = [arr.copy() for _ in range(8000)]
for i in range(1, 8000):
np.random.shuffle(b[i])
return b
def calcArea(a, b, scoreA: int, scoreB: int) -> float:
m = scoreA / scoreB
m_i = scoreB / scoreA
last_side, cur_side = 1, 1 # 1 is Home team
lastPoint, curPoint = [0] * 2, [0] * 2
curSum, cur_y, last_y, x_cut = 0., 0., 0., 0.
# j = 1
for i in range(min(len(a), len(b))):
for j in range(2):
if j == 0:
if type(a[i]) is not int:
continue
curPoint[1] += a[i]
else:
if type(b[i]) is not int:
continue
curPoint[0] += b[i]
if curPoint[0] == lastPoint[0] and curPoint[1] == lastPoint[1]:
continue
cur_y = curPoint[0]*m
# dot product used to find the side: (P.y - A.y)*(B.x - A.x) - (P.x - A.x)*(B.y - A.y)
cur_side = 1 if (curPoint[1] > cur_y) else -1
if cur_side == 1 and last_side == 1: # new point is at A side if last_side == 1: # lsat point was at A side
curSum += (curPoint[1] - (cur_y + last_y)/2) * (curPoint[0] - lastPoint[0]) # calculate the local area between the graphs
elif cur_side == -1:
if last_side == -1:
curSum += ((cur_y + last_y)/2 - curPoint[1]) * (curPoint[0] - lastPoint[0]) # calculate the local area between the graphs
else:
x_cut = curPoint[1] * m_i
curSum += (curPoint[1] - (curPoint[1] + last_y)/2) * (x_cut - lastPoint[0]) + ((cur_y + curPoint[0])/2 - curPoint[1]) * (curPoint[0] - x_cut)
last_side, last_y, lastPoint = cur_side, cur_y, curPoint.copy()
if len(a) > len(b) or len(b) > len(a):
if len(a) > len(b):
if type(a[i+1]) is not int:
return curSum
curPoint[1] += a[i + 1]
else:
if type(b[i+1]) is not int:
return curSum
curPoint[0] += b[i + 1]
if curPoint[0] == lastPoint[0] and curPoint[1] == lastPoint[1]:
return curSum
cur_y = curPoint[0] * m
# dot product used to find the side: (P.y - A.y)*(B.x - A.x) - (P.x - A.x)*(B.y - A.y)
cur_side = 1 if (curPoint[1] > cur_y) else -1
if cur_side == 1 and last_side == 1: # new point is at A side if last_side == 1: # lsat point was at A side
curSum += (curPoint[1] - (cur_y + last_y) / 2) * (curPoint[0] - lastPoint[0]) # calculate the local area between the graphs
elif cur_side == -1:
if last_side == -1:
curSum += ((cur_y + last_y) / 2 - curPoint[1]) * (curPoint[0] - lastPoint[0]) # calculate the local area between the graphs
else:
x_cut = curPoint[1] * m_i
curSum += (curPoint[1] - (curPoint[1] + last_y) / 2) * (x_cut - lastPoint[0]) + ((cur_y + curPoint[0]) / 2 - curPoint[1]) * (curPoint[0] - x_cut)
last_side, last_y, lastPoint = cur_side, cur_y, curPoint.copy()
return curSum
def calcArea_global(glob, scoreA: int, scoreB: int) -> float:
m = scoreA / scoreB
m_i = scoreB / scoreA
last_side, cur_side = 1, 1 # 1 is Home team
lastPoint, curPoint = [0] * 2, [0] * 2
curSum, cur_y, last_y, x_cut = 0., 0., 0., 0.
j = 0
for i in range(len(glob)):
if j == 0:
curPoint[1] += glob[i]
else:
curPoint[0] += glob[i]
if curPoint[0] == lastPoint[0] and curPoint[1] == lastPoint[1]:
continue
cur_y = curPoint[0]*m
# dot product used to find the side: (P.y - A.y)*(B.x - A.x) - (P.x - A.x)*(B.y - A.y)
cur_side = 1 if (curPoint[1] > cur_y) else -1
if cur_side == 1 and last_side == 1: # new point is at A side if last_side == 1: # lsat point was at A side
curSum += (curPoint[1] - (cur_y + last_y)/2) * (curPoint[0] - lastPoint[0]) # calculate the local area between the graphs
elif cur_side == -1:
if last_side == -1:
curSum += ((cur_y + last_y)/2 - curPoint[1]) * (curPoint[0] - lastPoint[0]) # calculate the local area between the graphs
else:
x_cut = curPoint[1] * m_i
curSum += (curPoint[1] - (curPoint[1] + last_y)/2) * (x_cut - lastPoint[0]) + ((cur_y + curPoint[0])/2 - curPoint[1]) * (curPoint[0] - x_cut)
last_side, last_y, lastPoint = cur_side, cur_y, curPoint.copy()
j = 1 - j
return curSum
def calc_possessions_change(a, b):
cur_direction = -1
changes_count = 0
for i in range(min(len(a), len(b))):
for j in range(2):
if j == 0:
if type(a[i]) is int and a[i] > 0:
if cur_direction == 1:
cur_direction = 0
changes_count += 1
elif cur_direction == -1:
cur_direction = 0
else:
if type(b[i]) is int and b[i] > 0:
if cur_direction == 0:
cur_direction = 1
changes_count += 1
elif cur_direction == -1:
cur_direction = 1
if len(b) > len(a):
for i in range(len(a), len(b)):
if type(b[i]) is int and b[i] > 0:
if cur_direction == 0:
cur_direction = 1
changes_count += 1
elif cur_direction == -1:
cur_direction = 1
elif len(a) > len(b):
for i in range(len(b), len(a)):
if type(a[i]) is int and a[i] > 0:
if cur_direction == 1:
cur_direction = 0
changes_count += 1
elif cur_direction == -1:
cur_direction = 0
return changes_count
def calc_max_point_distance(a, b, score_a, score_b):
lastPoint, curPoint = [0] * 2, [0] * 2
cur_dist, max_dist = 0., 0.
for i in range(min(len(a), len(b))):
for j in range(2):
if j == 0:
if type(a[i]) is not int:
continue
curPoint[1] += a[i]
else:
if type(b[i]) is not int:
continue
curPoint[0] += b[i]
if curPoint[0] == lastPoint[0] and curPoint[1] == lastPoint[1]:
continue
cur_dist = abs(score_a*curPoint[0] - score_b*curPoint[1]) / (score_a**2 + score_b**2)**0.5
if cur_dist > max_dist:
max_dist = cur_dist
if len(a) > len(b) and (type(a[i+1]) is int) and a[i+1] > 0:
curPoint[1] += a[i+1]
cur_dist = abs(score_a*curPoint[0] - score_b*curPoint[1]) / (score_a**2 + score_b**2)**0.5
if cur_dist > max_dist:
max_dist = cur_dist
return max_dist
def check_res(game_tag, season, scoreA, scoreB):
game_possessions, _ = NBA_Parser.pbp_to_possessions("Games/{}-{}/{}.csv".format(season-1, season, game_tag))
a_poss = [_ for _ in game_possessions[0::2] if type(_) == int]
b_poss = [_ for _ in game_possessions[1::2] if type(_) == int]
a_perms = GenPermReg(a_poss)
b_perms = GenPermReg(b_poss)
res_area = [0] * 8000
for i in range(8000):
res_area[i] = calcArea(a_perms[i], b_perms[i], scoreA, scoreB)
print(np.median(res_area), res_area[0])
# print(res_area[0])
def calc_momentum(start_season, end_season, lock, prc_name):
with sqlite3.connect('Games.db') as conn_db:
insert_arr = [(None,) * 2] * 2000 # 2000 - max number of games per season
insert_row = [None] * 2
# res_area = [0.] * 8000
for i in range(start_season, end_season - 1, -1):
result = conn_db.execute("SELECT COUNT(*) FROM games_table WHERE SEASON=?", (i,))
num_of_rows = result.fetchone()[0]
games_list = conn_db.execute("SELECT GAME_TAG, SEASON, HOME_SCORE, AWAY_SCORE FROM games_table WHERE SEASON=?", (i,))
# time_var = 0
# EMA_var = 0
row_num = 0
for index, game in enumerate(games_list):
start_t = time.time()
for k in range(1, 6):
try:
try:
game_possessions = NBA_Parser.pbp_to_possessions("Games/{}-{}/{}.csv".format(game[1] - 1, game[1], game[0]))
except:
raise Exception("pbp parser error")
# if who_start == 'H':
# scoreA = game[2]
# scoreB = game[3]
# else:
# scoreA = game[3]
# scoreB = game[2]
#
# a_poss = [_ for _ in game_possessions[0::2] if type(_) == int]
# b_poss = [_ for _ in game_possessions[1::2] if type(_) == int]
#
# if scoreA != sum(a_poss) or scoreB != sum(b_poss):
# raise Exception("Sum doesn't match!")
#
# a_perms = GenPermReg(a_poss)
# b_perms = GenPermReg(b_poss)
#
# for j in range(8000):
# res_area[j] = calcArea(a_perms[j], b_perms[j], scoreA, scoreB)
#
insert_row[0] = game[0]
insert_row[1] = '|'.join([repr(_) for _ in game_possessions])
# insert_row[2] = res_area[0]
# insert_row[3] = np.median(res_area)
# insert_row[4] = np.mean(res_area)
# insert_row[5] = np.var(res_area, ddof=1) # unbiased variance estimator
# insert_row[6] = np.sum([(1 if (v <= insert_row[2]) else 0) for v in res_area]) / 8000
insert_arr[row_num] = tuple(insert_row)
except Exception as inst:
print("\nError occurred in season {},\t{}:\t{}".format(i, game[0], inst.args))
if row_num > 0:
conn_db.executemany("INSERT INTO games_momentum_new VALUES (?,?)", insert_arr[0:row_num])
conn_db.commit()
row_num = 0
break
except:
# sys.stdout.write("\r{} failed calculating,\t{} out of 5".format(game[0], k))
# sys.stdout.flush()
if k == 5:
if row_num > 0:
conn_db.executemany("INSERT INTO games_momentum_new VALUES (?,?)", insert_arr[0:row_num])
conn_db.commit()
# conn.close()
raise
else:
row_num += 1
if k > 1:
print()
break
# sys.stdout.write("\r{}% finished ({} avg sec for game:\t{} min remains)".format(index/num_of_rows*100, time_var, time_var*(num_of_rows - index)/60))
# sys.stdout.flush()
if index == num_of_rows - 1:
print("{}:\tseason {}, index {} - {}".format(prc_name, i, index, time.time() - start_t))
if row_num > 0:
conn_db.executemany("INSERT INTO games_momentum_new VALUES (?,?)", insert_arr[0:row_num])
conn_db.commit()
print("\rfinished season {}".format(i))
def csv_to_possessions():
# with sqlite3.connect('Games.db') as conn:
# conn.execute("""
# CREATE TABLE IF NOT EXISTS games_momentum_new(
# GAME_TAG TEXT NOT NULL UNIQUE,
# POSSESSIONS_ARR TEXT NOT NULL
# );
# """)
lock = mp.Lock()
# process_arr = [None] * 2
# process_arr[0] = mp.Process(target=calc_momentum, args=(2017, 2010, lock, 'Prc_1'))
# process_arr[0].start()
# process_arr[1] = mp.Process(target=calc_momentum, args=(2009, 2002, lock, 'Prc_2'))
# process_arr[1].start()
# process_arr[0].join()
# process_arr[1].join()
calc_momentum(2018, 2018, lock, 'Prc_1')
def area_hist(games_data):
# with sqlite3.connect('Games.db') as conn:
#
# result = conn.execute("SELECT COUNT(*) FROM games_area_momentum")
# num_of_rows = result.fetchone()[0]
# games_stats = conn.execute("""SELECT games_table.YEAR, games_table.MONTH, games_table.HOME_SCORE, games_table.AWAY_SCORE, games_area_momentum.AREA, games_area_momentum.MEAN, games_area_momentum.VAR
# FROM games_area_momentum
# INNER JOIN games_table
# ON games_area_momentum.GAME_TAG = games_table.GAME_TAG
# """)
#
# games_data = games_stats.fetchall()
stats_list = np.array([_[6:] for _ in games_data])
hist_arr = (stats_list[:, 0] - stats_list[:, 2]) / np.sqrt(stats_list[:, 3])
z_hist_density = plt.hist(hist_arr, bins=100, rwidth=0.75, density=True)[0:2]
z_median = np.median(hist_arr)
median_value = 0
for i in range(len(z_hist_density[1]) - 1):
if z_median >= z_hist_density[1][i] and z_median < z_hist_density[1][i+1]:
median_value = z_hist_density[0][i]
print("Median:", z_median, median_value, abs(z_median*2*np.sqrt(len(hist_arr))*median_value), sep='\t')
plt.show(block=False)
plt.figure()
#region Score difference
attribute_arr = [abs(_[4] - _[5]) for _ in games_data]
mask_arr = [attribute_arr[_] for _ in range(len(hist_arr)) if hist_arr[_] >= 0]
mask_arr2 = [attribute_arr[_] for _ in range(len(hist_arr)) if hist_arr[_] < 0]
print("Mask:", np.mean(mask_arr), np.median(mask_arr), np.std(mask_arr), 1/np.sqrt(len(mask_arr)), sep="\t")
plt.hist([mask_arr, mask_arr2], bins=100, rwidth=0.75, density=True, color=['blue', 'green'], alpha=0.7)
# plt.hist(mask_arr2, bins=100, rwidth=0.75, density=True, color='green', alpha=0.6)
plt.show(block=False)
plt.figure()
mask_arr = [hist_arr[_] for _ in range(len(hist_arr)) if attribute_arr[_] >= 20]
mask_arr2 = [hist_arr[_] for _ in range(len(hist_arr)) if attribute_arr[_] < 20]
print("Mann–Whitney U test:", scipy.stats.mannwhitneyu(mask_arr, mask_arr2))
plt.hist([mask_arr, mask_arr2], bins=100, rwidth=0.75, density=True, color=['blue', 'green'], alpha=0.7)
# plt.hist(mask_arr2, bins=100, rwidth=0.75, density=True, color='green', alpha=0.6)
print("Mask:", np.mean(mask_arr), np.median(mask_arr), np.std(mask_arr), 1/np.sqrt(len(mask_arr)), sep="\t")
plt.show(block=False)
plt.figure()
plt.boxplot([mask_arr, mask_arr2], sym='')
plt.show()
def str2possessions(x):
return [int(_) if _[0] != "'" else '0' for _ in str.split(x, '|')]
def calc_global_momentum_range(games_arr, proc_name, res_queue):
area_arr = [0.] * 8000
stats_arr = [None] * 6
insert_arr = [(None,)*6] * len(games_arr)
for k, game in enumerate(games_arr):
try:
time_1 = time.time()
game_tag = game[0]
game_possessions_1 = game[1]
home_score = game[2]
away_score = game[3]
who_start = game[1][1]
game_possessions_2 = [int(_) for _ in str.split(game_possessions_1, '|') if _[0] != "'"] # only possessions
global_possessions = [1] * (len(game_possessions_2) * 2 - 1)
poss_perm = GenPermReg(game_possessions_2)
for j in range(8000):
global_possessions[0::2] = poss_perm[j]
area_arr[j] = calcArea_global(global_possessions, home_score + away_score, len(game_possessions_2) - 1)
# possessions_arr_a = [_ for _ in str2possessions(game[1])[0::2] if type(_) is int]
# possessions_arr_b = [_ for _ in str2possessions(game[1])[1::2] if type(_) is int]
# time_4 = time.time()
# possessions_perm_a = GenPermReg(possessions_arr_a)
# possessions_perm_b = GenPermReg(possessions_arr_b)
# print(time.time() - time_4)
# time_2, time_3 = 0, 0
#
# for j in range(8000):
# time_4 = time.time()
# area_arr[j] = calcArea(possessions_perm_a[j], possessions_perm_b[j], scoreH, scoreA) # calcArea(global_possessions[0::2], global_possessions[1::2], scoreH + scoreA, len(possessions_arr) - 1)
# time_3 += time.time() - time_4
stats_arr[0] = game_tag
stats_arr[1] = area_arr[0]
stats_arr[2] = np.median(area_arr)
stats_arr[3] = np.mean(area_arr)
stats_arr[4] = np.var(area_arr, ddof=1)
stats_arr[5] = sum([1 for v in area_arr if v <= area_arr[0]]) / 8000
insert_arr[k] = tuple(stats_arr)
if (k % 100) == 0:
print("{}:\t {} - {}".format(proc_name, k, time.time() - time_1))
except:
print("Error in " + game[0])
raise
res_queue.put(insert_arr[0:(k+1)])
def calc_global_momentum():
with sqlite3.connect('Games.db') as conn:
conn.execute("DROP TABLE IF EXISTS games_poss_area_global")
conn.execute("""
CREATE TABLE IF NOT EXISTS games_poss_area_global(
GAME_TAG TEXT NOT NULL UNIQUE,
AREA REAL NOT NULL,
MEDIAN REAL NOT NULL,
MEAN REAL NOT NULL,
VAR REAL NOT NULL,
P_VALUE REAL NOT NULL
);
""")
result = conn.execute("SELECT COUNT(*) FROM games_momentum_new")
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""SELECT games_momentum_new.GAME_TAG, games_momentum_new.POSSESSIONS_ARR, games_table.HOME_SCORE, games_table.AWAY_SCORE
FROM games_momentum_new
INNER JOIN games_table
ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
""")
games_data = games_stats.fetchall()
# area_arr = [0.] * 8000
# sign_arr = [0.] * 8000
#
# for k, game in enumerate(games_data):
#
# if k < 1000:
# continue
#
# time_1 = time.time()
# game_tag = game[0]
# scoreH, scoreA = game[2], game[3]
# possessions_arr = [_ for _ in str2possessions(game[1]) if type(_) is int]
# time_4 = time.time()
# possessions_perm = GenPermReg(possessions_arr)
# print(time.time() - time_4)
# global_possessions = [1] * (len(possessions_arr) * 2 - 1)
# time_2, time_3 = 0, 0
#
# for j in range(8000):
# time_4 = time.time()
# global_possessions[0::2] = possessions_perm[j]
# time_2 += time.time() - time_4
# time_4 = time.time()
# area_arr[j] = calcArea_global(global_possessions, scoreH + scoreA, len(possessions_arr) - 1) # calcArea(global_possessions[0::2], global_possessions[1::2], scoreH + scoreA, len(possessions_arr) - 1)
# time_3 += time.time() - time_4
# # possessions_arr_a = [_ for _ in str2possessions(game[1])[0::2] if type(_) is int]
# # possessions_arr_b = [_ for _ in str2possessions(game[1])[1::2] if type(_) is int]
# # time_4 = time.time()
# # possessions_perm_a = GenPermReg(possessions_arr_a)
# # possessions_perm_b = GenPermReg(possessions_arr_b)
# # print(time.time() - time_4)
# # time_2, time_3 = 0, 0
# #
# # for j in range(8000):
# # time_4 = time.time()
# # area_arr[j] = calcArea(possessions_perm_a[j], possessions_perm_b[j], scoreH, scoreA) # calcArea(global_possessions[0::2], global_possessions[1::2], scoreH + scoreA, len(possessions_arr) - 1)
# # time_3 += time.time() - time_4
#
# print(time_2, time_3)
# sign_arr[k] = (area_arr[0] - np.mean(area_arr)) / np.std(area_arr, ddof=1)
# print("\t\t", time.time() - time_1)
#
# if k == 2000:
# break
# print(k)
#
# plt.hist(sign_arr[1000:(k+1)], bins=40, rwidth=0.75)
# plt.show()
# print(sign_arr[0:1000])
# print(sign_arr[1000:(k+1)])
res_queue = mp.Queue()
process_arr = [None] * 4
process_arr[0] = mp.Process(target=calc_global_momentum_range, args=(games_data[0:10000], "Prc_1", res_queue))
process_arr[0].start()
process_arr[1] = mp.Process(target=calc_global_momentum_range, args=(games_data[10000:], "Prc_2", res_queue))
process_arr[1].start()
# process_arr[2] = mp.Process(target=calc_global_momentum_range, args=(10000, 14999, games_data[10000:15000].copy(), "thread_3.txt"))
# process_arr[2].start()
# process_arr[3] = mp.Process(target=calc_global_momentum_range, args=(15000, 25000, games_data[15000:].copy(), "thread_4.txt"))
# process_arr[3].start()
print("Here1")
# process_arr[2].join()
# process_arr[3].join()
insert_arr = res_queue.get()
print("Here2")
insert_arr = insert_arr + res_queue.get()
print("Here3")
process_arr[0].join()
print("check1")
process_arr[1].join()
print("check2")
conn.executemany("INSERT INTO games_poss_area_global VALUES (?,?,?,?,?,?)", insert_arr)
conn.commit()
def plot_pbp_game(pbp_arr, who_start, home_score, away_score, draw_linear=False, draw_area=False, block=False, new_figure=True, draw_legend=True):
game_possessions = pbp_arr.split('|') # [(int(_) if _[0] != "'" else '0') for _ in pbp_arr.split('|') if not (_[0] == "'" and _[1] != "0")] # quarter and OT filtering
# game_points = [[0] * (len(a_poss) + len(b_poss) + 1), [0] * (len(a_poss) + len(b_poss) + 1)]
game_points = [[0] * len(game_possessions), [0] * len(game_possessions)]
quarter_indices = []
quarter_colors = ['black', 'red', 'blue', 'green', 'purple']
quarter_legends = ['QT #' + str(_) for _ in range(1, 5)] + ['OT']
j, k = 0, 0
for poss in game_possessions:
if poss[0] == "'":
if poss in ["'1'", "'2'", "'3'", "'4'", "'1OT'"]:
quarter_indices.append(k)
elif poss == "'0'":
j = 1 - j
continue
game_points[j][k+1] = game_points[j][k] + int(poss)
game_points[1-j][k+1] = game_points[1-j][k]
k += 1
j = 1 - j
quarter_indices.append(k)
if new_figure:
plt.figure()
for i in range(len(quarter_indices) - 1):
plt.plot(game_points[0 if who_start == 'H' else 1][quarter_indices[i]:(quarter_indices[i+1]+1)], game_points[1 if who_start == 'H' else 0][quarter_indices[i]:(quarter_indices[i+1]+1)], color=quarter_colors[i], lw=3, label=quarter_legends[i])
# plt.plot(game_points[0 if who_start == 'H' else 1][quarter_indices[-1]:k+1], game_points[1 if who_start == 'H' else 0][quarter_indices[-1]:k+1], color=quarter_colors[i+1], lw=4)
if draw_linear:
plt.plot([0, home_score], [0, away_score], '--', color='black')
if draw_area:
plt.fill_between(game_points[0 if who_start == 'H' else 1][0:k+1], game_points[1 if who_start == 'H' else 0][0:k+1], np.array(game_points[0 if who_start == 'H' else 1][0:k+1]) * (away_score / home_score), interpolate=True, facecolor='yellow')
plt.title("Play-By-Play Home-Away score progress")
plt.xlabel("Home score")
plt.ylabel("Away score")
if draw_legend:
plt.legend()
plt.show(block=block)
def games_possessions_change():
# old function
with sqlite3.connect('Games.db') as conn:
# conn.execute("""
# CREATE TABLE IF NOT EXISTS games_poss_changes(
# GAME_TAG TEXT NOT NULL UNIQUE,
# CHANGES_COUNT INT NOT NULL,
# MEDIAN REAL NOT NULL,
# MEAN REAL NOT NULL,
# VAR REAL NOT NULL,
# P_VALUE REAL NOT NULL
# );
# """)
insert_arr = [(None,) * 6] * 2000 # 2000 - max number of games per season
insert_row = [None] * 6
res_changes = [0] * 8000
for i in range(2016, 2001, -1):
result = conn.execute("SELECT COUNT(*) FROM games_table WHERE games_table.SEASON = ?", (i,))
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""SELECT games_momentum.GAME_TAG, games_momentum.POSSESSIONS_ARR, games_table.HOME_SCORE, games_table.AWAY_SCORE
FROM games_momentum
INNER JOIN games_table
ON games_momentum.GAME_TAG = games_table.GAME_TAG
WHERE games_table.SEASON = ?
""", (i,))
games_data = games_stats.fetchall()
for k, game in enumerate(games_data):
time_1 = time.time()
possessions_arr_a = [_ for _ in str2possessions(game[1])[0::2] if type(_) is int]
possessions_arr_b = [_ for _ in str2possessions(game[1])[1::2] if type(_) is int]
possessions_perm_a = GenPermReg(possessions_arr_a)
possessions_perm_b = GenPermReg(possessions_arr_b)
time_2, time_3 = 0, 0
for j in range(8000):
time_4 = time.time()
res_changes[j] = calc_possessions_change(possessions_perm_a[j], possessions_perm_b[j])
time_3 += time.time() - time_4
print(time_3)
insert_row[0] = game[0]
insert_row[1] = res_changes[0]
insert_row[2] = np.median(res_changes)
insert_row[3] = np.mean(res_changes)
insert_row[4] = np.var(res_changes, ddof=1)
insert_row[5] = np.sum([(1 if (v <= insert_row[1]) else 0) for v in res_changes]) / 8000
insert_arr[k] = tuple(insert_row)
print("\t\t", time.time() - time_1)
print(k, res_changes[0])
conn.executemany("INSERT INTO games_poss_changes VALUES (?,?,?,?,?,?)", insert_arr[0:(k+1)])
conn.commit()
print("Finished season {}".format(i))
def area_hist_poss_changes():
with sqlite3.connect('Games.db') as conn:
result = conn.execute("SELECT COUNT(*) FROM games_changes_momentum")
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""SELECT games_table.YEAR, games_table.MONTH, games_changes_momentum.CHANGES_COUNT, games_changes_momentum.MEAN, games_changes_momentum.VAR
FROM games_changes_momentum
INNER JOIN games_table
ON games_changes_momentum.GAME_TAG = games_table.GAME_TAG
""")
games_data = games_stats.fetchall()
month_list = [(_[0], _[1]) for _ in games_data]
stats_list = np.array([_[2:] for _ in games_data])
hist_arr = (stats_list[:, 0] - stats_list[:, 1]) / np.sqrt(stats_list[:, 2])
plt.hist(hist_arr, bins=100, rwidth=0.75, density=True)
print(np.median(hist_arr))
print("Hist arr:\n", np.mean(hist_arr), 1/np.sqrt(len(hist_arr)), -np.mean(hist_arr)*np.sqrt(len(hist_arr)))
plt.show()
plt.figure()
# plt.plot(month_list, hist_arr, 'o')
def area_hist_poss_max_dist():
with sqlite3.connect('Games.db') as conn:
result = conn.execute("SELECT COUNT(*) FROM games_poss_dist")
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""SELECT games_table.YEAR, games_table.MONTH, games_poss_dist.MAX_DIST, games_poss_dist.MEAN, games_poss_dist.VAR
FROM games_poss_dist
INNER JOIN games_table
ON games_poss_dist.GAME_TAG = games_table.GAME_TAG
""")
games_data = games_stats.fetchall()
month_list = [(_[0], _[1]) for _ in games_data]
stats_list = np.array([_[2:] for _ in games_data])
hist_arr = (stats_list[:, 0] - stats_list[:, 1]) / np.sqrt(stats_list[:, 2])
plt.hist(hist_arr, bins=100, rwidth=0.75, density=True)
print(np.mean(hist_arr), np.median(hist_arr), sep="\t")
print("Hist arr:\n", np.mean(hist_arr), 1/np.sqrt(len(hist_arr)), -np.mean(hist_arr)*np.sqrt(len(hist_arr)))
plt.show()
plt.figure()
# plt.plot(month_list, hist_arr, 'o')
def area_hist_poss_global():
with sqlite3.connect('Games.db') as conn:
result = conn.execute("SELECT COUNT(*) FROM games_poss_area_global")
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""SELECT games_table.YEAR, games_table.MONTH, games_poss_area_global.AREA, games_poss_area_global.MEAN, games_poss_area_global.VAR
FROM games_poss_area_global
INNER JOIN games_table
ON games_poss_area_global.GAME_TAG = games_table.GAME_TAG
""")
games_data = games_stats.fetchall()
month_list = [(_[0], _[1]) for _ in games_data]
stats_list = np.array([_[2:] for _ in games_data])
hist_arr = (stats_list[:, 0] - stats_list[:, 1]) / np.sqrt(stats_list[:, 2])
plt.hist(hist_arr, bins=100, rwidth=0.75, density=True)
plt.vlines(np.mean(hist_arr), 0, 0.6, color='k', linestyles='--', label='Mean')
plt.annotate(r"${}\sigma_{{\bar{{X}}}}$".format(-4.23), xy=(np.mean(hist_arr), 0.45), xytext=(np.mean(hist_arr)+1, 0.44), arrowprops=dict(facecolor='black', shrink=0.1, width=0.2, headwidth=4), fontsize=15)
plt.title('Area Z-Score')
print(np.mean(hist_arr), np.median(hist_arr), sep="\t")
print("Hist arr:\n", np.mean(hist_arr), 1/np.sqrt(len(hist_arr)), -np.mean(hist_arr)*np.sqrt(len(hist_arr)))
plt.show()
plt.figure()
# plt.plot(month_list, hist_arr, 'o')
def calc_area_h_a(start_season, end_season):
with sqlite3.connect('Games.db') as conn:
# conn.execute("DROP TABLE IF EXISTS games_area_momentum4")
conn.execute("""
CREATE TABLE IF NOT EXISTS games_area_momentum5(
GAME_TAG TEXT NOT NULL UNIQUE,
AREA REAL NOT NULL,
MEDIAN REAL NOT NULL,
MEAN REAL NOT NULL,
VAR REAL NOT NULL,
P_VALUE REAL NOT NULL,
MEDIAN_SMALLER INT NOT NULL,
MEDIAN_EQUAL INT NOT NULL
);
""")
insert_arr = [(None,) * 8] * 2000 # 2000 - max number of games per season
insert_row = [None] * 8
res_area = [0.] * 8000
row_index = 0
for i in range(start_season, end_season - 1, -1):
result = conn.execute("""
SELECT COUNT(*)
FROM games_momentum_new
INNER JOIN games_table ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
inner join games_scores on games_table.GAME_TAG = games_scores.GAME_TAG
WHERE SEASON=? AND games_scores.VALID = 1
""", (i,))
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""
SELECT games_table.GAME_TAG, games_momentum_new.POSSESSIONS_ARR, games_table.HOME_SCORE, games_table.AWAY_SCORE
FROM games_momentum_new
INNER JOIN games_table ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
inner join games_scores on games_table.GAME_TAG = games_scores.GAME_TAG
WHERE SEASON=? AND games_scores.VALID = 1
""", (i,))
games_data = games_stats.fetchall()
row_index = 0
for k, game in enumerate(games_data):
start_t = time.time()
game_tag = game[0]
game_possessions_1 = game[1]
home_score = game[2]
away_score = game[3]
who_start = game[1][1]
game_possessions_2 = [(int(_) if _[0] != "'" else '0') for _ in str.split(game_possessions_1, '|') if not (_[0] == "'" and _[1] != "0")] # quarter and OT filtering
# a_possessions = [_ for _ in game_possessions_2[0::2] if type(_) is int]
# b_possessions = [_ for _ in game_possessions_2[1::2] if type(_) is int]
a_possessions = game_possessions_2[0::2]
b_possessions = game_possessions_2[1::2]
a_poss_perm = GenPermReg(a_possessions)
b_poss_perm = GenPermReg(b_possessions)
if who_start == 'H':
for j in range(8000):
res_area[j] = calcArea(a_poss_perm[j], b_poss_perm[j], home_score, away_score)
else:
for j in range(8000):
res_area[j] = calcArea(a_poss_perm[j], b_poss_perm[j], away_score, home_score)
insert_row[0] = game_tag
insert_row[1] = res_area[0]
insert_row[2] = np.median(res_area)
insert_row[3] = np.mean(res_area)
insert_row[4] = np.var(res_area, ddof=1)
insert_row[5] = sum([1 for _ in res_area if _ < res_area[0]]) / 8000
insert_row[6] = sum([1 for _ in res_area if _ < insert_row[2]])
insert_row[7] = sum([1 for _ in res_area if _ == insert_row[2]])
insert_arr[row_index] = tuple(insert_row)
row_index += 1
if k % 50 == 0:
print("k={} - {}".format(k, time.time() - start_t))
conn.executemany("INSERT INTO games_area_momentum5 VALUES (?,?,?,?,?,?,?,?)", insert_arr[0:row_index])
conn.commit()
print("finished season {}".format(i))
def calc_changes_h_a(start_season, end_season):
with sqlite3.connect('Games.db') as conn:
# conn.execute("DROP TABLE IF EXISTS games_changes_momentum2")
conn.execute("""
CREATE TABLE IF NOT EXISTS games_changes_momentum3(
GAME_TAG TEXT NOT NULL UNIQUE,
CHANGES_COUNT INT NOT NULL,
MEDIAN REAL NOT NULL,
MEAN REAL NOT NULL,
VAR REAL NOT NULL,
P_VALUE REAL NOT NULL,
MEDIAN_SMALLER INT NOT NULL,
MEDIAN_EQUAL INT NOT NULL
);
""")
insert_arr = [(None,) * 8] * 2000 # 2000 - max number of games per season
insert_row = [None] * 8
res_changes = [0] * 8000
row_index = 0
for i in range(start_season, end_season - 1, -1):
result = conn.execute("""
SELECT COUNT(*)
FROM games_momentum_new
INNER JOIN games_table ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
WHERE SEASON=?
""", (i,))
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""SELECT games_table.GAME_TAG, games_momentum_new.POSSESSIONS_ARR, games_table.HOME_SCORE, games_table.AWAY_SCORE
FROM games_momentum_new
INNER JOIN games_table ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
WHERE SEASON=?
""", (i,))
games_data = games_stats.fetchall()
row_index = 0
for k, game in enumerate(games_data):
start_t = time.time()
game_tag = game[0]
game_possessions_1 = game[1]
home_score = game[2]
away_score = game[3]
who_start = game[1][1]
game_possessions_2 = [(int(_) if _[0] != "'" else '0') for _ in str.split(game_possessions_1, '|') if not (_[0] == "'" and _[1] != "0")] # quarter and OT filtering
# a_possessions = [_ for _ in game_possessions_2[0::2] if type(_) is int]
# b_possessions = [_ for _ in game_possessions_2[1::2] if type(_) is int]
a_possessions = game_possessions_2[0::2]
b_possessions = game_possessions_2[1::2]
a_poss_perm = GenPermReg(a_possessions)
b_poss_perm = GenPermReg(b_possessions)
if who_start == 'H':
for j in range(8000):
res_changes[j] = calc_possessions_change(a_poss_perm[j], b_poss_perm[j])
else:
for j in range(8000):
res_changes[j] = calc_possessions_change(a_poss_perm[j], b_poss_perm[j])
insert_row[0] = game_tag
insert_row[1] = res_changes[0]
insert_row[2] = np.median(res_changes)
insert_row[3] = np.mean(res_changes)
insert_row[4] = np.var(res_changes, ddof=1)
insert_row[5] = sum([1 for _ in res_changes if _ < res_changes[0]]) / 8000
insert_row[6] = sum([1 for _ in res_changes if _ < insert_row[2]])
insert_row[7] = sum([1 for _ in res_changes if _ == insert_row[2]])
insert_arr[row_index] = tuple(insert_row)
row_index += 1
if k % 50 == 0:
print("k={} - {}".format(k, time.time() - start_t))
conn.executemany("INSERT INTO games_changes_momentum3 VALUES (?,?,?,?,?,?,?,?)", insert_arr[0:row_index])
conn.commit()
print("finished season {}".format(i))
def calc_possessions_dist(start_season, end_season):
with sqlite3.connect('Games.db') as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS games_poss_dist3(
GAME_TAG TEXT NOT NULL UNIQUE,
MAX_DIST REAL NOT NULL,
MEDIAN REAL NOT NULL,
MEAN REAL NOT NULL,
VAR REAL NOT NULL,
P_VALUE REAL NOT NULL,
MEDIAN_SMALLER INT NOT NULL,
MEDIAN_EQUAL INT NOT NULL
);
""")
insert_arr = [(None,) * 8] * 2000 # 2000 - max number of games per season
insert_row = [None] * 8
res_changes = [0] * 8000
row_index = 0
for i in range(start_season, end_season - 1, -1):
result = conn.execute("""
SELECT COUNT(*)
FROM games_momentum_new
INNER JOIN games_table ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
INNER JOIN games_scores on games_table.GAME_TAG = games_scores.GAME_TAG
WHERE SEASON=? AND games_scores.VALID = 1
""", (i,))
num_of_rows = result.fetchone()[0]
games_stats = conn.execute("""
SELECT
games_table.GAME_TAG, games_momentum_new.POSSESSIONS_ARR, games_table.HOME_SCORE, games_table.AWAY_SCORE
FROM games_momentum_new
INNER JOIN games_table ON games_momentum_new.GAME_TAG = games_table.GAME_TAG
INNER JOIN games_scores on games_table.GAME_TAG = games_scores.GAME_TAG
WHERE SEASON=? AND games_scores.VALID = 1
""", (i,))
games_data = games_stats.fetchall()
row_index = 0
for k, game in enumerate(games_data):
start_t = time.time()
game_tag = game[0]
game_possessions_1 = game[1]
home_score = game[2]
away_score = game[3]
who_start = game[1][1]
game_possessions_2 = [(int(_) if _[0] != "'" else '0') for _ in str.split(game_possessions_1, '|') if not (_[0] == "'" and _[1] != "0")] # quarter and OT filtering
# a_possessions = [_ for _ in game_possessions_2[0::2] if type(_) is int]
# b_possessions = [_ for _ in game_possessions_2[1::2] if type(_) is int]
a_possessions = game_possessions_2[0::2]
b_possessions = game_possessions_2[1::2]
a_poss_perm = GenPermReg(a_possessions)
b_poss_perm = GenPermReg(b_possessions)
if who_start == 'H':
for j in range(8000):
res_changes[j] = calc_max_point_distance(a_poss_perm[j], b_poss_perm[j], home_score, away_score)
else:
for j in range(8000):
res_changes[j] = calc_max_point_distance(a_poss_perm[j], b_poss_perm[j], away_score, home_score)
insert_row[0] = game_tag
insert_row[1] = res_changes[0]
insert_row[2] = np.median(res_changes)
insert_row[3] = np.mean(res_changes)
insert_row[4] = np.var(res_changes, ddof=1)
insert_row[5] = sum([1 for _ in res_changes if _ <= res_changes[0]]) / 8000
insert_row[6] = sum([1 for _ in res_changes if _ < insert_row[2]])
insert_row[7] = sum([1 for _ in res_changes if _ == insert_row[2]])
insert_arr[row_index] = tuple(insert_row)
row_index += 1
if k % 50 == 0:
print("k={} - {}".format(k, time.time() - start_t))
conn.executemany("INSERT INTO games_poss_dist3 VALUES (?,?,?,?,?,?,?,?)", insert_arr[0:row_index])
conn.commit()
print("finished season {}".format(i))
def check_bias():
arr = "'A'|'1'|2|0|2|2|0|0|0|0|0|2|1|0|0|0|2|0|0|3|0|0|3|3|0|2|0|2|2|0|0|0|0|3|2|2|2|0|0|0|0|2|0|2|0|1|0|0|2|1|0|3|0|'2'|0|0|2|0|0|0|0|2|2|2|0|2|0|0|2|0|0|0|0|0|2|2|3|2|0|2|0|3|0|3|2|3|0|2|3|0|0|1|2|0|0|0|0|0|0|2|0|0|0|1|2|0|'3'|0|0|2|0|1|0|0|2|3|2|2|0|2|0|3|0|0|0|0|0|0|2|2|0|3|0|0|0|3|2|3|0|2|2|0|2|2|3|2|0|0|3|2|1|2|0|'4'|'0'|0|0|2|2|3|0|2|3|0|2|0|3|3|0|0|2|0|2|0|0|0|2|2|3|0|3|0|3|2|2|2|0|2|0|2|0|0|2|0|0|0|2|0|0|0|2|1|0|0|2|3"
game_possessions_2 = [(int(_) if _[0] != "'" else '0') for _ in str.split(arr, '|') if not (_[0] == "'" and _[1] != "0")] # quarter and OT filtering
a_possessions = [_ for _ in game_possessions_2[0::2] if type(_) is int]
b_possessions = [_ for _ in game_possessions_2[1::2] if type(_) is int]
res_area = [0.] * 8000
a_poss_perm = GenPermReg(a_possessions)
b_poss_perm = GenPermReg(b_possessions)
score_a = sum(a_possessions)
score_b = sum(b_possessions)
for i in range(8000):
res_area[i] = calcArea(a_poss_perm[i], b_poss_perm[i], score_a, score_b)
print("without 0:\t", res_area[0], np.mean(res_area), np.std(res_area))
plt.hist(res_area, bins=100, rwidth=0.75)
plt.show(block=False)
arr = "'A'|'1'|2|0|2|2|0|0|0|0|0|2|1|0|0|0|2|0|0|3|0|0|3|3|0|2|0|2|2|0|0|0|0|3|2|2|2|0|0|0|0|2|0|2|0|1|0|0|2|1|0|3|0|'2'|0|0|2|0|0|0|0|2|2|2|0|2|0|0|2|0|0|0|0|0|2|2|3|2|0|2|0|3|0|3|2|3|0|2|3|0|0|1|2|0|0|0|0|0|0|2|0|0|0|1|2|0|'3'|0|0|2|0|1|0|0|2|3|2|2|0|2|0|3|0|0|0|0|0|0|2|2|0|3|0|0|0|3|2|3|0|2|2|0|2|2|3|2|0|0|3|2|1|2|0|'4'|'0'|0|0|2|2|3|0|2|3|0|2|0|3|3|0|0|2|0|2|0|0|0|2|2|3|0|3|0|3|2|2|2|0|2|0|2|0|0|2|0|0|0|2|0|0|0|2|1|0|0|2|3"
game_possessions_2 = [(int(_) if _[0] != "'" else '0') for _ in str.split(arr, '|') if not (_[0] == "'" and _[1] != "0")] # quarter and OT filtering
a_possessions = [_ for _ in game_possessions_2[0::2] if type(_) is int] + [0] * 400
b_possessions = [_ for _ in game_possessions_2[1::2] if type(_) is int] + [0] * 400
res_area = [0.] * 8000