-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretrosheet_parse_event_outcomes.py
executable file
·2596 lines (2376 loc) · 100 KB
/
retrosheet_parse_event_outcomes.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 sys
import re
import traceback
import time
from random import randint
from copy import deepcopy
# global
playerCodeToIDMap = dict()
playerIDToCodeMap = dict()
#playerIDMap = dict()
SKIP_GAMES = ("1938-05-14SLNCIN0", # this game was protested and replayed later
)
class BatResult:
def __init__(self, results=[], bases=[], hit_type=None, hit_loc=None, mods=[]):
self.results = list(results)
# base paramters for each result
self.bases = list(bases)
# G=ground ball, F=fly ball L=line drive, P=pop up
self.hit_type = hit_type
# roughly where in the field ball was hit,
self.hit_loc = hit_loc
self.mods = list(mods)
class FieldingResult:
def __init__(self, errors=[], putouts=[], assists=[], fielded=[]):
self.errors = list(errors)
self.putouts = list(putouts)
self.assists = list(assists)
self.fielded = list(fielded)
class RunResult:
def __init__(self, out=[], adv=[], mods=[]):
self.out = list(out)
self.adv = list(adv)
self.mods = list(mods)
# the interpretation of results of these plays is ambiguous
# amd would be difficul to resolve with general rules
# therefore the results are entered in manually
AMBIGUOUS_PLAYS = dict()
# game date, home team, away team, double header num (0, 1, 2)
# innning, inning half, batter code, play count with batter
br = BatResult(("O",), bases=(None,), hit_type="G", hit_loc="4")
fr = FieldingResult(errors=[6], assists=(4,), putouts=(3,))
rr = RunResult(adv=[(1, 2, True)], out=((0, False, 1),))
#S9.2-H(UR);BXH(E9)(932)
br2 = BatResult(("S",), bases=(None,), hit_loc="9")
fr2 = FieldingResult(errors=(9,), assists=(9, 3), putouts=[2,])
rr2 = RunResult(adv=((2, 4, True), (0, 4, False)))
AMBIGUOUS_PLAYS["1922-05-10NYACHA0"] = { (11, "T", "strua102", 0) : (br, fr, rr),
(11, "T", "hooph101", 0) : (br2, fr2, rr2)}
# setting to True will print debugging output for all games
# if false, only games which fail to parse
DEBUG = False
DEBUG_OUT = []
def DEBUG_PRINT(*args,end="\n"):
if DEBUG:
print(*args, end=end)
else:
DEBUG_OUT.append((args, end))
def PRINT_DEBUG_OUT():
for l in DEBUG_OUT:
for s in l[0]:
print(s, end=" ")
print(end=l[1])
def valOrNULL(v):
if v == None:
return "NULL"
# wrap in single quotes
if type(v) == type(""):
return "'" + v + "'"
elif type(v) == type(True):
if v:
return "0"
return "1"
return v
def baseToNum(b):
if b == 'B':
return 0
elif b == 'H':
return 4
return int(b)
class Event:
def __init__(self):
pass
class PitchSeqData:
def __init__(self):
self.pitchesThrown = 0
self.strikes = 0
self.balls = 0
self.intBalls = 0
self.pitchOuts = 0
self.pickoffAttempts = 0
self.catcherPickoffAttempts = 0
self.catcherBlocks = 0
self.runnerGoing = 0
self.inPlay = False
self.hitBatter = False
FIELD_POS_NUM = range(1, 10)
# adopted from Chadwick baseball data
locations = {"1":0, "13":1, "15":2, "1S":3, "2":4, "2F":5, "23":6,
"23F":7, "25":8, "25F":9, "3SF":10, "3F":11, "3DF":12,
"3S":13, "3":14, "3D":15, "34S":16, "34":17, "34D":18,
"4S":19, "4":20, "4D":21, "4MS":22, "4M":22, "4MD":23,
"6MS":24, "6M":25, "6MD":26, "6S":27, "6":28, "6D":29,
"56S":30, "56":31, "56D":32, "5S":33, "5":34, "5D":35,
"5SF":36, "5F":37, "5DF":38, "7LSF":39, "7LS":40, "7S":41,
"78S":42, "8S":43, "89S":44, "9S":45, "9LS":46, "9LSF":47,
"7LF":48, "7L":49, "7":50, "78":51, "8":52, "89":53, "9":54,
"9L":55, "9LF":56, "7LDF":57, "7LD":58, "7D":59, "78D":60,
"8D":61, "89D":62, "9D":63, "9LD":64, "9LDF":65, "78XD":66,
"8XD":67, "89XD":68 }
# "the following locations are nonstandard or archaic,
# but appear in existing Retrosheet data ""
# adopted from Chadwick baseball data
# remap to canonical locations
# TODO mapping locations need to be improved
odd_locations= { # pitchers mound area
"13S":"13", "15S":"15",
# catcher
"2LF":"LF", "2RF":"RF",
"2L":"2", "2R":"2",
# first base
"3L":"3",
# second base
"46":"4",
# third base
"5L":"5",
# left field
"7LDW":"7", "7DW":"7", "78XDW":"7",
"7LMF":"7", "7LM":"7", "7M":"7", "78M":"7",
# center field
"8XDW":"8", "89XDW":"8",
"8LS":"8", "8RS":"8", "8LD":"8", "8RD":"8",
"8LXD":"8", "8RXD":"8", "8LXDW":"8", "8RXDW":"8",
"8LM":"8", "8M":"8", "8RM":"8", "89M":"8",
# right field
"9DW":"9", "9LDW":"9",
"9M":"9", "9LM":"9", "9LMF":"9" }
# playCodeNumMap = {"S":0, "D":1, "CI":2, "DGR":3, "T":4, "HR":5,
# "WP":6, "BB":7, "FC":8, "PB":9, "E":10, "O":11,
# "HBP":12, "IBB":13, "K":14, "SB":15, "CS":16, "BK":17,
# "PO":18, "POCS":19, "POE":20, "OA":21, "DI":22, "NP":23,
# "FLE":24, "FO":25}
playCodeMap = {"S": "single", "D":"double", "CI":"catcher interference",
"DGR":"ground rule double", "T":"triple", "HR":"home run",
"WP":"wild pitch", "BB":"walk", "FC":"fielders choice", "PB":"pass ball",
"E":"error", "O":"out", "HBP":"hit by pitch", "IBB":"intentional walk",
"K":"strikeout", "SB":"stolen base", "CS":"caught stealing", "BK":"balk",
"PO":"pick off", "POCS":"pickoff caught stealing", "POE":"pick off error", "OA":"other advance",
"DI":"defensive indifference", "NP":"(no play)", }
# retro sheet to play code for certain lays
RStoPlayCodeMap = {"W": "BB", "I":"IBB", "IW":"IBB", "HP":"HBP", "WP":"WP",
"PB":"PB", "K":"K", "DI":"DI", "OA":"OA", "NP":"NP", "BK":"BK",
"C":"CI", "DGR":"DGR"}
HIT_TYPES = {None:0, "G":1,"L":2, "F":3, "P":4}
for p in list(RStoPlayCodeMap.keys()):
RStoPlayCodeMap[p + "!"] = RStoPlayCodeMap[p]
RStoPlayCodeMap[p + "#"] = RStoPlayCodeMap[p]
RStoPlayCodeMap[p + "?"] = RStoPlayCodeMap[p]
RStoPlayCodeMap[p + "+"] = RStoPlayCodeMap[p]
RStoPlayCodeMap[p + "-"] = RStoPlayCodeMap[p]
for m in list(playCodeMap.keys()):
playCodeMap[m + "!"] = playCodeMap[m]
playCodeMap[m + "#"] = playCodeMap[m]
playCodeMap[m + "?"] = playCodeMap[m]
playCodeMap[m + "+"] = playCodeMap[m]
playCodeMap[m + "-"] = playCodeMap[m]
modCodeMap = {"AP": "appeal play",
"BP": "pop up bunt",
"BF": "bunt foul",
"BG": "ground ball bunt",
"BGDP": "bunt grounded into double play",
"BINT": "batter interference",
"BL": "line drive bunt",
"BOOT": "batting out of turn",
"BPDP": "bunt popped into double play",
"BR": "runner hit by batted ball",
"C": "called third strike",
"COUB": "courtesy batter",
"COUF": "courtesy fielder",
"COUR": "courtesy runner",
"DP": "unspecified double play",
"DGR": "ground rule double",
"E$": "error on $",
"F": "fly",
"FDP": "fly ball double play",
"FINT": "fan interference",
"FL": "foul",
"FO": "force out",
"G": "ground ball",
"GDP": "ground ball double play",
"GTP": "ground ball triple play",
"IF": "infield fly rule",
"INT": "interference",
"IPHR": "inside the park home run",
"L": "line drive",
"LDP": "lined into double play",
"LTP": "lined into triple play",
"MREV": "manager challenge of call on the field",
"NDP": "no double play credited for this play",
"OBS": "obstruction (fielder obstructing a runner)",
"P": "pop fly",
"PASS": "a runner passed another runner and was called out",
"R$": "relay throw from the initial fielder to $ with no out made",
"RINT": "runner interference",
"SF": "sacrifice fly",
"SH": "sacrifice hit (bunt)",
"TH": "throw",
"TH%": "throw to base %",
"TP": "unspecified triple play",
"UINT": "umpire interference",
"UREV": "umpire review of call on the field" }
# modCodeNumMap = {"H":0, "B":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7,
# "8":8, "9":9, "AP": 10, "BP": 11, "BF": 12,
# "BG": 13, "BGDP": 14,
# "BINT": 15, "BL": 16, "BOOT": 17, "BPDP": 18, "BR": 19, "C": 20,
# "COUB": 21, "COUF": 22, "COUR": 23, "DP": 24, "DGR": 25,
# "E": 26, "F": 27, "FDP": 28, "FINT": 29, "FL": 30, "FO": 31,
# "G": 32, "GDP": 33, "GTP": 34, "IF": 35, "INT": 36, "IPHR": 37,
# "L": 38, "LDP": 39, "LTP": 40, "MREV": 41, "NDP": 42, "OBS": 43,
# "P": 44, "PASS": 45, "R$": 46, "RINT": 47, "SF": 48, "SH": 49,
# "TH": 50, "TP": 51, "UINT": 52, "UREV": 53, "T":54 }
# for m in list(modCodeNumMap.keys()):
# modCodeNumMap[m + "!"] = modCodeNumMap[m]
# modCodeNumMap[m + "#"] = modCodeNumMap[m]
# modCodeNumMap[m + "?"] = modCodeNumMap[m]
# modCodeNumMap[m + "+"] = modCodeNumMap[m]
# modCodeNumMap[m + "-"] = modCodeNumMap[m]
for m in list(modCodeMap.keys()):
modCodeMap[m + "!"] = modCodeMap[m]
modCodeMap[m + "#"] = modCodeMap[m]
modCodeMap[m + "?"] = modCodeMap[m]
modCodeMap[m + "+"] = modCodeMap[m]
modCodeMap[m + "-"] = modCodeMap[m]
batPlaysNoParse = []
runPlaysNoParse = []
sqlStmts = []
def baseNumForPOCS(b, play):
if b is None:
return None
if b in ("1", "2", "3"):
b = int(b)
else:
b = 4
if play in ("CS", "POCS"):
b = b-1
return b
class PlayEvent(Event):
def parsePitchSeq(self):
if self.pitch_seq != None and self.pitch_seq != "":
s = PitchSeqData()
for p in self.pitch_seq:
if p == "+": # following pickoff throw by the catcher
s.catcherPickoffAttempts += 1
elif p == "*": # indicates the following pitch was blocked by the catcher
s.catcherBlocks += 1
elif p == ".": # marker for play not involving the batter
pass
# pickoff throw to first
elif p in ("1", "2", "3"):
s.pickoffAttempts += 1
elif p == ">": # Indicates a runner going on the pitch
s.runnerGoing += 1
elif p == "A": # automatic strike, usually for pitch timer violation
s.strikes += 1
elif p == "B": # ball
s.balls += 1
s.pitchesThrown += 1
elif p == "C": # called strike
s.strikes += 1
s.pitchesThrown += 1
elif p == "F": # foul
s.strikes += 1
s.pitchesThrown += 1
elif p == "H": # hit batter
s.balls += 1
s.hitBatter = True
s.pitchesThrown += 1
elif p == "I": # intentional ball
s.pitchesThrown += 1
s.intBalls += 1
elif p == "K": # strike (unknown type)
s.strikes += 1
s.pitchesThrown += 1
elif p == "L": # foul bunt
s.strikes += 1
s.pitchesThrown += 1
elif p == "M": # missed bunt attempt
s.strikes += 1
s.pitchesThrown += 1
elif p == "N": # no pitch (on balks and interference calls)
pass
elif p == "O": # foul tip on bunt
s.strikes += 1
s.pitchesThrown += 1
elif p == "P": # pitchout
s.pitchOuts += 1
elif p == "Q": # swinging on pitchout
s.strikes += 1
s.pitchOuts += 1
elif p == "R": # foul ball on pitchout
s.strikes += 1
s.pitchOuts += 1
elif p == "S": # swinging strike
s.strikes += 1
s.pitchesThrown += 1
elif p == "T": # foul tip
s.strikes += 1
s.pitchesThrown += 1
elif p == "U": # unknown or missed pitch
pass
elif p == "V": # called ball because pitcher went to his mouth or automatic ball on intentional walk orpitch timer violation
s.balls += 1
elif p == "X": # ball put into play by batter
s.strikes += 1
s.pitchesThrown += 1
s.inPlay = True
elif p == "Y": # ball put into play on pitchout
s.inPlay = True
self.pitchSeq = s
def getFielderPOA(self, play):
r_m = re.fullmatch(r"(\d*)(\d).*", play)
if r_m is not None:
fldrs = set(r_m.group(1))
for f in fldrs:
self.fielding.assists.append(int(f))
self.fielding.putouts.append(int(r_m.group(2)))
def parseRunnerMods(self, modsParens):
runMods = []
if modsParens == "":
#self.run.mods.append(())
return []
# break up parentheses
idx = 0
mods_m = re.match(r"(\([^()]*\))", modsParens)
# all modifications for this advance
while mods_m is not None and modsParens != "":
mods = mods_m.group(1)
# remove enclosing parentheses
mods=mods[1:-1]
DEBUG_PRINT(f"parseRunnerMods: mods={mods}")
runSubMod = []
for mod in mods.split("/"):
DEBUG_PRINT(mod)
if mod in modCodeMap:
runSubMod.append(mod)
continue
# runner thrown out, possibly due to rundown
m = re.fullmatch(r"\((\d+)\)", mod)
if m is not None:
grps = m.groups()
self.getFielderPOA(grps[2])
DEBUG_PRINT("runner out")
runSubMod.append("O")
continue
m = re.fullmatch(r"TH([123H])", mod)
if m is not None:
runSubMod.append(("TH", m.group(1)))
DEBUG_PRINT("throw to base", m.group(1))
continue
m = re.fullmatch(r"R([123H])", mod)
if m is not None:
runSubMod.append(("R", m.group(1)))
DEBUG_PRINT("relay throw to base", m.group(1))
continue
# error (fielding or catch)
m = re.fullmatch(r"(\d*)E(\d)", mod)
if m is not None:
grps = m.groups()
if grps[0] is not None:
DEBUG_PRINT("error - catch")
fldrs = set(grps[0])
for f in fldrs:
self.fielding.fielded.append(int(f))
else:
DEBUG_PRINT("fielding error")
self.fielding.errors.append(int(grps[1]))
runSubMod.append(("E", int(grps[1])))
continue
DEBUG_PRINT(runSubMod)
runMods.append(runSubMod)
idx = mods_m.end()
modsParens = modsParens[idx:]
mods_m = re.match(r"(\([^()]*\))", modsParens)
self.run.mods.append(runMods)
return runMods
def parseRunnerAdv(self, run_all):
self.run.adv = []
self.run.mods = []
if len(run_all) == 0:
return False
run_adv = run_all.split(";")
DEBUG_PRINT("parseRunnerAdv: run_adv=", run_adv)
for adv in run_adv:
idx = adv.find("(")
a0 = adv
mods = ""
if idx != -1:
a0 = adv[:idx]
mods = adv[idx:]
if "-" in a0: # safe
a = a0.split("-")
isSafe = True
elif "X" in a0: # out
a = a0.split("X")
isSafe = False
else:
DEBUG_PRINT("no valid separator found")
return True
if len(a) != 2:
DEBUG_PRINT("len(a) != 2")
return True
srcBase = a[0]
dstBase = a[1][0]
if len(mods) > 0 and mods[0] in ("#", "?", "!"):
mods = a[1][2:]
runMods = self.parseRunnerMods(mods)
if srcBase not in ("B","1","2","3"):
DEBUG_PRINT("bad srcBase=", srcBase)
return True
if dstBase not in ("H","1","2","3"):
DEBUG_PRINT("bad dstBase=", dstBase)
return True
possiblySafeDueToError = False
if not isSafe:
# if there was error on this play, runner might be safe
# despite being marked out on the score sheet
# for example see game id = PIT191205310, top of the 3rd inning
# or PIT/NY1 date= 191208232 top of the 2nd inning
# OTOH, they could also be out - see CHA @ BOS19120827 Top of the 6th
# handle speculation in parseGame/applyPlay, if inning ends before or after
# expected, use the other interpretation
DEBUG_PRINT("parseRunAdv: runMods=", runMods)
possiblySafeDueToError = False
for mods in runMods:
for subMod in mods:
if type(subMod) == type(tuple()):
if subMod[0] == "E":
DEBUG_PRINT("runner marked as out may be safe due to error")
possiblySafeDueToError = True
break
if possiblySafeDueToError:
break
# use E designation as opposed to True/False
if possiblySafeDueToError:
isSafe = "E"
t = (srcBase, dstBase, isSafe)
DEBUG_PRINT("parseRunAdv: appending ", t)
self.run.adv.append(t)
return False
def parseBat(self, bat_all):
# parse a single play
def parseFirst(bat0):
# 99 generic out, unknown fielder
if bat0 == "99":
DEBUG_PRINT("generic fielding out (99)")
return False, "O", None, len(bat0)
# walks, etc.
if bat0 in RStoPlayCodeMap.keys():
result = RStoPlayCodeMap[bat0]
DEBUG_PRINT("mapped to code", playCodeMap[result])
return False, result, None, len(bat0)
# stolen base
m = re.match(r"^SB([123H])[#!?]?", bat0)
if m is not None:
DEBUG_PRINT("stolen base")
return False, "SB", m.group(1), m.end()
# caught stealing / pickoff
m = re.match(r"^(CS|POCS|PO)([123H])\((.*)\)?[#!?]?", bat0)
if m is not None:
DEBUG_PRINT("caught stealing/pickoff")
grps = m.groups()
DEBUG_PRINT(m.group(1), grps)
result = grps[0]
base = grps[1]
m_end = m.end()
isError = False
if grps[2] is not None:
DEBUG_PRINT("CS/POCS/PO grps[2]=", grps[2])
# error on play
e_m = re.fullmatch(r"(.*)E(\d).*", grps[2])
if e_m is not None:
self.fielding.errors.append(int(e_m.group(2)))
isError = True
self.getFielderPOA(grps[2])
b = baseNumForPOCS(base, result)
self.run.out.append((b, isError, base))
return False, result, base, m_end
# base hit/single/double/triple S,D,or T followed by single digit (optional)
m = re.match(r"^([SDT])(.*)?[#!?+-]?", bat0)
if m is not None:
DEBUG_PRINT("hit")
if m.group(2) is not None:
self.bat.hit_loc = m.group(2)
return False, m.group(1), None, m.end()
# home run (possibly inside the park)
m = re.match(r"^HR?(.*)?[#!?+-]?", bat0)
if m is not None:
DEBUG_PRINT("home run")
if m.group(1) is not None:
self.bat.hit_loc = m.group(1)
return False, "HR", None, m.end()
# error (fielding or catch)
m = re.match(r"^(\d*)[#!?]?E(\d)[#!?+-]?", bat0)
if m is not None:
grps = m.groups()
if grps[0] is not None:
DEBUG_PRINT("error - catch")
for f in grps[0]:
if f.isnumeric():
self.fielding.fielded.append(int(f))
else:
DEBUG_PRINT("fielding error")
self.fielding.errors.append(int(grps[1]))
return False, "E", None, m.end()
# more complciated play need to come first
# since we are not doing fullmatch and less complicated plays woule
# match this pattern
# triple play, batter out first may be due to caught ball
m = re.match(r"^(\d).?\(B\)(.*)\(([123])\)(.*)\(([123])\)(\d.)?", bat0)
if m is not None:
DEBUG_PRINT("triple play")
grps = m.groups()
self.run.out.append((int(grps[2]), False, int(grps[2])+1))
self.run.out.append((int(grps[4]), False, int(grps[4])+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[1]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
flast = int(grps[4][0])
self.fielding.putouts.append(flast)
return False, "O", None, m.end()
# triple play - ground ball, forceout, explicity or implied runner out at first
m = re.match(r"^(\d.*)\(([123])\)(\d.*)\(([123])\)(\d.?)(\(B\))?", bat0)
if m is not None:
DEBUG_PRINT("triple play")
grps = m.groups()
self.run.out.append((int(grps[1]), False, int(grps[1])+1))
self.run.out.append((int(grps[3]), False, int(grps[3])+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[2]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
flast = int(grps[4][0])
self.fielding.putouts.append(flast)
return False, "O", None, m.end()
# triple play - ground ball
m = re.match(r"^(\d.*)\(([123B])\)(\d.*)\(([123B])\)(\d.*)\(([123B])\)", bat0)
if m is not None:
DEBUG_PRINT("triple play")
grps = m.groups()
b1 = baseToNum(grps[1])
b2 = baseToNum(grps[3])
b3 = baseToNum(grps[5])
if b1 != 0:
self.run.out.append((b1, False, b1+1))
if b2 != 0:
self.run.out.append((b2, False, b2+1))
if b3 != 0:
self.run.out.append((b3, False, b3+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[2]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[4]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
return False, "O", None, m.end()
# double play, either ball caught, runner tagged out
# or force at first followed by tag of other runner
m = re.match(r"^(\d.*)\(B\)(\d.*)\(([123])\)", bat0)
if m is not None:
DEBUG_PRINT("double play")
grps = m.groups()
self.run.out.append((int(grps[2]), False, int(grps[2])+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[1]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.assists.pop()
self.fielding.putouts.append(flast)
return False, "O", None, m.end()
# double play to bags other than first
m = re.match(r"^(\d.*)\(([123])\)[!]?(\d.*)\(([123])\)", bat0)
if m is not None:
DEBUG_PRINT("double play (bags other than first)")
grps = m.groups()
self.run.out.append((int(grps[1]), False, int(grps[1])+1))
self.run.out.append((int(grps[3]), False, int(grps[3])+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[2]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
return False, "FO", None, m.end()
# double play - implied or explicit runner out at first
m = re.match(r"^(\d.*)\(([123])\)[!]?(\d.*)(\(B\))?", bat0)
if m is not None:
DEBUG_PRINT("double play - runner out at first")
grps = m.groups()
self.run.out.append((int(grps[1]), False, int(grps[1])+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
for f in grps[2]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.assists.pop()
self.fielding.putouts.append(flast)
return False, "O", None, m.end()
# force out (single out) to bag other than first
m = re.match(r"^(\d.*)\(([123])\)", bat0)
if m is not None:
DEBUG_PRINT("force out")
grps = m.groups()
self.run.out.append((int(grps[1]), False, int(grps[1])+1))
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.putouts.append(flast)
return False, "FO", None, m.end()
# generic fielding out (batter)
m = re.match(r"^(\d.*)", bat0)
if m is not None:
DEBUG_PRINT("generic out")
grps = m.groups()
for f in grps[0]:
if f.isnumeric():
flast = int(f)
self.fielding.assists.append(flast)
self.fielding.assists.pop()
self.fielding.putouts.append(flast)
return False, "O", None, m.end()
# fielders choice / defensive indifference / other advance
m = re.match(r"^(FC|DI|OA)(\d)?[#!?+-]?", bat0)
if m is not None:
DEBUG_PRINT("fielders choice/DI/OA")
return False, m.group(1), m.group(2), m.end()
# fielding error on foul ball
m = re.fullmatch(r"^FLE(\d)[#!?+-]?", bat0)
if m is not None:
DEBUG_PRINT("fielding error on foul ball")
self.fielding.errors.append(int(m.group(1)))
return False, "FLE", None, m.end()
# strikeout, potentially with dropped third strike
# and plays by other fielders
m = re.match(r"^K(\d.*)[!#?]?", bat0)
if m is not None:
DEBUG_PRINT("strikeout")
return False, "K", None, m.end()
DEBUG_PRINT("cannot parse ", bat0)
return True, None, None, None
# end parseFirst()
def parseBatMod(mod, mods):
if mod in locations:
self.bat.hit_loc = mod
return False
elif mod in odd_locations:
# map to canonical
self.bat.hit_loc = odd_locations[mod]
return False
elif mod in modCodeMap:
mods.append(mod)
return False
m = re.match(r"([GLFP])(.*)?[#!?+-]?", mod)
if m is not None:
self.bat.hit_type = m.group(1)
self.bat.hit_loc = m.group(2)
DEBUG_PRINT("hit_type", self.bat.hit_type, "hit_loc", self.bat.hit_loc)
return False
m = re.match(r"TH([123H])[#!?]?", mod)
if m is not None:
b = m.group(1)
DEBUG_PRINT("throw to base", b)
mods.append(("TH", b))
return False
m = re.match(r"R([123H])", mod)
if m is not None:
b = m.group(1)
DEBUG_PRINT("relay throw to base", b)
mods.append(("R", b))
return False
# error (catch or field)
m = re.match(r"(\d)?E(\d)", mod)
if m is not None:
grps = m.groups()
if grps[0] is not None:
self.fielding.fielded.append(int(m.group(1)))
self.fielding.errors.append(int(m.group(2)))
mods.append(("E", int(m.group(2))))
return False
DEBUG_PRINT("cannot parse batter mod", mod)
return True
# end parseBatMod
#pID = playerIDMap[self.player_id][0]
pID = self.player_id
DEBUG_PRINT("parseBat ", self.inning, self.team, pID, " bat_all=", bat_all)
# can be multiple plays within single line (e.g. double steals)
# so we split them up
# NOTE we cannot further split into "combo plays" such as K+SB
# because '+' can also be used to denote "hard hit ball"
plays = bat_all.split(";")
for p in plays:
p1 = p.split("/")
p1_0 = p1[0]
DEBUG_PRINT("parseBat: p1_0=", p1_0)
p1_1 = p1[1:]
DEBUG_PRINT("parseBat: p1_1=", p1_1)
# detect combo play
m = re.match(r"^(K|K\d*|W|IW|I)\+", p1_0)
if m is not None:
err, result, base, lastIdx = parseFirst(m.group(1))
if err:
return True
self.bat.results.append(result)
self.bat.bases.append(base)
self.bat.mods.append([])
p1_0 = p1_0[m.end():]
err, result, base, lastIdx = parseFirst(p1_0)
rest = p1_0[lastIdx:]
if len(rest) > 0:
print("parseFirst: unparsed=", rest, "p1_0=", p1_0)
if err:
return True
self.bat.results.append(result)
self.bat.bases.append(base)
# modifiers
mods = []
# there may be fragment(s) left after the "/" split
# e.g., 'PO1(E2/TH)' will have fragment 'TH)'
if rest != "":
if rest[0] == "(":
rest = rest[1:]
if rest[-1] == ")":
rest = rest[::-1]
parseBatMod(rest, mods)
for m in p1_1:
parseBatMod(m, mods)
self.bat.mods.append(mods)
return False
def parsePlay(self):
# split up bat and base run
run_all = ""
s = self.play.split(".")
bat_all = s[0]
if len(s) > 1:
run_all = s[1]
if len(s) > 2:
DEBUG_PRINT("parsePlay: unexpected input (more than one '.') play=", self.play)
return True
err = self.parseBat(bat_all)
if err:
return True
err = self.parseRunnerAdv(run_all)
if err:
return True
return False
def __init__(self, p=None):
if p is not None:
# destructure
self.game_id, self.event_id, self.team_id, self.player_id = p[0:4]
self.inning, self.batter_count, self.pitch_seq, self.play = p[4:]
self.team = self.team_id
self.player_id = playerIDToCodeMap[self.player_id]
#print("team=", self.team)
self.pitchSeq = None
self.bat = BatResult()
self.fielding = FieldingResult()
self.run = RunResult()
class SubEvent(Event):
def __init__(self, s=None):
if s is not None:
self.game_id, self.event_id, self.player_id = s[0:3]
self.team_id, self.bat_pos, self.field_pos = s[3:]
self.player_id = playerIDToCodeMap[self.player_id]
self.bat_pos = int(self.bat_pos)
self.field_pos = int(self.field_pos)
self.team = self.team_id
class PlayerAdjEvent(Event):
def __init__(self, p=None):
if p is not None:
# destructure
self.game_id, self.event_id, self.player_id = p[0:3]
self.adjType, self.adj = p[3:]
self.player_id = playerIDToCodeMap[self.player_id]
def print(self):
DEBUG_PRINT(f"**** Player adjustment: {self.player_id} {self.adjType} {self.adj}")
class LineupAdjEvent(Event):
def __init__(self, l=None):
if l is not None:
# destructure
self.game_id, self.event_id, self.team = l[0:3]
self.adj = int(l[3])
def print(self):
DEBUG_PRINT(f"***** Lineup adjustment: {self.team} {self.adj}")
class DataEREvent(Event):
def __init__(self, d=None):
if d is not None:
# destructure
self.game_id, self.event_id, self.player_id = d[0:3]
self.er = int(d[3])
self.player_id = playerIDToCodeMap[self.player_id]
def print(self):
DEBUG_PRINT(f"ER: {self.player_id} {self.er}")
class ComEvent(Event):
def __init__(self, d=None):
if d is not None:
self.game_id, self.event_id, self.com = d[0:3]
self.event_id = int(self.event_id)
class Lineup:
def __init__(self, team_id):
self.team_id = team_id
self.team = team_id
# map between order in batting (1..9)
# order 0 has no meaning, or could be interpted as the P when using a DH
self.battingOrder = [None]*10
# map between field position, with 1=pitcher 2=catcher, 3=1B etc.
# 0 position has no meaning, or could be the DH
self.fieldPos = [None]*10
self.battingOrderStart = [None]*10
self.battingOrderSubs = [[] for i in range(10)]
self.pitchersUsed = []
def print(self):
DEBUG_PRINT(self.team, "lineup")
for b in range(1, 10):
p = self.battingOrder[b]
#pID = playerIDMap[p]
pID = p
fldPos = None
for f in range(1, 10):
if p == self.fieldPos[f]:
fldPos = f
break
DEBUG_PRINT(b, pID, "playing", fldPos)
DEBUG_PRINT("Pitching", self.fieldPos[1])
def applySub(self, sub):
rep_batter = None
rep_fielder = None
newPos = None
DEBUG_PRINT("applySub: sub=", sub.player_id, "bat_pos=", sub.bat_pos, " field_pos=", sub.field_pos )
if sub.field_pos == 1:
self.pitchersUsed.append(sub.player_id)
if sub.bat_pos != 0:
idx = sub.bat_pos
rep_batter = self.battingOrder[idx]
if rep_batter != sub.player_id:
DEBUG_PRINT("applySub: appending to batting order at ", idx)
self.battingOrder[idx] = sub.player_id
self.battingOrderSubs[idx].append(sub.player_id)
else:
DEBUG_PRINT("applySub: rep_batter=", rep_batter, " replacing self in order (field position change")
if sub.field_pos in FIELD_POS_NUM:
idx = int(sub.field_pos)
rep_fielder = self.fieldPos[idx]
if rep_batter is not None and self.fieldPos[idx] != rep_batter:
DEBUG_PRINT("WARNING: player is replacing different fielder.")
# find position in the field the batter was playing
for f in range(1, 10):
if self.fieldPos[f] == rep_batter:
# move fielder to this osition
self.fieldPos[f] = rep_fielder
newPos = f
break
self.fieldPos[idx] = sub.player_id
return rep_batter, (rep_fielder, newPos)
class FielderStats:
def __init__(self):
self.GP = 1
self.IF3 = 0
self.PO = 0
self.A = 0
self.E = 0
self.DP = 0
self.TP = 0
self.PB = 0
def add(self, st):
self.GP += st.GP
self.IF3 += st.IF3
self.PO += st.PO
self.A += st.A
self.E += st.E
self.DP += st.DP
self.TP += st.TP
self.PB += st.PB
def insertIntoDB(self, cur, game_id, player_id, team_id, pos, seq):