forked from ChazDazzle/fpdb-chaz
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDerivedStats.py
1775 lines (1659 loc) · 85.7 KB
/
DerivedStats.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/env python
# -*- coding: utf-8 -*-
#Copyright 2008-2011 Carl Gherardi
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, version 3 of the License.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
#In the "official" distribution you can find the license in agpl-3.0.txt.
#fpdb modules
import L10n
_ = L10n.get_translation()
import Card
from decimal_wrapper import Decimal, ROUND_DOWN
import sys
import logging
# logging has been set up in fpdb.py or HUD_main.py, use their settings:
log = logging.getLogger("parser")
try:
from pokereval import PokerEval
pokereval = PokerEval()
except:
pokereval = None
def _buildStatsInitializer():
init = {}
#Init vars that may not be used, but still need to be inserted.
# All stud street4 need this when importing holdem
init['bigblind'] = 0
init['effStack'] = 0
init['effActiveStack'] = 0
init['effMzone'] = 0
init['effActiveMzone'] = 0
init['tableMzone'] = 0
init['startBounty'] = None
init['endBounty'] = None
init['common'] = 0
init['committed'] = 0
init['winnings'] = 0
init['rake'] = 0
init['rakeDealt'] = 0
init['rakeContributed'] = 0
init['rakeWeighted'] = 0
init['totalProfit'] = 0
init['allInEV'] = 0
init['showdownWinnings'] = 0
init['nonShowdownWinnings'] = 0
init['sawShowdown'] = False
init['showed'] = False
init['wonAtSD'] = False
init['startCards'] = 170
init['handString'] = None
init['position'] = 9 #ANTE ALL IN
init['street0CalledRaiseChance'] = 0
init['street0CalledRaiseDone'] = 0
init['street0VPIChance'] = True
init['street0VPI'] = False
init['street0AggrChance'] = True
init['street0_2BChance'] = False
init['street0_2BDone'] = False
init['street0_3BChance'] = False
init['street0_3BDone'] = False
init['street0_4BChance'] = False
init['street0_4BDone'] = False
init['street0_C4BChance'] = False
init['street0_C4BDone'] = False
init['street0_FoldTo2BChance']= False
init['street0_FoldTo2BDone']= False
init['street0_FoldTo3BChance']= False
init['street0_FoldTo3BDone']= False
init['street0_FoldTo4BChance']= False
init['street0_FoldTo4BDone']= False
init['street0_SqueezeChance']= False
init['street0_SqueezeDone'] = False
init['street0_FoldToSqueezeChance']= False
init['street0_FoldToSqueezeDone'] = False
init['street1_2BChance'] = False
init['street1_2BDone'] = False
init['street1_3BChance'] = False
init['street1_3BDone'] = False
init['street1_4BChance'] = False
init['street1_4BDone'] = False
init['street1_C4BChance'] = False
init['street1_C4BDone'] = False
init['street1_FoldTo2BChance']= False
init['street1_FoldTo2BDone']= False
init['street1_FoldTo3BChance']= False
init['street1_FoldTo3BDone']= False
init['street1_FoldTo4BChance']= False
init['street1_FoldTo4BDone']= False
init['street1_SqueezeChance']= False
init['street1_SqueezeDone'] = False
init['street1_FoldToSqueezeChance']= False
init['street1_FoldToSqueezeDone'] = False
init['street2_2BChance'] = False
init['street2_2BDone'] = False
init['street2_3BChance'] = False
init['street2_3BDone'] = False
init['street2_4BChance'] = False
init['street2_4BDone'] = False
init['street2_C4BChance'] = False
init['street2_C4BDone'] = False
init['street2_FoldTo2BChance']= False
init['street2_FoldTo2BDone']= False
init['street2_FoldTo3BChance']= False
init['street2_FoldTo3BDone']= False
init['street2_FoldTo4BChance']= False
init['street2_FoldTo4BDone']= False
init['street2_SqueezeChance']= False
init['street2_SqueezeDone'] = False
init['street2_FoldToSqueezeChance']= False
init['street2_FoldToSqueezeDone'] = False
init['street3_2BChance'] = False
init['street3_2BDone'] = False
init['street3_3BChance'] = False
init['street3_3BDone'] = False
init['street3_4BChance'] = False
init['street3_4BDone'] = False
init['street3_C4BChance'] = False
init['street3_C4BDone'] = False
init['street3_FoldTo2BChance']= False
init['street3_FoldTo2BDone']= False
init['street3_FoldTo3BChance']= False
init['street3_FoldTo3BDone']= False
init['street3_FoldTo4BChance']= False
init['street3_FoldTo4BDone']= False
init['street3_SqueezeChance']= False
init['street3_SqueezeDone'] = False
init['street3_FoldToSqueezeChance']= False
init['street3_FoldToSqueezeDone'] = False
init['stealChance'] = False
init['stealDone'] = False
init['success_Steal'] = False
init['raiseToStealChance'] = False
init['raiseToStealDone'] = False
init['raiseFirstInChance'] = False
init['raisedFirstIn'] = False
init['foldBbToStealChance'] = False
init['foldSbToStealChance'] = False
init['foldedSbToSteal'] = False
init['foldedBbToSteal'] = False
init['tourneyTypeId'] = None
init['street1Seen'] = False
init['street2Seen'] = False
init['street3Seen'] = False
init['street4Seen'] = False
init['otherRaisedStreet0'] = False
init['foldToOtherRaisedStreet0'] = False
init['callToOtherRaisedStreet0'] = False
init['raiseToOtherRaisedStreet0'] = False
init['wentAllIn'] = False
for i in range(5):
init['street%dCalls' % i] = 0
init['street%dRaises' % i] = 0
init['street%dCallers' % i] = 0
init['street%dAggressors' % i] = 0
init['street%dAggr' % i] = False
init['street%dInPosition' % i] = False
init['street%dFirstToAct' % i] = False
init['street%dAllIn' % i] = False
for i in range(1,4):
init['street%dDiscards' % i] = 0
for i in range(1,5):
init['street%dCBChance' %i] = False
init['street%dCBDone' %i] = False
init['street%dCheckCallRaiseChance' %i] = False
init['street%dCheckCallDone' %i] = False
init['street%dCheckRaiseDone' %i] = False
init['street%dfoldToCheckRaiseChance' %i] = False
init['street%dfoldToCheckRaiseDone' %i] = False
init['otherRaisedStreet%d' %i] = False
init['foldToOtherRaisedStreet%d' %i] = False
init['callToOtherRaisedStreet%d' %i] = False
init['raiseToOtherRaisedStreet%d' %i] = False
init['foldToStreet%dCBChance' %i] = False
init['foldToStreet%dCBDone' %i] = False
init['callToStreet%dCBChance' %i] = False
init['callToStreet%dCBDone' %i] = False
init['raiseToStreet%dCBChance' %i] = False
init['raiseToStreet%dCBDone' %i] = False
init['wonWhenSeenStreet%d' %i] = False
return init
_INIT_STATS = _buildStatsInitializer()
class DerivedStats():
def __init__(self):
self.hands = {}
self.handsplayers = {}
self.handsactions = {}
self.handsstove = []
self.handspots = []
def getStats(self, hand):
for player in hand.players:
self.handsplayers[player[1]] = _INIT_STATS.copy()
self.assembleHands(hand)
self.assembleHandsPlayers(hand)
self.assembleHandsActions(hand)
if pokereval and hand.gametype['category'] in Card.games:
self.assembleHandsStove(hand)
self.assembleHandsPots(hand)
def getHands(self):
return self.hands
def getHandsPlayers(self):
return self.handsplayers
def getHandsActions(self):
return self.handsactions
def getHandsStove(self):
return self.handsstove
def getHandsPots(self):
return self.handspots
def assembleHands(self, hand):
self.hands['tableName'] = hand.tablename
self.hands['siteHandNo'] = hand.handid
self.hands['gametypeId'] = None # Leave None, handled later after checking db
self.hands['sessionId'] = None # Leave None, added later if caching sessions
self.hands['gameId'] = None # Leave None, added later if caching sessions
self.hands['startTime'] = hand.startTime # format this!
self.hands['importTime'] = None
self.hands['seats'] = self.countPlayers(hand)
self.hands['maxPosition'] = -1
#self.hands['maxSeats'] = hand.maxseats
self.hands['texture'] = None # No calculation done for this yet.
self.hands['tourneyId'] = hand.tourneyId
self.hands['heroSeat'] = 0
for player in hand.players:
if hand.hero==player[1]:
self.hands['heroSeat'] = player[0]
# This (i think...) is correct for both stud and flop games, as hand.board['street'] disappears, and
# those values remain default in stud.
boardcards = []
if hand.board.get('FLOPET')!=None:
boardcards += hand.board.get('FLOPET')
for street in hand.communityStreets:
boardcards += hand.board[street]
boardcards += [u'0x', u'0x', u'0x', u'0x', u'0x']
cards = [Card.encodeCard(c) for c in boardcards[0:5]]
self.hands['boardcard1'] = cards[0]
self.hands['boardcard2'] = cards[1]
self.hands['boardcard3'] = cards[2]
self.hands['boardcard4'] = cards[3]
self.hands['boardcard5'] = cards[4]
#print "cards: ",cards
self.hands['boards'] = []
self.hands['runItTwice'] = False
for i in range(hand.runItTimes):
boardcards = []
for street in hand.communityStreets:
boardId = i+1
street_i = street + str(boardId)
if street_i in hand.board:
boardcards += hand.board[street_i]
if hand.gametype['split']:
boardcards = boardcards + [u'0x', u'0x', u'0x', u'0x', u'0x']
cards = [Card.encodeCard(c) for c in boardcards[:5]]
else:
self.hands['runItTwice'] = True
boardcards = [u'0x', u'0x', u'0x', u'0x', u'0x'] + boardcards
cards = [Card.encodeCard(c) for c in boardcards[-5:]]
self.hands['boards'] += [[boardId] + cards]
#print "DEBUG: %s self.getStreetTotals = (%s, %s, %s, %s, %s, %s)" % tuple([hand.handid] + list(hand.getStreetTotals()))
totals = hand.getStreetTotals()
totals = [int(100*i) for i in totals]
self.hands['street0Pot'] = totals[0]
self.hands['street1Pot'] = totals[1]
self.hands['street2Pot'] = totals[2]
self.hands['street3Pot'] = totals[3]
self.hands['street4Pot'] = totals[4]
self.hands['finalPot'] = totals[5]
self.vpip(hand) # Gives playersVpi (num of players vpip)
#print "DEBUG: vpip: %s" %(self.hands['playersVpi'])
self.playersAtStreetX(hand) # Gives playersAtStreet1..4 and Showdown
#print "DEBUG: playersAtStreet 1:'%s' 2:'%s' 3:'%s' 4:'%s'" %(self.hands['playersAtStreet1'],self.hands['playersAtStreet2'],self.hands['playersAtStreet3'],self.hands['playersAtStreet4'])
self.streetXRaises(hand)
def assembleHandsPlayers(self, hand):
#street0VPI/vpip already called in Hand
# sawShowdown is calculated in playersAtStreetX, as that calculation gives us a convenient list of names
#hand.players = [[seat, name, chips],[seat, name, chips]]
for player in hand.players:
player_name = player[1]
player_stats = self.handsplayers.get(player_name)
player_stats['seatNo'] = player[0]
player_stats['startCash'] = int(100 * Decimal(player[2]))
if player[4] != None:
player_stats['startBounty'] = int(100 * Decimal(player[4]))
player_stats['endBounty'] = int(100 * Decimal(player[4]))
if player_name in hand.endBounty:
player_stats['endBounty'] = int(hand.endBounty.get(player_name))
if player_name in hand.sitout:
player_stats['sitout'] = True
else:
player_stats['sitout'] = False
if hand.gametype["type"]=="tour":
player_stats['tourneyTypeId']=hand.tourneyTypeId
player_stats['tourneysPlayersId'] = hand.tourneysPlayersIds[player[1]]
else:
player_stats['tourneysPlayersId'] = None
if player_name in hand.shown:
player_stats['showed'] = True
#### seen now processed in playersAtStreetX()
# XXX: enumerate(list, start=x) is python 2.6 syntax; 'start'
#for i, street in enumerate(hand.actionStreets[2:], start=1):
#for i, street in enumerate(hand.actionStreets[2:]):
# self.seen(self.hand, i+1)
for i, street in enumerate(hand.actionStreets[1:]):
self.aggr(hand, i)
self.calls(hand, i)
self.bets(hand, i)
self.raises(hand, i)
if i>0:
self.folds(hand, i)
# Winnings is a non-negative value of money collected from the pot, which already includes the
# rake taken out. hand.collectees is Decimal, database requires cents
num_collectees, i = len(hand.collectees), 0
even_split = hand.totalpot / num_collectees if num_collectees > 0 else 0
unraked = [c for c in hand.collectees.values() if even_split == c]
for player, winnings in hand.collectees.iteritems():
collectee_stats = self.handsplayers.get(player)
collectee_stats['winnings'] = int(100 * winnings)
# Splits evenly on split pots and gives remainder to first player
# Gets overwritten when calculating multi-way pots in assembleHandsPots
if num_collectees == 0:
collectee_stats['rake'] = 0
elif len(unraked)==0:
rake = int(100 * hand.rake)/num_collectees
remainder_1, remainder_2 = 0, 0
if rake > 0 and i==0:
leftover = int(100 * hand.rake) - (rake * num_collectees)
remainder_1 = int(100 * hand.rake) % rake
remainder_2 = leftover if remainder_1 == 0 else 0
collectee_stats['rake'] = rake + remainder_1 + remainder_2
else:
collectee_stats['rake'] = int(100 *(even_split - winnings))
if collectee_stats['street1Seen'] == True:
collectee_stats['wonWhenSeenStreet1'] = True
if collectee_stats['street2Seen'] == True:
collectee_stats['wonWhenSeenStreet2'] = True
if collectee_stats['street3Seen'] == True:
collectee_stats['wonWhenSeenStreet3'] = True
if collectee_stats['street4Seen'] == True:
collectee_stats['wonWhenSeenStreet4'] = True
if collectee_stats['sawShowdown'] == True:
collectee_stats['wonAtSD'] = True
i+=1
contributed, i = [], 0
for player, money_committed in hand.pot.committed.iteritems():
committed_player_stats = self.handsplayers.get(player)
paid = (100 * money_committed) + (100*hand.pot.common[player])
committed_player_stats['common'] = int(100 * hand.pot.common[player])
committed_player_stats['committed'] = int(100 * money_committed)
committed_player_stats['totalProfit'] = int(committed_player_stats['winnings'] - paid)
committed_player_stats['allInEV'] = committed_player_stats['totalProfit']
committed_player_stats['rakeDealt'] = 100 * hand.rake/len(hand.players)
committed_player_stats['rakeWeighted'] = 100 * hand.rake * paid/(100*hand.totalpot) if hand.rake>0 else 0
if paid > 0: contributed.append(player)
i+=1
for i, player in enumerate(contributed):
self.handsplayers[player]['rakeContributed'] = 100 * hand.rake/len(contributed)
self.calcCBets(hand)
# More inner-loop speed hackery.
encodeCard = Card.encodeCard
calcStartCards = Card.calcStartCards
for player in hand.players:
player_name = player[1]
hcs = hand.join_holecards(player_name, asList=True)
hcs = hcs + [u'0x']*18
#for i, card in enumerate(hcs[:20, 1): #Python 2.6 syntax
# self.handsplayers[player[1]]['card%s' % i] = Card.encodeCard(card)
player_stats = self.handsplayers.get(player_name)
if player_stats['sawShowdown']:
player_stats['showdownWinnings'] = player_stats['totalProfit']
else:
player_stats['nonShowdownWinnings'] = player_stats['totalProfit']
for i, card in enumerate(hcs[:20]):
player_stats['card%d' % (i+1)] = encodeCard(card)
try:
player_stats['startCards'] = calcStartCards(hand, player_name)
except IndexError:
log.error("IndexError: string index out of range %s %s" % (hand.handid, hand.in_path))
self.setPositions(hand)
self.calcEffectiveStack(hand)
self.calcCheckCallRaise(hand)
self.calc34BetStreet0(hand)
self.calc34BetStreet1(hand)
self.calc34BetStreet2(hand)
self.calc34BetStreet3(hand)
self.calcSteals(hand)
self.calcCalledRaiseStreet0(hand)
# Additional stats
# 3betSB, 3betBB
# Squeeze, Ratchet?
def assembleHandsActions(self, hand):
k = 0
walk = False
for i, street in enumerate(hand.actionStreets):
for j, act in enumerate(hand.actions[street]):
k += 1
self.handsactions[k] = {}
#default values
self.handsactions[k]['amount'] = 0
self.handsactions[k]['raiseTo'] = 0
self.handsactions[k]['amountCalled'] = 0
self.handsactions[k]['numDiscarded'] = 0
self.handsactions[k]['cardsDiscarded'] = None
self.handsactions[k]['allIn'] = False
#Insert values from hand.actions
self.handsactions[k]['player'] = act[0]
self.handsactions[k]['street'] = i-1
self.handsactions[k]['actionNo'] = k
self.handsactions[k]['streetActionNo'] = (j+1)
if street == 'BLINDSANTES' and act[1] in ('big blind', 'both', 'button blind'):
all_folds = True
for _act in enumerate(hand.actions['PREFLOP']):
if _act[1][0] != act[0] and _act[1][1] in ('checks', 'calls', 'bets', 'raises', 'completes'):
all_folds = False
if all_folds:
walk = True
if walk:
self.handsactions[k]['actionId'] = 17
walk = False
else:
self.handsactions[k]['actionId'] = hand.ACTION[act[1]]
if act[1] not in ('discards') and len(act) > 2:
self.handsactions[k]['amount'] = int(100 * act[2])
if act[1] in ('raises', 'completes'):
self.handsactions[k]['raiseTo'] = int(100 * act[3])
self.handsactions[k]['amountCalled'] = int(100 * act[4])
if act[1] in ('discards'):
self.handsactions[k]['numDiscarded'] = int(act[2])
self.handsplayers[act[0]]['street%dDiscards' %(i-1)] = int(act[2])
if act[1] in ('discards') and len(act) > 3:
self.handsactions[k]['cardsDiscarded'] = act[3]
if len(act) > 3 and act[1] not in ('discards'):
self.handsactions[k]['allIn'] = act[-1]
if act[-1]:
self.handsplayers[act[0]]['wentAllIn'] = True
self.handsplayers[act[0]]['street%dAllIn' %(i-1)] = True
def assembleHandsStove(self, hand):
category = hand.gametype['category']
holecards, holeplayers, allInStreets = {}, [], hand.allStreets[1:]
base, evalgame, hilo, streets, last, hrange = Card.games[category]
hiLoKey = {'h': [('h', 'hi')], 'l': [('l', 'low')], 's': [('h', 'hi'),('l', 'low')], 'r': [('l', 'hi')]}
boards = self.getBoardsDict(hand, base, streets)
for player in hand.players:
pname = player[1]
hp = self.handsplayers.get(pname)
if evalgame:
hcs = hand.join_holecards(pname, asList=True)
holecards[pname] = {}
holecards[pname]['cards'] = []
holecards[pname]['eq'] = 0
holecards[pname]['committed'] = 0
holeplayers.append(pname)
for street, board in boards.iteritems():
streetId = streets[street]
if streetId > 0:
streetSeen = hp['street%sSeen' % str(streetId)]
else: streetSeen = True
if ((pname==hand.hero and streetSeen) or (hp['showed'] and streetSeen) or hp['sawShowdown']):
boardId, hl, rankId, value, _cards = 0, 'n', 1, 0, None
for n in range(len(board['board'])):
streetIdx = -1 if base=='hold' else streetId
cards = hcs[hrange[streetIdx][0]:hrange[streetIdx][1]]
boardId = (n + 1) if (len(board['board']) > 1) else n
cards += board['board'][n] if (board['board'][n] and 'omaha' not in evalgame) else []
bcards = board['board'][n] if (board['board'][n] and 'omaha' in evalgame) else []
cards = [str(c) if Card.encodeCardList.get(c) else '0x' for c in cards]
bcards = [str(b) if Card.encodeCardList.get(b) else '0x' for b in bcards]
holecards[pname]['hole'] = cards[hrange[streetIdx][0]:hrange[streetIdx][1]]
holecards[pname]['cards'] += [cards]
notnull = ('0x' not in cards) and ('0x' not in bcards)
postflop = (base=='hold' and len(board['board'][n])>=3)
maxcards = (base!='hold' and len(cards)>=5)
if notnull and (postflop or maxcards):
for hl, side in hiLoKey[hilo]:
value, rank = pokereval.best(side, cards, bcards)
rankId = Card.hands[rank[0]][0]
if rank!=None and rank[0] != 'Nothing':
_cards = ''.join([pokereval.card2string(i)[0] for i in rank[1:]])
else:
_cards = None
self.handsstove.append( [hand.dbid_hands, hand.dbid_pids[pname], streetId, boardId, hl, rankId, value, _cards, 0] )
else:
self.handsstove.append( [hand.dbid_hands, hand.dbid_pids[pname], streetId, boardId, 'n', 1, 0, None, 0] )
else:
hl, streetId = hiLoKey[hilo][0][0], 0
if (hp['sawShowdown'] or hp['showed']):
hp['handString'] = hand.showdownStrings.get(pname)
streetId = streets[last]
self.handsstove.append( [hand.dbid_hands, hand.dbid_pids[player[1]], streetId, 0, hl, 1, 0, None, 0] )
if base=='hold' and evalgame:
self.getAllInEV(hand, evalgame, holeplayers, boards, streets, holecards)
def getAllInEV(self, hand, evalgame, holeplayers, boards, streets, holecards):
startstreet, potId, allInStreets, allplayers = None, 0, hand.allStreets[1:], []
for pot, players in hand.pot.pots:
if potId ==0: pot += (sum(hand.pot.common.values()) + hand.pot.stp)
potId+=1
for street in allInStreets:
board = boards[street]
streetId = streets[street]
for n in range(len(board['board'])):
if len(board['board']) > 1:
boardId = n + 1
else: boardId = n
valid = [p for p in players if self.handsplayers[p]['sawShowdown'] and u'0x' not in holecards[p]['cards'][n]]
if potId == 1:
allplayers = valid
deadcards, deadplayers = [], []
else:
deadplayers = [d for d in allplayers if d not in valid]
_deadcards = [holecards[d]['hole'] for d in deadplayers]
deadcards = [item for sublist in _deadcards for item in sublist]
if len(players) == len(valid) and (board['allin'] or hand.publicDB):
if board['allin'] and not startstreet: startstreet = street
if len(valid) > 1:
evs = pokereval.poker_eval(
game = evalgame,
iterations = Card.iter[streetId],
pockets = [holecards[p]['hole'] for p in valid],
dead = deadcards,
board = [str(b) for b in board['board'][n]] + (5 - len(board['board'][n])) * ['__']
)
equities = [e['ev'] for e in evs['eval']]
else:
equities = [1000]
remainder = (1000 - sum(equities)) / Decimal(len(equities))
for i in range(len(equities)):
equities[i] += remainder
p = valid[i]
pid = hand.dbid_pids[p]
if street == startstreet:
rake = Decimal(0) if hand.cashedOut else (hand.rake * (Decimal(pot)/Decimal(hand.totalpot)))
holecards[p]['eq'] += ((pot - rake) * equities[i])/Decimal(10)
holecards[p]['committed'] = 100*hand.pot.committed[p] + 100*hand.pot.common[p]
for j in self.handsstove:
if [pid, streetId, boardId] == j[1:4] and len(valid) == len(hand.pot.contenders):
j[-1] = equities[i]
for p in holeplayers:
if holecards[p]['committed'] != 0:
self.handsplayers[p]['allInEV'] = holecards[p]['eq'] - holecards[p]['committed']
def getBoardsList(self, hand):
boards, community = [], []
if hand.gametype['base']=='hold':
for s in hand.communityStreets:
community += hand.board[s]
for i in range(hand.runItTimes):
boardcards = []
for street in hand.communityStreets:
boardId = i+1
street_i = street + str(boardId)
if street_i in hand.board:
boardcards += hand.board[street_i]
cards = [str(c) for c in community + boardcards]
boards.append(cards)
if not boards:
boards = [community]
return boards
def getBoardsDict(self, hand, base, streets):
boards, boardcards, allInStreets, showdown = {}, [], hand.allStreets[1:], False
for player in hand.players:
if (self.handsplayers[player[1]]['sawShowdown']):
showdown = True
if base == 'hold':
for s in allInStreets:
streetId = streets[s]
b = [x for sublist in [hand.board[k] for k in allInStreets[:streetId+1]] for x in sublist]
boards[s] = {'board': [b], 'allin': False}
boardcards += hand.board[s]
if not hand.actions[s] and showdown:
if streetId>0: boards[allInStreets[streetId-1]]['allin'] = True
boards[s]['allin'] = True
boardStreets = [[], [], []]
for i in range(hand.runItTimes):
runitcards = []
for street in hand.communityStreets:
street_i = street + str((i+1))
if street_i in hand.board:
runitcards += hand.board[street_i]
sId = len(boardcards + runitcards) - 3
boardStreets[sId].append(boardcards + runitcards)
for i in range(len(boardStreets)):
if boardStreets[i]:
boards[allInStreets[i+1]]['board'] = boardStreets[i]
else:
for s in allInStreets:
if s in streets:
streetId = streets[s]
boards[s] = {}
boards[s]['board'] = [[]]
boards[s]['allin'] = False
return boards
def awardPots(self, hand):
holeshow = True
base, evalgame, hilo, streets, last, hrange = Card.games[hand.gametype['category']]
for pot, players in hand.pot.pots:
for p in players:
hcs = hand.join_holecards(p, asList=True)
holes = [str(c) for c in hcs[hrange[-1][0]:hrange[-1][1]] if Card.encodeCardList.get(c)!=None or c=='0x']
#log.error((p, holes))
if '0x' in holes: holeshow = False
factor = 100
if ((hand.gametype["type"]=="tour" or
(hand.gametype["type"]=="ring" and
(hand.gametype["currency"]=="play" and
(hand.sitename not in ('Winamax', 'PacificPoker'))))) and
(not [n for (n,v) in hand.pot.pots if (n % Decimal('1.00'))!=0])):
factor = 1
hiLoKey = {'h':['hi'],'l':['low'],'r':['low'],'s':['hi','low']}
#log.error((len(hand.pot.pots)>1, evalgame, holeshow))
if pokereval and len(hand.pot.pots)>1 and evalgame and holeshow: #hrange
hand.collected = [] #list of ?
hand.collectees = {} # dict from player names to amounts collected (?)
rakes, totrake, potId = {}, 0, 0
totalrake = hand.rakes.get('rake')
if not totalrake:
totalpot = hand.rakes.get('pot')
if totalpot:
totalrake = hand.totalpot - totalpot
else:
totalrake = 0
for pot, players in hand.pot.pots:
if potId ==0: pot += (sum(hand.pot.common.values()) + hand.pot.stp)
potId+=1
boards, boardId, sumpot = self.getBoardsList(hand), 0, 0
for b in boards:
boardId += (hand.runItTimes>=2)
potBoard = Decimal(int(pot/len(boards)*factor))/factor
modBoard = pot - potBoard*len(boards)
if boardId==1:
potBoard+=modBoard
holeplayers, holecards = [], []
for p in players:
hcs = hand.join_holecards(p, asList=True)
holes = [str(c) for c in hcs[hrange[-1][0]:hrange[-1][1]] if Card.encodeCardList.get(c)!=None or c=='0x']
board = [str(c) for c in b if 'omaha' in evalgame]
if 'omaha' not in evalgame:
holes = holes + [str(c) for c in b if base=='hold']
if '0x' not in holes and '0x' not in board:
holecards.append(holes)
holeplayers.append(p)
if len(holecards)>1:
try:
win = pokereval.winners(game = evalgame, pockets = holecards, board = board)
except RuntimeError:
#log.error((evalgame, holecards, board))
log.error("awardPots: error evaluating winners for hand %s %s" % (hand.handid, hand.in_path))
win = {}
win[hiLoKey[hilo][0]] = [0]
else:
win = {}
win[hiLoKey[hilo][0]] = [0]
for hl in hiLoKey[hilo]:
if hl in win and len(win[hl])>0:
potHiLo = Decimal(int(potBoard/len(win)*factor))/factor
modHiLo = potBoard - potHiLo*len(win)
if len(win)==1 or hl=='hi':
potHiLo+=modHiLo
potSplit = Decimal(int(potHiLo/len(win[hl])*factor))/factor
modSplit = potHiLo - potSplit*len(win[hl])
pnames = players if len(holeplayers)==0 else [holeplayers[w] for w in win[hl]]
for p in pnames:
ppot = potSplit
if modSplit>0:
cent = (Decimal('0.01') * (100/factor))
ppot += cent
modSplit -= cent
rake = (totalrake * (ppot/hand.totalpot)).quantize(Decimal("0.01"), rounding=ROUND_DOWN)
hand.addCollectPot(player=p,pot=(ppot-rake))
def assembleHandsPots(self, hand):
category, positions, playersPots, potFound, positionDict, showdown, allinAnte = hand.gametype['category'], [], {}, {}, {}, False, False
for p in hand.players:
playersPots[p[1]] = [0,[]]
potFound[p[1]] = [0,0]
positionDict[self.handsplayers[p[1]]['position']] = p[1]
positions.append(self.handsplayers[p[1]]['position'])
if self.handsplayers[p[1]]['sawShowdown']:
showdown = True
if self.handsplayers[p[1]]['position'] == 9 and self.handsplayers[p[1]]['winnings']>0:
allinAnte = True
positions.sort(reverse=True)
factor = 100
if ((hand.gametype["type"]=="tour" or
(hand.gametype["type"]=="ring" and
(hand.gametype["currency"]=="play" and
(hand.sitename not in ('Winamax', 'PacificPoker'))))) and
(not [n for (n,v) in hand.pot.pots if (n % Decimal('1.00'))!=0])):
factor = 1
hiLoKey = {'h':['hi'],'l':['low'],'r':['low'],'s':['hi','low']}
base, evalgame, hilo, streets, last, hrange = Card.games[category]
if ((hand.sitename != 'KingsClub' or hand.adjustCollected) and # Can't trust KingsClub draw/stud holecards
evalgame and
(len(hand.pot.pots)>1 or (showdown and (hilo=='s' or hand.runItTimes>=2))) and
allinAnte == False
):
#print 'DEBUG hand.collected', hand.collected
#print 'DEBUG hand.collectees', hand.collectees
rakes, totrake, potId = {}, 0, 0
for pot, players in hand.pot.pots:
if potId ==0: pot += (sum(hand.pot.common.values()) + hand.pot.stp)
potId+=1
boards, boardId, sumpot = self.getBoardsList(hand), 0, 0
for b in boards:
boardId += (hand.runItTimes>=2)
potBoard = Decimal(int(pot/len(boards)*factor))/factor
modBoard = pot - potBoard*len(boards)
if boardId==1:
potBoard+=modBoard
holeplayers, holecards = [], []
for p in players:
hcs = hand.join_holecards(p, asList=True)
holes = [str(c) for c in hcs[hrange[-1][0]:hrange[-1][1]] if Card.encodeCardList.get(c)!=None or c=='0x']
board = [str(c) for c in b if 'omaha' in evalgame]
if 'omaha' not in evalgame:
holes = holes + [str(c) for c in b if base=='hold']
if '0x' not in holes and '0x' not in board:
holecards.append(holes)
holeplayers.append(p)
if len(holecards)>1:
try:
win = pokereval.winners(game = evalgame, pockets = holecards, board = board)
except RuntimeError:
log.error("assembleHandsPots: error evaluating winners for hand %s %s" % (hand.handid, hand.in_path))
win = {}
win[hiLoKey[hilo][0]] = [0]
else:
win = {}
win[hiLoKey[hilo][0]] = [0]
for hl in hiLoKey[hilo]:
if hl in win and len(win[hl])>0:
potHiLo = Decimal(int(potBoard/len(win)*factor))/factor
modHiLo = potBoard - potHiLo*len(win)
if len(win)==1 or hl=='hi':
potHiLo+=modHiLo
potSplit = Decimal(int(potHiLo/len(win[hl])*factor))/factor
modSplit = potHiLo - potSplit*len(win[hl])
pnames = players if len(holeplayers)==0 else [holeplayers[w] for w in win[hl]]
for n in positions:
if positionDict[n] in pnames:
pname = positionDict[n]
ppot = potSplit
if modSplit>0:
cent = (Decimal('0.01') * (100/factor))
ppot += cent
modSplit -= cent
playersPots[pname][0] += ppot
potFound[pname][0] += ppot
data = {'potId': potId, 'boardId': boardId, 'hiLo': hl,'ppot':ppot, 'winners': [m for m in pnames if pname!=n], 'mod': ppot>potSplit}
playersPots[pname][1].append(data)
self.handsplayers[pname]['rake'] = 0
for p, (total, info) in playersPots.iteritems():
#log.error((p, (total, info)))
if hand.collectees.get(p) and info:
potFound[p][1] = hand.collectees.get(p)
for item in info:
#log.error((str(hand.handid)," winners: ",item['winners']))
split = [n for n in item['winners'] if len(playersPots[n][1])==1 and hand.collectees.get(n)!=None]
if len(info)==1:
ppot = item['ppot']
rake = ppot - hand.collectees[p]
collected = hand.collectees[p]
elif item==info[-1]:
ppot, collected = potFound[p]
rake = ppot - collected
elif len(split)>0 and not item['mod']:
ppot = item['ppot']
collected = min([hand.collectees[s] for s in split] + [ppot])
rake = ppot - collected
else:
ppot = item['ppot']
totalrake = total - hand.collectees[p]
rake = (totalrake * (ppot/total)).quantize(Decimal("0.01"))
collected = ppot - rake
potFound[p][0] -= ppot
potFound[p][1] -= collected
insert = [None, item['potId'], item['boardId'], item['hiLo'][0], hand.dbid_pids[p], int(item['ppot']*100), int(collected*100), int(rake*100)]
self.handspots.append(insert)
self.handsplayers[p]['rake'] += int(rake*100)
def setPositions(self, hand):
"""Sets the position for each player in HandsPlayers
any blinds are negative values, and the last person to act on the
first betting round is 0
NOTE: HU, both values are negative for non-stud games
NOTE2: I've never seen a HU stud match"""
actions = hand.actions[hand.holeStreets[0]]
# Note: pfbao list may not include big blind if all others folded
players = self.pfbao(actions)
# set blinds first, then others from pfbao list, avoids problem if bb
# is missing from pfbao list or if there is no small blind
sb, bb, bi, ub, st = False, False, False, False, False
if hand.gametype['base'] == 'stud':
# Stud position is determined after cards are dealt
# First player to act is always the bring-in position in stud
# even if they decided to bet/completed
if len(hand.actions[hand.actionStreets[1]])>0:
bi = [hand.actions[hand.actionStreets[1]][0][0]]
#else:
# TODO fix: if ante all and no actions and no bring in
# bi = [hand.actions[hand.actionStreets[0]][0][0]]
else:
ub = [x[0] for x in hand.actions[hand.actionStreets[0]] if x[1] == 'button blind']
bb = [x[0] for x in hand.actions[hand.actionStreets[0]] if x[1] == 'big blind']
sb = [x[0] for x in hand.actions[hand.actionStreets[0]] if x[1] == 'small blind']
st = [x[0] for x in hand.actions[hand.actionStreets[0]] if x[1] == 'straddle']
# if there are > 1 sb or bb only the first is used!
if ub:
self.handsplayers[ub[0]]['street0InPosition'] = True
if ub[0] not in players: players.append(ub[0])
if bb:
self.handsplayers[bb[0]]['position'] = 'B'
self.handsplayers[bb[0]]['street0InPosition'] = True
if bb[0] in players: players.remove(bb[0])
if sb:
self.handsplayers[sb[0]]['position'] = 'S'
self.handsplayers[sb[0]]['street0FirstToAct'] = True
if sb[0] in players: players.remove(sb[0])
if bi:
self.handsplayers[bi[0]]['position'] = 'S'
self.handsplayers[bi[0]]['street0FirstToAct'] = True
if bi[0] in players: players.remove(bi[0])
if st and st[0] in players:
players.insert(0, players.pop())
#print "DEBUG: actions: '%s'" % actions
#print "DEBUG: ub: '%s' bb: '%s' sb: '%s' bi: '%s' plyrs: '%s'" %(ub, bb, sb, bi, players)
for i,player in enumerate(reversed(players)):
self.handsplayers[player]['position'] = i
self.hands['maxPosition'] = i
if i==0 and hand.gametype['base'] == 'stud':
self.handsplayers[player]['street0InPosition'] = True
elif (i-1)==len(players):
self.handsplayers[player]['street0FirstToAct'] = True
def assembleHudCache(self, hand):
# No real work to be done - HandsPlayers data already contains the correct info
pass
def vpip(self, hand):
vpipers = set()
bb = [x[0] for x in hand.actions[hand.actionStreets[0]] if x[1] in ('big blind', 'button blind')]
for act in hand.actions[hand.actionStreets[1]]:
if act[1] in ('calls','bets', 'raises', 'completes'):
vpipers.add(act[0])
self.hands['playersVpi'] = len(vpipers)
for player in hand.players:
pname = player[1]
player_stats = self.handsplayers.get(pname)
if pname in vpipers:
player_stats['street0VPI'] = True
elif pname in hand.sitout:
player_stats['street0VPIChance'] = False
player_stats['street0AggrChance'] = False
if len(vpipers)==0 and bb:
self.handsplayers[bb[0]]['street0VPIChance'] = False
self.handsplayers[bb[0]]['street0AggrChance'] = False
def playersAtStreetX(self, hand):
""" playersAtStreet1 SMALLINT NOT NULL, /* num of players seeing flop/street4/draw1 */"""
# self.actions[street] is a list of all actions in a tuple, contining the player name first
# [ (player, action, ....), (player2, action, ...) ]
# The number of unique players in the list per street gives the value for playersAtStreetXXX
# FIXME?? - This isn't couting people that are all in - at least showdown needs to reflect this
# ... new code below hopefully fixes this
# partly fixed, allins are now set as seeing streets because they never do a fold action
self.hands['playersAtStreet1'] = 0
self.hands['playersAtStreet2'] = 0
self.hands['playersAtStreet3'] = 0
self.hands['playersAtStreet4'] = 0
self.hands['playersAtShowdown'] = 0
# alliners = set()
# for (i, street) in enumerate(hand.actionStreets[2:]):
# actors = set()
# for action in hand.actions[street]:
# if len(action) > 2 and action[-1]: # allin
# alliners.add(action[0])
# actors.add(action[0])
# if len(actors)==0 and len(alliners)<2:
# alliners = set()
# self.hands['playersAtStreet%d' % (i+1)] = len(set.union(alliners, actors))
#
# actions = hand.actions[hand.actionStreets[-1]]
# print "p_actions:", self.pfba(actions), "p_folds:", self.pfba(actions, l=('folds',)), "alliners:", alliners
# pas = set.union(self.pfba(actions) - self.pfba(actions, l=('folds',)), alliners)
# hand.players includes people that are sitting out on some sites for cash games
# actionStreets[1] is 'DEAL', 'THIRD', 'PREFLOP', so any player dealt cards
# must act on this street if dealt cards. Almost certainly broken for the 'all-in blind' case
# and right now i don't care - CG
p_in = set([x[0] for x in hand.actions[hand.actionStreets[1]]])
#Add in players who were allin blind
if hand.pot.pots:
if len(hand.pot.pots[0][1])>1:
p_in = p_in.union(hand.pot.pots[0][1])
p_in = p_in.union(hand.pot.common.keys())
#
# discover who folded on each street and remove them from p_in
#
# i values as follows 0=BLINDSANTES 1=PREFLOP 2=FLOP 3=TURN 4=RIVER
# (for flop games)
#
# At the beginning of the loop p_in contains the players with cards
# at the start of that street.
# p_in is reduced each street to become a list of players still-in
# e.g. when i=1 (preflop) all players who folded during preflop
# are found by pfba() and eliminated from p_in.
# Therefore at the end of the loop, p_in contains players remaining
# at the end of the action on that street, and can therefore be set
# as the value for the number of players who saw the next street
#
# note that i is 1 in advance of the actual street numbers in the db
#
# if p_in reduces to 1 player, we must bomb-out immediately
# because the hand is over, this will ensure playersAtStreetx
# is accurate.
#
for (i, street) in enumerate(hand.actionStreets):
if (i-1) in (1,2,3,4):
# p_in stores players with cards at start of this street,
# so can set streetxSeen & playersAtStreetx with this information
# This hard-coded for i-1 =1,2,3,4 because those are the only columns
# in the db! this code section also replaces seen() - more info log 66
# nb i=2=flop=street1Seen, hence i-1 term needed
self.hands['playersAtStreet%d' % (i-1)] = len(p_in)
for player_with_cards in p_in:
self.handsplayers[player_with_cards]['street%sSeen' % (i-1)] = True
players = self.pfbao(hand.actions[street], f=('discards','stands pat'))
if len(players)>0:
self.handsplayers[players[0]]['street%dFirstToAct' % (i-1)] = True
self.handsplayers[players[-1]]['street%dInPosition' % (i-1)] = True
#
# find out who folded, and eliminate them from p_in
#
actions = hand.actions[street]
p_in = p_in - self.pfba(actions, l=('folds',))
#