-
Notifications
You must be signed in to change notification settings - Fork 4
/
parseretrosheet.py
executable file
·2274 lines (2089 loc) · 99.9 KB
/
parseretrosheet.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
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
#!/usr/bin/python3
import re, sys, copy, getopt, os, os.path
import unittest
import typing
import cProfile
import copy
import multiprocessing
from enum import IntEnum
class Verbosity(IntEnum):
quiet = 0
normal = 1
verbose = 2
doParallel = True
#TODO - use __all__
#TODO - do something with these
verbosity = Verbosity.normal
skipOutput = False
stopOnFirstError = False
sortByYear = False
knownBadGames = ['WS2196605270', 'MIL197107272', 'MON197108040', 'NYN198105090', 'SEA200709261', 'MIL201304190', 'SFN201407300', 'BAL201906250']
class GameRuleOptions:
def __init__(self):
self.innings = 9
self.runnerStartsOnSecondInExtraInnings = False
positionToBase = {1:-1, 2:-1, 3:1, 4:2, 5:3, 6:2, 7:-1, 8:-1, 9:-1}
# TODO - make this a real class I guess
GameSituationKey = typing.Tuple[int, bool, int, typing.Tuple[int, int, int], int]
class GameSituation:
def __init__(self):
self.inning = 1
self.isHome = False
self.outs = 0
# Runners on first, second, third
self.runners : typing.List[int] = [0, 0, 0]
# Number of runs the currently batting team is ahead by (can be negative)
self.curScoreDiff = 0
def copy(self):
return GameSituation.fromKey(self.getKey())
def __str__(self):
return "inning: %d isHome: %d outs: %d curScoreDiff: %d runners: %s" % (self.inning, self.isHome, self.outs, self.curScoreDiff, self.runners)
def __repr__(self):
return str(self)
def getKey(self) -> GameSituationKey:
return (self.inning, self.isHome, self.outs, (self.runners[0], self.runners[1], self.runners[2]), self.curScoreDiff)
def __eq__(self, other):
return self.getKey() == other.getKey()
@staticmethod
def fromKey(key: GameSituationKey) -> 'GameSituation':
situation = GameSituation()
situation.inning = key[0]
situation.isHome = key[1]
situation.outs = key[2]
situation.runners = [key[3][0], key[3][1], key[3][2]]
situation.curScoreDiff = key[4]
return situation
def nextInningIfThreeOuts(self, runnerStartsOnSecondInExtraInnings, innings):
if (self.outs >= 3):
if (self.isHome):
self.isHome = False
self.inning = self.inning + 1
else:
self.isHome = True
self.outs = 0
self.runners = [0, 1 if runnerStartsOnSecondInExtraInnings and self.inning > innings else 0, 0]
self.curScoreDiff = -1 * self.curScoreDiff
# returns True, False, or None if it's still tied.
def isHomeWinning(self):
if (self.curScoreDiff == 0):
# This game must have been tied when it stopped.
return None
if (self.isHome):
return self.curScoreDiff > 0
else:
return self.curScoreDiff < 0
class GameSituationKeyAndNextPlayLine(typing.NamedTuple):
situationKey: GameSituationKey
playLine: str
def __str__(self):
return f"situationKey: {self.situationKey} playLine: {self.playLine}"
def __repr__(self):
return self.__str__()
# TODO - write this and use it
def parseBatterEvent(batterEvent: str):
pass
def parseFilesParallel(fileNames: typing.Iterable[str]) -> typing.Tuple[int, typing.Iterable['Report']]:
global verbosity
verbosity = parseFilesParallel.localVerbosity
clonedReportsToRun = [copy.deepcopy(x) for x in parseFilesParallel.originalReportsToRun]
numGames = 0
for fileName in fileNames:
with open(fileName, 'r', encoding='latin-1') as eventFile:
if verbosity >= Verbosity.normal:
print(fileName)
numGames += parseFile(eventFile, fileName, clonedReportsToRun)[0]
return (numGames, clonedReportsToRun)
def parseFile(f: typing.IO[str], eventFileName: str, reports: typing.Iterable['Report']) -> typing.Tuple[int, typing.Iterable['Report']]:
numGames = 0
inGame = False
curGameSituation : GameSituation = GameSituation()
gameSituationKeys : typing.List[GameSituationKey] = []
playLines : typing.List[str] = []
curId : str = ""
_, eventFileExtension = os.path.splitext(eventFileName)
isPlayoffs = eventFileExtension.upper() == '.EVE'
gameRuleOptions = GameRuleOptions()
for line in f.readlines():
if (not(inGame)):
if (line.startswith("id,")):
curId = line[3:].strip()
curGameSituation = GameSituation()
gameSituationKeys = []
gameSituationKeys.append(curGameSituation.getKey())
playLines = []
inGame = True
# In 2020 a runner started on second base in extra innings, but not in playoff games
curYear = int(curId[3:7])
gameRuleOptions.runnerStartsOnSecondInExtraInnings = (curYear == 2020 and not isPlayoffs)
gameRuleOptions.innings = 9
if eventFileName == "2020NLW1.EVE":
print(f"isPlayoffs: {isPlayoffs}, runneronsecond: {gameRuleOptions.runnerStartsOnSecondInExtraInnings}")
else:
if (line.startswith("id,")):
assert curId != ""
numGames = numGames + 1
callReportsProcessedGame(gameSituationKeys, curGameSituation, reports, curId, playLines, gameRuleOptions)
if (verbosity == Verbosity.verbose):
print("NEW GAME")
curGameSituation = GameSituation()
curId = line[3:].strip()
gameSituationKeys = []
gameSituationKeys.append(curGameSituation.getKey())
playLines = []
# In 2020 a runner started on second base in extra innings, but not in playoff games
curYear = int(curId[3:7])
gameRuleOptions.runnerStartsOnSecondInExtraInnings = (curYear == 2020 and not isPlayoffs)
gameRuleOptions.innings = 9
else:
if (line.startswith("play")):
try:
parsePlay(line, curGameSituation, gameRuleOptions)
except AssertionError:
if verbosity >= Verbosity.normal:
print("Error in game " + curId)
if curId in knownBadGames:
print("known bad game")
if curId not in knownBadGames:
raise Exception(f"Error in game {curId}")
else:
# We're just gonna punt and ignore the error
inGame = False
else:
curGameSituationKey = curGameSituation.getKey()
if (curGameSituationKey not in gameSituationKeys):
gameSituationKeys.append(curGameSituationKey)
playLines.append(line.strip())
elif (line.startswith("info,innings,")):
gameRuleOptions.innings = int(line[len("info,innings,"):])
if inGame:
assert curId != ""
numGames = numGames + 1
callReportsProcessedGame(gameSituationKeys, curGameSituation, reports, curId, playLines, gameRuleOptions)
return (numGames, reports)
def callReportsProcessedGame(gameSituationKeys: typing.List[GameSituationKey], finalGameSituation: GameSituation, reports: typing.Iterable['Report'], curId: str, playLines: typing.List[str], gameRuleOptions: GameRuleOptions) -> None:
# Don't include the last situation in the list of keys, because it's one after the last inning probably
if (len(gameSituationKeys) > 0 and gameSituationKeys[-1] == finalGameSituation.getKey()):
gameSituationKeys = gameSituationKeys[:-1]
assert len(gameSituationKeys) == len(playLines)
situationKeysAndNextPlayLines : typing.List[GameSituationKeyAndNextPlayLine] = [GameSituationKeyAndNextPlayLine(key, line) for (key, line) in zip(gameSituationKeys, playLines)]
for report in reports:
report.processedGame(curId, finalGameSituation, situationKeysAndNextPlayLines, gameRuleOptions)
def batterToFirst(runnerDests) -> None:
runnerDests['B'] = 1
if 1 in runnerDests:
runnerDests[1] = 2
if 2 in runnerDests:
runnerDests[2] = 3
if 3 in runnerDests:
runnerDests[3] = 4
else:
if 3 in runnerDests:
runnerDests[3] = 3
else:
if 2 in runnerDests:
runnerDests[2] = 2
if 3 in runnerDests:
runnerDests[3] = 3
def characterToBase(ch) -> int:
if ch == 'H':
return 4
return int(ch)
reCache = {}
def getRe(pattern):
global reCache
oldRe = reCache.get(pattern, None)
if oldRe is not None:
return oldRe
reCache[pattern] = re.compile(pattern)
return reCache[pattern]
class PlayLineInfo(typing.NamedTuple):
inning: int
isHome: bool
playerId: str
countWhenPlayHappened: str
pitchesString: str
playString: str
@staticmethod
def fromLine(line: str) -> 'PlayLineInfo':
# decription of the format is at http://www.retrosheet.org/eventfile.htm
playMatch = getRe(r'^play,\s?(\d+),\s?([01]),(.*?),(.*?),(.*?),(.*)$').match(line)
assert playMatch
return PlayLineInfo(inning=int(playMatch.group(1)), isHome=(int(playMatch.group(2))==1), playerId=playMatch.group(3), countWhenPlayHappened=playMatch.group(4), pitchesString=playMatch.group(5), playString=playMatch.group(6))
def parsePlay(line: str, gameSituation: GameSituation, gameRuleOptions: GameRuleOptions):
# decription of the format is at http://www.retrosheet.org/eventfile.htm
playLineInfo = PlayLineInfo.fromLine(line)
# if runnerDests[x] = 0, runner (or batter) is out
# if runnerDests[x] = 4, runner (or batter) scores
# if runnerDests['B'] = -1, batter is still up
# if runnerDests['B'] = -2, undetermined
runnerDests = {}
outAtBase = []
defaultBatterBase = -1
beginningRunners = []
runnersDefaultStayStill = False
if (gameSituation.runners[0]):
runnerDests[1] = -1
beginningRunners.append(1)
if (gameSituation.runners[1]):
runnerDests[2] = -1
beginningRunners.append(2)
if (gameSituation.runners[2]):
runnerDests[3] = -1
beginningRunners.append(3)
if (verbosity == Verbosity.verbose):
print("Game situation is: %s" % gameSituation)
print(line[0:-1])
assert gameSituation.inning == playLineInfo.inning
assert gameSituation.isHome == playLineInfo.isHome
playString = playLineInfo.playString
# Strip !'s, #'s, and ?'s
playString = playString.replace('!', '').replace('#', '').replace('?', '')
playArray = playString.split('.')
assert len(playArray) <= 2
# Deal with the first part of the string.
batterEvents = playArray[0].split(';')
for batterEvent in batterEvents:
batterEvent = batterEvent.strip()
doneParsingEvent = False
simpleHitMatch = getRe(r"^([SDTH])(?:\d|/)").match(batterEvent)
simpleHitMatch2 = getRe(r"^([SDTH])\s*$").match(batterEvent)
if (simpleHitMatch or simpleHitMatch2):
if (simpleHitMatch):
typeOfHit = simpleHitMatch.group(1)
else:
typeOfHit = simpleHitMatch2.group(1)
if (typeOfHit == 'S'):
runnerDests['B'] = 1
elif (typeOfHit == 'D'):
runnerDests['B'] = 2
elif (typeOfHit == 'T'):
runnerDests['B'] = 3
elif (typeOfHit == 'H'):
runnerDests['B'] = 4
for runner in runnerDests:
runnerDests[runner] = 4
# Sometimes these aren't specified - assume runners don't move
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('HR')):
runnerDests['B'] = 4
for runner in runnerDests:
if (runner != 'B'):
runnerDests[runner] = 4
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('K')):
runnerDests['B'] = 0
runnersDefaultStayStill = True
if (batterEvent.startswith('K+') or batterEvent.startswith('K23+')):
if batterEvent.startswith('K+'):
tempEvent = batterEvent[2:]
else:
tempEvent = batterEvent[4:]
if (tempEvent.startswith('SB')):
dest = characterToBase(tempEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
elif (tempEvent.startswith('CS')):
if (getRe(r'^CS.\([^)]*?E.*?\)').match(tempEvent)):
# Error, so no out.
dest = characterToBase(tempEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
else:
dest = characterToBase(tempEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = 0
elif (tempEvent.startswith('POCS')):
if (getRe(r'^POCS.\([^)]*?E.*?\)').match(tempEvent)):
# Error, so no out.
dest = characterToBase(tempEvent[4])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
else:
dest = characterToBase(tempEvent[4])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = 0
elif (tempEvent.startswith('PO')):
if (getRe(r'^PO.\([^)]*?E.*?\)').match(tempEvent)):
# Error, so no out.
pass
else:
base = characterToBase(tempEvent[2])
assert (base == 1 or base == 2 or base == 3)
runnerDests[base] = 0
elif (tempEvent.startswith('PB') or tempEvent.startswith('WP')):
pass
# OBA is used instead of OA in BOS196704300
elif (tempEvent.startswith('OA') or tempEvent.startswith('OBA') or tempEvent.startswith('DI')):
pass
elif (tempEvent.startswith('E')):
pass
else:
if verbosity >= Verbosity.normal:
print("ERROR - unrecognized K+ event: %s" % tempEvent)
assert False
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('NP')):
# No play
runnerDests['B'] = -1
for runner in runnerDests:
if (runner != 'B'):
runnerDests[runner] = runner
doneParsingEvent = True
if (not doneParsingEvent):
if ((batterEvent.startswith('W') and not batterEvent.startswith('WP')) or batterEvent.startswith('IW') or batterEvent.startswith('I')):
# Walk
runnerDests['B'] = 1
batterToFirst(runnerDests)
if (batterEvent.startswith('W+') or batterEvent.startswith('IW+') or batterEvent.startswith('I+')):
tempEvent = batterEvent[2:]
if (batterEvent.startswith('IW+')):
tempEvent = batterEvent[3:]
if (tempEvent.startswith('SB')):
sbArray = tempEvent.split(';')
for entry in sbArray:
dest = characterToBase(entry[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
elif (tempEvent.startswith('CS')):
if (getRe(r'^CS.\([^)]*?E.*?\)').match(tempEvent)):
# There was an error, so not an out.
dest = characterToBase(tempEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
else:
dest = characterToBase(tempEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = 0
elif (tempEvent.startswith('POCS')):
dest = characterToBase(tempEvent[4])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = 0
elif (tempEvent.startswith('PO')):
base = characterToBase(tempEvent[2])
assert (base == 1 or base == 2 or base == 3)
runnerDests[base] = 0
elif (tempEvent.startswith('PB') or tempEvent.startswith('WP')):
pass
elif (tempEvent.startswith('OA') or tempEvent.startswith('DI')):
pass
elif (tempEvent.startswith('E')):
runnerDests['B'] = 1
else:
if verbosity >= Verbosity.normal:
print("ERROR - unrecognized W+ or IW+ event: %s" % tempEvent)
assert False
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('HP')):
# Hit by pitch
batterToFirst(runnerDests)
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('DGR')):
# Ground-rule double
runnerDests['B'] = 2
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('C/') or batterEvent == 'C'):
# Catcher's interference
runnerDests['B'] = 1
doneParsingEvent = True
runnersDefaultStayStill = True
if (not doneParsingEvent):
if (batterEvent.startswith('E')):
# Error letting the runner reach base
runnerDests['B'] = 1 # may be overridden
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('FC')):
# Fielder's choice. Batter goes to first unless overridden
runnerDests['B'] = 1 # may be overridden
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('FLE')):
# Error on fly foul ball. Nothing happens.
runnerDests['B'] = -1
for runner in runnerDests:
if (runner != 'B'):
runnerDests[runner] = runner
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('SHE')):
# Error on sac hit (bunt). Advances given explicitly
runnerDests['B'] = -2
doneParsingEvent = True
if (not doneParsingEvent):
# double or triple play
doublePlayMatch = getRe(r'^\d+\((\d|B)\)(?:\d*\((\d|B)\))?(?:\d*\((\d|B)\))?').match(batterEvent)
if (doublePlayMatch and ('DP' in batterEvent or 'TP' in batterEvent)):
if (verbosity == Verbosity.verbose):
print("double/triple play")
# The batter is out if the last character is a number, not ')'
# (unless there's a "(B)" in the string
doublePlayString = batterEvent.split('/')[0]
if (doublePlayString[-1:] != ')'):
runnerDests['B'] = 0
else:
runnerDests['B'] = 1
if (doublePlayMatch.group(1) == 'B'):
runnerDests['B'] = 0
else:
runnerDests[int(doublePlayMatch.group(1))] = 0
if (doublePlayMatch.group(2)):
if (doublePlayMatch.group(2) == 'B'):
runnerDests['B'] = 0
else:
runnerDests[int(doublePlayMatch.group(2))] = 0
if (doublePlayMatch.group(3)):
if (doublePlayMatch.group(3) == 'B'):
runnerDests['B'] = 0
else:
runnerDests[int(doublePlayMatch.group(3))] = 0
# Unfortunately, since it could be a caught fly ball and throw
# out, we have to assume runners don't go anywhere.
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
weirdDoublePlayMatch = getRe(r'^\d+(/.*?)*/.?[DT]P').match(batterEvent)
if (weirdDoublePlayMatch):
# This is a double play. The specifics of who's out will
# come later.
if (verbosity == Verbosity.verbose):
print("weird double/triple play")
runnerDests['B'] = 0
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
simpleOutMatch = getRe(r'^\d\D').match(batterEvent)
if (simpleOutMatch and "/FO" not in batterEvent or (len(batterEvent) == 1 and (int(batterEvent) >= 1 and int(batterEvent) <= 9))):
if (verbosity == Verbosity.verbose):
print("simple out")
if (getRe(r'^\dE').match(batterEvent)):
if (verbosity == Verbosity.verbose):
print("error")
runnerDests['B'] = 1
else:
runnerDests['B'] = 0
# runners don't move unless explicit
for runner in runnerDests:
if (runner != 'B'):
runnerDests[runner] = runner
doneParsingEvent = True
if (not doneParsingEvent):
putOutMatch = getRe(r'^\d*(\d).*?(?:\((.)\))?').match(batterEvent)
if (putOutMatch):
if (verbosity == Verbosity.verbose):
print("Got a putout")
if (getRe(r'\d?E\d').search(batterEvent)):
# Error on the play - batter goes to first unless
# explicit
runnerDests['B'] = 1
else:
foundBatterDest = False
if ("/FO" in batterEvent):
# Force out - this means the thing in parentheses
# is the runner who is out.
if (verbosity == Verbosity.verbose):
print("force out")
assert putOutMatch.group(2)
runnerDests[int(putOutMatch.group(2))] = 0
else:
# Determine from putOutMatch.group(1) (who made out) and
# putOutMatch.group(2) (where out is) which base the out was at.
if (putOutMatch.group(2)):
runnerOut = putOutMatch.group(2)
if runnerOut != 'B':
runnerOut = int(runnerOut)
else:
foundBatterDest = True
runnerDests[runnerOut] = 0
else:
# If we don't know what base it was at, assume first base.
if (positionToBase[int(putOutMatch.group(1))] == -1):
outAtBase.append(1)
else:
outAtBase.append(positionToBase[int(putOutMatch.group(1))])
if (not foundBatterDest):
runnerDests['B'] = -2
defaultBatterBase = 1
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('BK')):
# Balk
runnerDests['B'] = -1
# Advance runners
# actually, this should be explicit, game NYA196209092
# has a balk where the runner doesn't advance from
# second??
#for runner in runnerDests:
# if (runner != 'B'):
# runnerDests[runner] = runner + 1
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('CS')):
# Caught stealing
if (getRe(r'^CS.\([^)]*?E.*?\)').match(batterEvent)):
# There was an error, so not an out.
if (verbosity == Verbosity.verbose):
print("no caught stealing")
dest = characterToBase(batterEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
else:
dest = characterToBase(batterEvent[2])
assert (dest == 2 or dest == 3 or dest == 4)
outAtBase.append(dest)
if ('B' not in runnerDests):
runnerDests['B'] = -1
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('SB')):
# stolen base (could be multiple)
dest = characterToBase(batterEvent[2])
assert(dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
if ('B' not in runnerDests):
runnerDests['B'] = -1
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('DI')):
# defensive indifference. runners resolved later
if ('B' not in runnerDests):
runnerDests['B'] = -1
for runner in runnerDests:
if (runner != 'B' and runnerDests[runner] == -1):
runnerDests[runner] = runner
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('OA')):
# runner advances somehow (resolved later)
if ('B' not in runnerDests):
runnerDests['B'] = -1
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('PB') or batterEvent.startswith('WP')):
# Passed ball or wild pitch
if ('B' not in runnerDests):
runnerDests['B'] = -1
for runner in runnerDests:
if (runner != 'B'):
runnerDests[runner] = runner
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('POCS')):
# Pick-off (and caught stealing)
if (getRe(r'^POCS.\(.*?E.*?\)').match(batterEvent)):
# There was an error, so not an out
dest = characterToBase(batterEvent[4])
assert (dest == 2 or dest == 3 or dest == 4)
runnerDests[dest - 1] = dest
else:
dest = characterToBase(batterEvent[4])
assert (dest == 2 or dest == 3 or dest == 4)
outAtBase.append(dest)
runnersDefaultStayStill = True
if ('B' not in runnerDests):
runnerDests['B'] = -1
doneParsingEvent = True
if (not doneParsingEvent):
if (batterEvent.startswith('PO')):
# Pick-off
if (getRe(r'^PO.\([^)]*?E.*?\)').match(batterEvent)):
# Error, so no out.
pass
else:
base = characterToBase(batterEvent[2])
assert (base == 1 or base == 2 or base == 3)
runnerDests[base] = 0
if ('B' not in runnerDests):
runnerDests['B'] = -1
runnersDefaultStayStill = True
doneParsingEvent = True
if (not doneParsingEvent):
if verbosity >= Verbosity.normal:
print("ERROR - couldn't parse event %s" % batterEvent)
print("line is: %s" % line[0:-1])
return
# Now parse runner stuff.
if (len(playArray) > 1):
runnerArray = playArray[1].split(';')
runnerArray = [x.strip() for x in runnerArray]
for runnerItem in runnerArray:
if (len(runnerItem) != 3):
assert (runnerItem[3] == '(')
if (runnerItem[0] == 'B'):
runner = 'B'
else:
runner = int(runnerItem[0])
assert (runner >= 1 and runner <= 3)
base = characterToBase(runnerItem[2])
assert (base >= 1 and base <= 4)
if (runnerItem[1] == '-'):
if (runner != 'B' and base != 0):
# This looks weird, but sometimes a runner can go to the
# same base (a little redundant, but OK)
assert (typing.cast(int, runner) <= base)
runnerDests[runner] = base
elif (runnerItem[1] == 'X'):
# See if there was an error.
if (getRe(r'^...(?:\([^)]*?\))*\(\d*E.*\)').match(runnerItem)):
#if (runner == 'B'):
# It seems to be the case that if it is the batter
# doing stuff, in this case the runner is safe
#runnerDests[runner] = base
# So this is probably an error. See if the intervening
# parentheses indicate an out
if (getRe(r'^....*?\(\d*(/TH)?\).*?\(\d*E.*\)').match(runnerItem) or getRe(r'^....*?\(\d*E.*\)\(\d*\)').match(runnerItem)):
# Yup, this is really an out.
runnerDests[runner] = 0
else:
# Nope, so runner is safe.
if (runner != 'B' and base != 0):
# This looks weird, but sometimes a runner can go to the
# same base (a little redundant, but OK)
assert (typing.cast(int, runner) <= base)
runnerDests[runner] = base
else:
runnerDests[runner] = 0
else:
assert False
unresolvedRunners = [runner for runner in runnerDests if runnerDests[runner] == -1]
if ('B' in unresolvedRunners):
unresolvedRunners.remove('B')
if (runnerDests['B'] == -2):
unresolvedRunners.append(0)
# See if there's an out at a base.
for outBase in outAtBase:
if (outBase == 'B'):
runnerDests['B'] = 0
unresolvedRunners.remove(0)
else:
# Find the closest unresolved runner behind that base.
possibleRunners = [runner for runner in unresolvedRunners if runner < outBase]
curRunner = max(possibleRunners)
if (verbosity == Verbosity.verbose):
print("picked runner %d" % curRunner)
if (curRunner == 0):
runnerDests['B'] = 0
unresolvedRunners.remove(0)
else:
runnerDests[curRunner] = 0
unresolvedRunners.remove(curRunner)
unresolvedRunners = [runner for runner in runnerDests if runnerDests[runner] == -1]
if (runnerDests['B'] == -2):
if (defaultBatterBase != -1):
if (verbosity == Verbosity.verbose):
print("using defaultBatterBase of %d" % defaultBatterBase)
runnerDests['B'] = defaultBatterBase
else:
if verbosity >= Verbosity.normal:
print("ERROR - unresolved batter!")
assert False
# 'B' going to -1 means nothing happens, so don't consider that.
if ('B' in unresolvedRunners):
unresolvedRunners.remove('B')
if (len(unresolvedRunners) > 0):
# We're OK if there will be three outs.
outs = gameSituation.outs
for runner in runnerDests:
if (runnerDests[runner] == 0):
outs = outs + 1
if (outs < 3):
if (runnersDefaultStayStill):
for runner in unresolvedRunners:
runnerDests[runner] = runner
else:
if verbosity >= Verbosity.normal:
print("ERROR - unresolved runners %s!" % unresolvedRunners)
print("runnerDests: %s" % (runnerDests))
assert False
# Check that no new entries to runnerDests
newRunners = [runner for runner in runnerDests if runner not in beginningRunners]
if (verbosity == Verbosity.verbose):
print("runnerDests: %s" % (runnerDests))
if ('B' not in newRunners):
if verbosity >= Verbosity.normal:
print("ERROR - don't know what happened to B!")
assert False
else:
newRunners.remove('B')
if (len(newRunners) > 0):
if verbosity >= Verbosity.normal:
print("ERROR - picked up extra runners %s!" % newRunners)
assert False
newRunners = [0, 0, 0]
# Deal with runnerDests
for runner in runnerDests:
if (runnerDests[runner] == 0):
gameSituation.outs += 1
elif (runnerDests[runner] == 4):
gameSituation.curScoreDiff += 1
elif (runnerDests[runner] == -1):
# Either we're the batter, and nothing happens, or
# we don't know what happens, and it doesn't matter because there
# are three outs.
pass
else:
if (newRunners[runnerDests[runner] - 1] == 1):
if verbosity >= Verbosity.normal:
print("ERROR - already a runner at base %d!" % runnerDests[runner])
assert False
newRunners[runnerDests[runner] - 1] = 1
gameSituation.runners = newRunners
gameSituation.nextInningIfThreeOuts(gameRuleOptions.runnerStartsOnSecondInExtraInnings, gameRuleOptions.innings)
# We're done - the information is "returned" in gameSituation
class BallStrikeCount(typing.NamedTuple):
balls: int
strikes: int
def __str__(self):
return f"{self.balls} balls, {self.strikes} strikes"
# This is what gets serialized to the file, so make it look like a tuple
def __repr__(self):
return f"({self.balls}, {self.strikes})"
def addBall(self) -> 'BallStrikeCount':
return BallStrikeCount(self.balls + 1, self.strikes)
def addStrike(self) -> 'BallStrikeCount':
return BallStrikeCount(self.balls, self.strikes + 1)
def assertOnlySingleCharacterStringsInSet(s : typing.Set[str]) -> None:
for x in s:
assert(len(x) == 1)
# This is surprisingly complicated because there's a lot of extraneous stuff in here.
# Ignore irrelevant stuff as well as the final result of a pitch (if it goes in play)
BALL_STRIKE_IGNORE_CHARS : typing.Set[str] = set([x for x in '!#?+*.123>HNXY '])
assertOnlySingleCharacterStringsInSet(BALL_STRIKE_IGNORE_CHARS)
BALL_STRIKE_BALLS : typing.Set[str] = set([x for x in 'BIPV'])
assertOnlySingleCharacterStringsInSet(BALL_STRIKE_BALLS)
BALL_STRIKE_STRIKES : typing.Set[str] = set([x for x in 'CKLMOQST'])
assertOnlySingleCharacterStringsInSet(BALL_STRIKE_STRIKES)
BALL_STRIKE_FOUL_BALLS : typing.Set[str] = set([x for x in 'FR'])
assertOnlySingleCharacterStringsInSet(BALL_STRIKE_FOUL_BALLS)
def getBallStrikeCountsFromPitches(pitches: str) -> typing.List[BallStrikeCount]:
counts = [BallStrikeCount(0, 0)]
for pitch in pitches.upper():
if pitch in BALL_STRIKE_IGNORE_CHARS:
continue
lastCount = counts[-1]
# For performance, check in rough order of frequency
if pitch in BALL_STRIKE_STRIKES:
counts.append(lastCount.addStrike())
elif pitch in BALL_STRIKE_BALLS:
counts.append(lastCount.addBall())
elif pitch in BALL_STRIKE_FOUL_BALLS:
if lastCount.strikes != 2:
counts.append(lastCount.addStrike())
# TODO - actually go through these exceptions?
elif pitch == 'U' or pitch == 'Z' or pitch == 'G' or pitch == '\\' or pitch == "`" or pitch == "8" or pitch == "A" or True:
# sigh, just throw this one out I guess
# "BZ" is used in 1988CHA.EVA, pretty sure it's supposed to be an X, but skip it
# TODO - add exceptions
# "FFFGFX" is used in 1989BAL.EVA, must be some kind of foul ball? (ended on 0-2 count)
# "\BBSBSX" is used in 1989BOS.EVA, probably should just ignore it (ended on 3-2 count)
# "11FB``PFBF1X`" is used in 1989CHA.EVA, ...??
# "BBB8FB" is used in 1989DET.EVA, ...??
# "CBABX" is used in 1989MIL.EVA
# TODO - contact retrosheet?
if pitch != 'U':
if verbosity >= Verbosity.normal:
print(f"Unknown pitch {pitch} in {pitches}, skipping")
return [BallStrikeCount(0, 0)]
else:
assert False, "Unexpected pitch character " + str(pitch) + " in " + str(pitches)
return counts
class Report:
# game_id is the Retrosheet game id for the game. year_from_game_id() will return the year the game was played in.
# final_game_situation is the situation _after_ the last play of the game. Beware - for a 9 inning game
# where the visiting team wins this will be in the top of the 10th inning with 0 outs. But for a 9 inning game
# where the home team wins on a walkoff this will be in the bottom of the 9th.
# situations is the list of the situations at the _start_ of every play. So the last value here will be the
# situation before the final plate appearance of the game.
# play_lines is the list of plays in the game - there are as many of these as entries in the situations slice.
def processedGame(self, gameId: str, finalGameSituation: GameSituation, situationKeysAndPlayLines: typing.List[GameSituationKeyAndNextPlayLine], gameRuleOptions: GameRuleOptions) -> None:
raise Exception(f"{type(self).__name__} must override processedGame!")
def clearStats(self) -> None:
pass
def mergeInto(self, other: 'Report') -> None:
raise Exception(f"{type(self).__name__} must override mergeInto to support parallel processing!")
def supportsParallelProcessing(self) -> bool:
return True
def doneWithYear(self, year: str) -> None:
assert sortByYear, "doneWithYear called but sortByYear is false!"
def doneWithAll(self) -> None:
assert not sortByYear, "doneWithAll called but sortByYear is true!"
class StatsReport(Report):
def __init__(self):
super().__init__()
self.stats = {}
def clearStats(self) -> None:
self.stats = {}
def shouldProcessGame(self, situationKeysAndPlayLines: typing.List[GameSituationKeyAndNextPlayLine], gameRuleOptions: GameRuleOptions) -> bool:
# In 2020 some games (doubleheaders) were played with only 7 innings, skip these
# to avoid messing up statistics.
if gameRuleOptions.innings != 9:
return False
# In 2020 extra innings started a runner on second base, which messes up
# statistics. If this rule continues we should figure out how to handle this,
# but for now, skip these games.
# don't use finalGameSituation here, because if the visiting team wins a normal 9 inning game
# finalGameSituation will be the top of the 10th inning (with 0 outs)
lastRealSituation = GameSituation.fromKey(situationKeysAndPlayLines[-1].situationKey)
if gameRuleOptions.runnerStartsOnSecondInExtraInnings and lastRealSituation.inning > 9:
return False
return True
def reportFileName(self) -> str:
raise Exception(f"{type(self).__name__} must override reportFileName!")
def doneWithYear(self, year: str) -> None:
super().doneWithYear(year)
outputFile = open('statsyears/' + self.reportFileName() + '.' + str(year), 'w')
statKeys = list(self.stats.keys())
statKeys.sort()
for key in statKeys:
outputFile.write("%s: %s\n" % (key, self.stats[key]))
self.writeExtraInfo(outputFile, key, self.stats[key])
outputFile.close()
def doneWithAll(self) -> None:
super().doneWithAll()
outputFile = open(self.reportFileName(), 'w')
statKeys = list(self.stats.keys())
statKeys.sort()
for key in statKeys:
outputFile.write("%s: %s\n" % (key, self.stats[key]))
self.writeExtraInfo(outputFile, key, self.stats[key])
outputFile.close()
def writeExtraInfo(self, outputFile, key, value) -> None:
pass
class StatsWinExpectancyReport(StatsReport):
def reportFileName(self) -> str:
return "stats"
def _addSituationKey(self, situationKey: typing.Tuple[typing.Any], isWin: bool):
if (situationKey in self.stats):
(numWins, numSituations) = self.stats[situationKey]
numSituations = numSituations + 1
if (isWin):
numWins = numWins + 1
self.stats[situationKey] = (numWins, numSituations)
else:
numWins = 1 if isWin else 0
self.stats[situationKey] = (numWins, 1)
def mergeInto(self, other: 'StatsWinExpectancyReport') -> None:
for key in self.stats:
if key in other.stats:
otherValue = other.stats[key]
thisValue = self.stats[key]
other.stats[key] = (otherValue[0] + thisValue[0], otherValue[1] + thisValue[1])
else:
other.stats[key] = self.stats[key]
# Maps a tuple (inning, isHome, outs, (runner on 1st, runner on 2nd, runner on 3rd), curScoreDiff) to a tuple of
# (number of wins, number of situations)
def processedGame(self, gameId: str, finalGameSituation: GameSituation, situationKeysAndPlayLines: typing.List[GameSituationKeyAndNextPlayLine], gameRuleOptions: GameRuleOptions) -> None:
if skipOutput:
return
if not self.shouldProcessGame(situationKeysAndPlayLines, gameRuleOptions):
return
# Add gameKeys to stats
# Check the last situation to see who won.
homeWon = finalGameSituation.isHomeWinning()
if (homeWon is None):
# This game must have been tied when it stopped. Don't count
# these stats.
return
for situationKeyOriginal in [x.situationKey for x in situationKeysAndPlayLines]:
isHomeInning = situationKeyOriginal[1]
isWin = (isHomeInning and homeWon) or (not isHomeInning and not homeWon)
#TODO this is probably slow?
situationKeyList = list(situationKeyOriginal)
situationKeyList[1] = 1 if isHomeInning else 0
situationKey = tuple(situationKeyList)
self._addSituationKey(situationKey, isWin)
class StatsWinExpectancyWithBallsStrikesReport(StatsWinExpectancyReport):
def __init__(self):
super().__init__()
def reportFileName(self) -> str:
return "statswithballsstrikes"
# Maps a tuple (inning, isHome, outs, (runner on 1st, runner on 2nd, runner on 3rd), curScoreDiff, (balls, strikes)) to a tuple of
# (number of wins, number of situations)
def processedGame(self, gameId: str, finalGameSituation: GameSituation, situationKeysAndPlayLines: typing.List[GameSituationKeyAndNextPlayLine], gameRuleOptions: GameRuleOptions) -> None:
if skipOutput:
return
if not self.shouldProcessGame(situationKeysAndPlayLines, gameRuleOptions):
return
# Add gameKeys to stats
# Check the last situation to see who won.
homeWon = finalGameSituation.isHomeWinning()
if (homeWon is None):
# This game must have been tied when it stopped. Don't count
# these stats.
return
for situationKeyAndPlayLine in situationKeysAndPlayLines:
situationKeyOriginal = situationKeyAndPlayLine.situationKey
isHomeInning = situationKeyOriginal[1]
#TODO this is probably slow?
situationKeyList = list(situationKeyOriginal)
situationKeyList[1] = 1 if isHomeInning else 0
pitches = PlayLineInfo.fromLine(situationKeyAndPlayLine.playLine).pitchesString
counts = getBallStrikeCountsFromPitches(pitches)
isWin = (isHomeInning and homeWon) or (not isHomeInning and not homeWon)
situationKeyList.append(typing.cast(int, (0, 0)))
for count in [x for x in counts if (x.balls < 4 and x.strikes < 3)]:
situationKeyList[-1] = count
situationKey = tuple(situationKeyList)
self._addSituationKey(situationKey, isWin)
class StatsRunExpectancyPerInningReport(StatsReport):
def reportFileName(self) -> str:
return "runsperinningstats"
def getNextInning(self, inning: typing.Tuple[int, bool]) -> typing.Tuple[int, bool]:
if (inning[1]):
return (inning[0]+1, False)
else:
return (inning[0], True)