-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmpairwise.py
563 lines (494 loc) · 20.7 KB
/
mpairwise.py
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
import openpyxl
import json
FIRSTWEIGHT = 0.8
SECONDWEIGHT = 2 - FIRSTWEIGHT
OTWIN = 0.55
OTLOSS = 1 - OTWIN
WPWEIGHT = 0.25
OWPWEIGHT = 0.21
OOWPWEIGHT = 0.54
QWBSTART = 0.050
QWBSCALE = QWBSTART / 20
def outputPWR(teamstats, sortedpwr):
# Create sheet
wb = openpyxl.Workbook()
ws = wb.active
# Header row
r = 1
ws.cell(row = r, column = 1).value = 'Rank'
ws.cell(row = r, column = 2).value = 'Team'
ws.cell(row = r, column = 3).value = 'PCWs'
ws.cell(row = r, column = 4).value = 'RPI'
ws.cell(row = r, column = 5).value = 'QWB'
ws.cell(row = r, column = 6).value = 'Adj RPI'
ws.cell(row = r, column = 7).value = 'Unadj RPI'
# Output each team
for i in sortedpwr:
team = i[0]
pwr, rpi = i[1]
ws.cell(row = r + 1, column = 1).value = r
ws.cell(row = r + 1, column = 2).value = team
ws.cell(row = r + 1, column = 3).value = pwr
ws.cell(row = r + 1, column = 4).value = rpi
ws.cell(row = r + 1, column = 5).value = teamstats[team]["qwb"]
ws.cell(row = r + 1, column = 6).value = teamstats[team]["arpi"]
ws.cell(row = r + 1, column = 7).value = teamstats[team]["urpi"]
r += 1
# Save wb
wb.save('Womens Pairwise.xlsx')
def compareH2H(teamstats, team1, team2):
team1wins = countTeam(teamstats[team1]["w"], team2) + countTeam(teamstats[team1]["otw"], team2)
team2wins = countTeam(teamstats[team2]["w"], team1) + countTeam(teamstats[team2]["otw"], team1)
return team1wins, team2wins
def compareCoOpp(teamstats, team1, team2):
# Use set intersect to find common opponents
coOpp = set(teamstats[team1]["opponents"]).intersection(set(teamstats[team2]["opponents"]))
# Calculate win percentage against common opponents
team1CoOpp = 0
team2CoOpp = 0
for team in coOpp:
# Calculate win percentage against common opponent and add to sum
team1wins = countTeam(teamstats[team1]["w"], team) + countTeam(teamstats[team1]["otw"], team) \
+ 0.5 * countTeam(teamstats[team1]["t"], team)
team1gp = countTeam(teamstats[team1]["w"], team) + countTeam(teamstats[team1]["l"], team) \
+ countTeam(teamstats[team1]["otw"], team) + countTeam(teamstats[team1]["otl"], team) \
+ countTeam(teamstats[team1]["t"], team)
team1CoOpp += team1wins / team1gp
team2wins = countTeam(teamstats[team2]["w"], team) + countTeam(teamstats[team2]["otw"], team) \
+ 0.5 * countTeam(teamstats[team2]["t"], team)
team2gp = countTeam(teamstats[team2]["w"], team) + countTeam(teamstats[team2]["l"], team) \
+ countTeam(teamstats[team2]["otw"], team) + countTeam(teamstats[team2]["otl"], team) \
+ countTeam(teamstats[team2]["t"], team)
team2CoOpp += team2wins / team2gp
if team1CoOpp > team2CoOpp:
return 1, 0
elif team2CoOpp > team1CoOpp:
return 0, 1
else:
return 0, 0
def compareRPI(teamstats, team1, team2):
if teamstats[team1]["rpi"] > teamstats[team2]["rpi"]:
return 1, 0
else:
return 0, 1
def calcPWR(teamstats):
# Stores all comparisons done to save time
done = set()
# Compare all teams
for team1 in teamstats:
for team2 in teamstats:
# Check if comparison already made
if (team1, team2) in done or (team2, team1) in done or team1 == team2:
continue
# Calculate pairwise components
rpi1, rpi2 = compareRPI(teamstats, team1, team2)
coopp1, coopp2 = compareCoOpp(teamstats, team1, team2)
h2h1, h2h2 = compareH2H(teamstats, team1, team2)
team1pwr = rpi1 + coopp1 + h2h1
team2pwr = rpi2 + coopp2 + h2h2
# Determine winner of comparison
if team1pwr > team2pwr:
teamstats[team1]["pwr"] += 1
elif team2pwr > team1pwr:
teamstats[team2]["pwr"] += 1
else:
if rpi1 > rpi2:
teamstats[team1]["pwr"] += 1
else:
teamstats[team2]["pwr"] += 1
done.add((team1, team2))
def calcFinalRPI(teamstats):
for key in teamstats:
teamstats[key]["rpi"] = teamstats[key]["arpi"] + teamstats[key]["qwb"]
def removeBadWins(teamstats):
for key in teamstats:
# Initialize adjusted rpi
teamstats[key]["arpi"] = teamstats[key]["urpi"]
# Number of changes in an iteration
changes = 1
# Sum of rpi removed
rpisum = 0
# Number of weighted wins removed
wgp = 0
# Set with indices of removed games
removed = set()
while changes > 0:
changes = 0
# Check each win
for i, w in enumerate(teamstats[key]["w"]):
# Check if already removed
if i in removed:
continue
# Calculate game rpi
gamerpi, gp = calcGameRPI(teamstats, w, key, "w")
# Check if game needs to be removed
if gamerpi + 0.000001 < teamstats[key]["arpi"]:
removed.add(i)
changes += 1
rpisum += gamerpi
wgp += gp
# Update rpi
teamstats[key]["arpi"] = (teamstats[key]["urpi"] * teamstats[key]["wgp"] - rpisum) / (teamstats[key]["wgp"] - wgp)
def calcQWB(teamstats):
# Create dict for just rpi
rpi = dict()
for t in teamstats:
rpi[t] = teamstats[t]["arpi"]
# Sort rpi in descending order to determine qwb for each team
sortedrpi = sorted(rpi.items(), key=lambda kv: kv[1], reverse = True)
# Bonus for beating #1 team
bonus = QWBSTART
# Key = team; value = bonus for beating that team
qwb = dict()
for t in sortedrpi:
# Make sure bonus isn't negative
if bonus < 0:
bonus = 0
# Add bonus to dict
qwb[t[0]] = bonus
# Decrement bonus
bonus -= QWBSCALE
# Calculate QWB for each team
for key in teamstats:
# Initialize bonus to 0
teamstats[key]["qwb"] = 0
# Go through wins and add qwb for each win
for w in teamstats[key]["w"]:
if w[1] in qwb:
teamstats[key]["qwb"] += qwb[w[1]]
# Go through ot wins and add qwb for each win
for otw in teamstats[key]["otw"]:
if otw[1] in qwb:
teamstats[key]["qwb"] += (qwb[otw[1]] * OTWIN)
# Go through ot losses and add qwb for each (ot loss counts as OTLOSS wins)
for otl in teamstats[key]["otl"]:
if otl[1] in qwb:
teamstats[key]["qwb"] += (qwb[otl[1]] * OTLOSS)
# Go through ties and add qwb for each (tie counts as 0.5 wins)
for t in teamstats[key]["t"]:
if t[1] in qwb:
teamstats[key]["qwb"] += (qwb[t[1]] * 0.5)
# Divide qwb by weighted games played
teamstats[key]["qwb"] /= teamstats[key]["wgp"]
def calcGameRPI(teamstats, info, team, result):
if result == "w":
# Win percentage for that game is 1
gamerpi = WPWEIGHT + OWPWEIGHT * calcWPwo(teamstats, info[1], team) + OOWPWEIGHT * teamstats[info[1]]["owp"]
# Calculate rpi weighted for home/road as FIRSTWEIGHT/SECONDWEIGHT
if info[0] == "H":
weightedgamerpi = FIRSTWEIGHT * gamerpi
weightedgp = FIRSTWEIGHT
elif info[0] == "A":
weightedgamerpi = SECONDWEIGHT * gamerpi
weightedgp = SECONDWEIGHT
else:
weightedgamerpi = gamerpi
weightedgp = 1
elif result == "l":
# Win percentage for that game is 0
gamerpi = OWPWEIGHT * calcWPwo(teamstats, info[1], team) + OOWPWEIGHT * teamstats[info[1]]["owp"]
# Calculate rpi weighted for home/road as SECONDWEIGHT/FIRSTWEIGHT
if info[0] == "H":
weightedgamerpi = SECONDWEIGHT * gamerpi
weightedgp = SECONDWEIGHT
elif info[0] == "A":
weightedgamerpi = FIRSTWEIGHT * gamerpi
weightedgp = FIRSTWEIGHT
else:
weightedgamerpi = gamerpi
weightedgp = 1
elif result == "otw":
# Win percentage for that game is OTWIN
gamerpi = WPWEIGHT * OTWIN + OWPWEIGHT * calcWPwo(teamstats, info[1], team) + OOWPWEIGHT * teamstats[info[1]]["owp"]
# Calculate rpi weighted for home/road
if info[0] == "H":
weightedgamerpi = FIRSTWEIGHT * gamerpi
weightedgp = FIRSTWEIGHT
elif info[0] == "A":
weightedgamerpi = SECONDWEIGHT * gamerpi
weightedgp = SECONDWEIGHT
else:
weightedgamerpi = gamerpi
weightedgp = 1
# if info[0] == "H":
# weightedgamerpi = (OTWIN * FIRSTWEIGHT + OTLOSS * SECONDWEIGHT) * gamerpi
# weightedgp = OTWIN * FIRSTWEIGHT + OTLOSS * SECONDWEIGHT
# elif info[0] == "A":
# weightedgamerpi = (OTWIN * SECONDWEIGHT + OTLOSS * FIRSTWEIGHT) * gamerpi
# weightedgp = OTWIN * SECONDWEIGHT + OTLOSS * FIRSTWEIGHT
# else:
# weightedgamerpi = gamerpi
# weightedgp = 1
# weightedgamerpi = gamerpi
# weightedgp = 1
elif result == "otl":
# Win percentage for that game is OTLOSS
gamerpi = WPWEIGHT * OTLOSS + OWPWEIGHT * calcWPwo(teamstats, info[1], team) + OOWPWEIGHT * teamstats[info[1]]["owp"]
# Calculate rpi weighted for home/road
if info[0] == "H":
weightedgamerpi = SECONDWEIGHT * gamerpi
weightedgp = SECONDWEIGHT
elif info[0] == "A":
weightedgamerpi = FIRSTWEIGHT * gamerpi
weightedgp = FIRSTWEIGHT
else:
weightedgamerpi = gamerpi
weightedgp = 1
# if info[0] == "H":
# weightedgamerpi = (OTWIN * SECONDWEIGHT + OTLOSS * FIRSTWEIGHT) * gamerpi
# weightedgp = OTWIN * SECONDWEIGHT + OTLOSS * FIRSTWEIGHT
# elif info[0] == "A":
# weightedgamerpi = (OTWIN * FIRSTWEIGHT + OTLOSS * SECONDWEIGHT) * gamerpi
# weightedgp = OTWIN * FIRSTWEIGHT + OTLOSS * SECONDWEIGHT
# else:
# weightedgamerpi = gamerpi
# weightedgp = 1
# weightedgamerpi = gamerpi
# weightedgp = 1
else:
# Win percentage for that game is 0.5
gamerpi = WPWEIGHT * 0.5 + OWPWEIGHT * calcWPwo(teamstats, info[1], team) + OOWPWEIGHT * teamstats[info[1]]["owp"]
weightedgamerpi = gamerpi
weightedgp = 1
return weightedgamerpi, weightedgp
def calcRPI(teamstats):
# Calculate components for each team
calcWP(teamstats)
calcOWP(teamstats)
calcOOWP(teamstats)
# Calculate rpi for each team
for key in teamstats:
# Calculate rpi for each game
rpisum = 0
weightedgp = 0
# Calculate rpi for each win
for w in teamstats[key]["w"]:
gamerpi, gp = calcGameRPI(teamstats, w, key, "w")
weightedgp += gp
rpisum += gamerpi
# Calculate rpi for each loss
for l in teamstats[key]["l"]:
gamerpi, gp = calcGameRPI(teamstats, l, key, "l")
weightedgp += gp
rpisum += gamerpi
# Calculate rpi for each ot win
for otw in teamstats[key]["otw"]:
gamerpi, gp = calcGameRPI(teamstats, otw, key, "otw")
weightedgp += gp
rpisum += gamerpi
# Calculate rpi for each ot loss
for otl in teamstats[key]["otl"]:
gamerpi, gp = calcGameRPI(teamstats, otl, key, "otl")
weightedgp += gp
rpisum += gamerpi
# Calculate rpi for each tie
for t in teamstats[key]["t"]:
gamerpi, gp = calcGameRPI(teamstats, t, key, "t")
weightedgp += gp
rpisum += gamerpi
teamstats[key]["urpi"] = rpisum / weightedgp
teamstats[key]["wgp"] = weightedgp
def calcOOWP(teamstats):
for team in teamstats:
# Initialize opponent opponent winning percentage
teamstats[team]["oowp"] = 0
games = len(teamstats[team]["opponents"])
# Add opponents
for opp in teamstats[team]["opponents"]:
teamstats[team]["oowp"] += teamstats[opp]["owp"]
# Calculate weighted opponent opponent win percentage
teamstats[team]["oowp"] /= games
def countTeam(teamList, team):
count = 0
for tup in teamList:
if tup[1] == team:
count += 1
return count
def calcWPwo(teamstats, team, exclude):
# Excluding games
# Initialize winning percentage
wp = 0
oppgames = len(teamstats[team]["opponents"]) - teamstats[team]["opponents"].count(exclude)
# Add wins
wp += (len(teamstats[team]["w"]) - countTeam(teamstats[team]["w"], exclude))
# Add ot wins: OTWIN of a win and OTLOSS of a loss
wp += ((len(teamstats[team]["otw"]) - countTeam(teamstats[team]["otw"], exclude)) * OTWIN)
# Add ot losses: OTLOSS of a win and OTWIN of a loss
wp += ((len(teamstats[team]["otl"]) - countTeam(teamstats[team]["otl"], exclude)) * OTLOSS)
# Add ties: 0.5 of a win and 0.5 of a loss
wp += ((len(teamstats[team]["t"]) - countTeam(teamstats[team]["t"], exclude)) * 0.5)
# calculate win percentage
wp /= oppgames
return wp
def calcOWP(teamstats):
for team in teamstats:
# Initialize opponent winning percentage
teamstats[team]["owp"] = 0
games = len(teamstats[team]["opponents"])
# Add opponents
for opp in teamstats[team]["opponents"]:
# Have to manually calculate win percentage with games against current team removed
wp = calcWPwo(teamstats, opp, team)
teamstats[team]["owp"] += wp
# calculate opponent win percentage
teamstats[team]["owp"] /= games
def calcWP(teamstats):
for team in teamstats:
# Initialize winning percentage
teamstats[team]["wp"] = 0
games = len(teamstats[team]["opponents"])
# Add wins
teamstats[team]["wp"] += len(teamstats[team]["w"])
# Add ot wins: OTWIN of a win and OTLOSS of a loss
teamstats[team]["wp"] += (len(teamstats[team]["otw"]) * OTWIN)
# Add ot losses: OTLOSS of a win and OTWIN of a loss
teamstats[team]["wp"] += (len(teamstats[team]["otl"]) * OTLOSS)
# Add ties: 0.5 of a win and 0.5 of a loss
teamstats[team]["wp"] += (len(teamstats[team]["t"]) * 0.5)
# Calculate win percentage
teamstats[team]["wp"] /= games
def readGames(teamstats, filename):
# Open the spreadsheet and assign the first 2 sheets
# Replace with your xlsx file name
wb = openpyxl.load_workbook(filename)
firstsheet = wb.worksheets[0]
# Read in every game with the teams
g = 2
while g < firstsheet.max_row + 1:
# Skip exhibition games
marker = firstsheet.cell(row = g, column = 7).value.strip().lower()
if marker == 'ex' or marker == 'n3':
g += 1
continue
team1 = firstsheet.cell(row = g, column = 1).value.strip()
team1score = firstsheet.cell(row = g, column = 2).value
team2 = firstsheet.cell(row = g, column = 4).value.strip()
team2score = firstsheet.cell(row = g, column = 5).value
regulation = firstsheet.cell(row = g, column = 6).value
# Remove possible padding
if regulation is not None:
regulation = regulation.strip()
# Neutral site game?
if firstsheet.cell(row = g, column = 3).value.strip() == "vs":
neutral = True
else:
neutral = False
# Initialize if necessary
if team1 not in teamstats and "/" not in team1:
# Initialize team dict
teamstats[team1] = dict()
# Initialize comparisons won to 0
teamstats[team1]["pwr"] = 0
# Initialize wins, losses, ot wins, ot losses, and ties
teamstats[team1]["w"] = []
teamstats[team1]["l"] = []
teamstats[team1]["otw"] = []
teamstats[team1]["otl"] = []
teamstats[team1]["t"] = []
# Initialize list of opponents
teamstats[team1]["opponents"] = []
# Initialize list of future games
teamstats[team1]["toplay"] = []
if team2 not in teamstats and "/" not in team2:
# Initialize team dict
teamstats[team2] = dict()
# Initialize comparisons won to 0
teamstats[team2]["pwr"] = 0
# Initialize wins, losses, ot wins, ot losses, and ties
teamstats[team2]["w"] = []
teamstats[team2]["l"] = []
teamstats[team2]["otw"] = []
teamstats[team2]["otl"] = []
teamstats[team2]["t"] = []
# Initialize list of opponents
teamstats[team2]["opponents"] = []
# Initialize list of future games
teamstats[team2]["toplay"] = []
# Game hasn't been played yet
if team1score == '' or team1score is None or team2score == '' or team2score is None:
# update toplay
if neutral:
# check for in-season tournaments
if "/" not in team1:
teamstats[team1]["toplay"].append(["N", team2])
# check for in-season tournaments
if "/" not in team2:
teamstats[team2]["toplay"].append(["N", team1])
else:
# check for in-season tournaments
if "/" not in team1:
teamstats[team1]["toplay"].append(["A", team2])
# check for in-season tournaments
if "/" not in team2:
teamstats[team2]["toplay"].append(["H", team1])
g += 1
continue
# check to see winner
if team1score == team2score:
# update ties
if neutral:
teamstats[team1]["t"].append(["N", team2])
teamstats[team2]["t"].append(["N", team1])
else:
teamstats[team1]["t"].append(["A", team2])
teamstats[team2]["t"].append(["H", team1])
elif team1score > team2score and (regulation == '' or regulation is None):
# update wins and losses
if neutral:
teamstats[team1]["w"].append(["N", team2])
teamstats[team2]["l"].append(["N", team1])
else:
teamstats[team1]["w"].append(["A", team2])
teamstats[team2]["l"].append(["H", team1])
elif team1score < team2score and (regulation == '' or regulation is None):
# update wins and losses
if neutral:
teamstats[team1]["l"].append(["N", team2])
teamstats[team2]["w"].append(["N", team1])
else:
teamstats[team1]["l"].append(["A", team2])
teamstats[team2]["w"].append(["H", team1])
elif team1score > team2score:
# update ot wins and losses
if neutral:
teamstats[team1]["otw"].append(["N", team2])
teamstats[team2]["otl"].append(["N", team1])
else:
teamstats[team1]["otw"].append(["A", team2])
teamstats[team2]["otl"].append(["H", team1])
else:
# update ot wins and losses
if neutral:
teamstats[team1]["otl"].append(["N", team2])
teamstats[team2]["otw"].append(["N", team1])
else:
teamstats[team1]["otl"].append(["A", team2])
teamstats[team2]["otw"].append(["H", team1])
# Add opponent
teamstats[team1]["opponents"].append(team2)
teamstats[team2]["opponents"].append(team1)
# Increment counter for reading the spreadsheet
g += 1
def main():
# Mega dictionary with all info
# key = team name
# value = dictionary with: win pct (float), opponent win pct (float), opponent opponent win pct (float)
# quality wins bonus (float), wins (list of opponents beaten), losses (list of opponents lost to),
# overtime wins (list of opponents beaten in ot), pairwise comparisons won (int),
# opponents (list of opponents), weighted games played (float)
teamstats = dict()
readGames(teamstats, "../NCAA games.xlsx")
calcRPI(teamstats)
removeBadWins(teamstats)
calcQWB(teamstats)
calcFinalRPI(teamstats)
calcPWR(teamstats)
# For output in order of the pairwise
pwr = dict()
for t in teamstats:
pwr[t] = (teamstats[t]["pwr"], teamstats[t]["rpi"])
sortedpwr = sorted(pwr.items(), key=lambda kv: (kv[1][0], kv[1][1]), reverse = True)
outputPWR(teamstats, sortedpwr)
return sortedpwr
if __name__ == "__main__":
main()