Merge claude/rake-live (3f59852): Rake in den Live-Entscheidungen

Tor am Micro-Tisch mit Rake: +4,60 +-0,99 bb/100, kein Verlierer (10 Gewinner, 10 offen),
Station allein -0,02 +-0,07, LBR nicht schlechter (-65 +-67). Schalter RAKE_LIVE, aus bit-identisch.
Owner-OK 15.11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 12:03:18 +01:00
co-authored by Claude Opus 5.5
31 changed files with 1204 additions and 54 deletions
+143
View File
@@ -0,0 +1,143 @@
# Rake in der Live-Entscheidung (`RAKE_LIVE`), 15.11.
Zweig `claude/rake-live`, abgezweigt vom Live-Stand `claude/engine-lecks-angreifen-de7b88` @62e51bb.
Der Schalter ist `RAKE_LIVE=1` und steht standardmäßig auf aus. Ist er aus, rechnet der Kern Bit für Bit wie 62e51bb (unten bewiesen).
## 1. Was der Tisch wirklich nimmt (gemessen)
Ausgezählt wurden 857 Hände der zwei Mikro-Läufe vom 14.11. (NL 0.01/0.02, 16 Tische). Verglichen wurde je Hand `game.winnerInfo` mit `potAmount` und `potAmountAfterRake`.
- Der Tisch nimmt **5 % des Topfs, auf den Cent gerundet (genau ein halber Cent rundet zur geraden Zahl), gedeckelt bei 0.20 = 10 bb.** Bei 425 von 429 Flop-Händen stimmt das auf den Cent.
- Es gilt **kein „no flop, no drop“.** 50 von 428 Händen ohne Flop zahlten, nämlich jeder Topf ab 0.11. Töpfe bis 0.10 zahlen nichts.
- In bb heißt das: Schritt 0.5 bb, Deckel 10 bb. Das ist `RakeRule::MICRO_BB`.
Das alte Modell ist `RakeRule::MEASURED_BB`. Es stammt von einem 1000/2000-Tisch: Deckel **1 bb**, ein Fold zahlt nichts, dazu Antes von 0.16 bb. An den Mikro-Tischen ist es um eine Größenordnung falsch. Die Mikro-Tische haben auch keine Ante; das hat preflop-voll ebenfalls gefunden (`PREFLOP_OHNE_ANTE`).
## 2. Bestand: wer rechnet den Rake mit?
| Entscheidungsweg | vorher | mit `RAKE_LIVE=1` |
|---|---|---|
| Heuristik: EV von Check, Call und Raise (`odds::ev`) | roher Topf | Topf nach Rake (`rake::live::net`), auch der Topf, den ein Fold gewinnt |
| Break-even und MDF-Boden (`odds::break_even`) | roh | `to_call / net(pot + to_call)` |
| Bluff-Zweige, Raise-Antwort (`engine::bluff`) und Schranke für reine Bluffs (`engine::options`) | roh | net |
| River-Veto, also der River-Baum v1 (`cfr::river::tree_with_chance`) | roh | jedes Blatt gerakt (`Payoff::with_live_rake`) |
| River-Spiel: DBR, Nash und Audit (`cfr::river_game`) | roh | jedes Blatt gerakt |
| Turn+River-Spiel: Arm TURN_SPIEL und Turn-Audit (`cfr::turn_river_game`) | roh | Fold- und Showdown-Blätter gerakt |
| Open-Jam (`preflop::open_jam`, Schalter `OPEN_JAM`) | roh | `need = call / net(pot)` |
| Audit Jam und All-in (`engine::audit_allin`), Audit-Einstieg (`engine::audit`) | roh | Rake-Scope und net |
| Preflop-Tabellen Heads-up (`generated_charts`) | **Rake von 1000/2000** (Deckel 1 bb, Fold frei) und 0.96 bb Antes | **offen, Stufe 2:** `chartgen charts --rake mikro` gebaut, die Tabelle wird gerechnet (Warteschlange `rake-charts`) |
| Preflop-Tabellen Multiway (`generated_charts_multi`) | Rake von 1000/2000 | offen (Rest) |
| Turn-Veto (`cfr::turn_river`, Flat-Blätter; Veto aus) | roh | offen (Rest, Veto nicht live) |
| ICM-Push/Fold, Turnier | kein Rake | bleibt ohne Rake (richtig: ein Turnier zahlt keinen Rake pro Topf; `Scope::none`) |
| Python `entscheiden/decide.py` | nur Hülle um den Kern | nichts zu tun |
| Simulator-Leiter | Tisch ohne Rake | `SIM_RAKE=mikro` setzt den Mikro-Tisch (`TableCost::MICRO`) |
| LBR | Spiel ohne Rake | unverändert: misst, ob der gerakte Kern im freien Spiel ausbeutbarer wird |
So ist es gebaut: `rake::live` hält einen thread-lokalen Scope mit dem Big Blind des Spots. `engine::decide::decide_with` betritt ihn nur bei einem Cash-Spot (`lage` = None) und nur, wenn `RAKE_LIVE=1` gesetzt ist. Ohne Scope gibt `net(pot)` den Topf unverändert zurück. Ein Blatt der Löser wird nur gerakt, wenn der Rake größer als 0 ist. Ist der Schalter aus, ändert sich also nichts.
## 3. Beweis „aus = unverändert“
**Nach dem Merge des Live-Stands 43e566f (b4fb579) noch einmal gezeigt:** 1767 Postflop- und 2776 Preflop-Spots sind ohne Schalter byte-gleich mit 43e566f (`43e566f/*_basis` = `*_aus`). Das Nachspiel mit Schalter ist unverändert: 20 Aktionen gekippt, +21.94 bb (`nachspiel_postflop_43e566f.md`).
Der erste Nachweis gegen 62e51bb:
- **Postflop:** 1767 echte, entdoppelte Postflop-Spots aus den Schatten-Mitschrieben und `tests/live_fixture/`. Die Ausgabe des Zweigs ohne Schalter ist byte-gleich mit 62e51bb (`post_basis.jsonl` = `post_aus.jsonl`).
- **Preflop:** 2776 Preflop-Spots von preflop-voll sind ebenfalls byte-gleich (`pre_basis` = `pre_aus`).
## 4. Wirkung auf echte Spots (`nachspiel_postflop.md`)
Dieselben 1767 Postflop-Spots liefen mit dem Schalter an. **20 Aktionen kippen** (1.1 %), 4 weitere ändern nur die Größe.
| Straße | Spots | gekippt | Richtung | im Audit | Rake-blind kostet laut Audit (mit Rake) |
|---|---|---|---|---|---|
| Flop | 816 | 7 | Call→Fold 6, Raise→Check 1 | 0 (kein Flop-Löser bzw. multiway) | – |
| Turn | 578 | 8 | Call→Fold 6, Raise→Check 1, Raise→Fold 1 | 8 | **+23.68 bb** |
| River | 373 | 5 | Raise→Check 5 | 5 | −1.73 bb |
| **alle** | 1767 | 20 | | 13 | **+21.94 bb** |
Ein positiver Wert heißt: Das Rake-blinde Spiel verliert so viel mehr gegen die Lösung.
- **Ein Spot trägt fast alles:** Zeile 345, Turn, Call 1.04 in einen Topf von 2.81 mit einem Kombi-Draw. Der gerakte Kern foldet, das Audit sagt: Der Call kostet 21.72 bb. Ohne diesen Spot bleiben auf dem Turn +1.96 bb über 7 Spots.
- **Der River verliert leicht:** Fünf kleine Luft-Bluffs entfallen, das kostet −1.73 bb. Das Audit hält sie für gut. Der erste Durchlauf hatte noch 12 solcher Entfallen; die Bluff-Schranke auf den Netto-Topf hat das auf 5 gedrückt.
- **Preflop: 0 von 2776 kippen.** Preflop entscheiden die Tabellen, und die sind erst mit Stufe 2 gerakt. Open-Jam ist live aus.
Ehrlich gesagt ist die Wirkung klein und rauschig: 13 Spots im Audit, einer davon dominiert. Die Richtung stimmt (Calls mit knapper Equity entfallen), der Betrag ist nicht belastbar.
## 5. Gepaarte Messungen (eingereiht, laufen im Engine-Starter)
Eingetragen in `messung_engine/warteschlange.txt`:
| id | was | Schalter |
|---|---|---|
| `rake-basis` / `rake-an` | Leiter, 20 Zeilen, 2000/4000/4, gepaart, **am gerakten Mikro-Tisch** | `SIM_RAKE=mikro` bzw. dazu `RAKE_LIVE=1` |
| `rake-lbr-aus` / `rake-lbr-an` | LBR, 2000 Hände | – bzw. `RAKE_LIVE=1` |
Auswertung der Leiter:
```
python messung_engine/ab.py D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-basis D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-an
```
Die Leiter ohne Rake im Simulator wäre sinnlos: Dort ist der Rake-blinde Kern per Definition richtig.
## 6. Schaltvorschlag
**Stufe 1 (Postflop, dieser Commit):** `RAKE_LIVE=1` live setzen, **wenn** beide Bedingungen gelten:
1. Die Leiter `rake-an` gegen `rake-basis` zeigt am Mikro-Tisch keinen Verlierer: keine Zeile signifikant schlechter, Summe nicht negativ.
2. `rake-lbr-an` ist nicht schlechter als `rake-lbr-aus`, innerhalb des Fehlers.
Erwartet wird ein kleiner Gewinn: weniger Calls mit knapper Equity, ein paar Mikro-Bluffs weniger. Das Audit sagt +22 bb auf 1767 Spots, getragen von einem Spot. Es ist ein reiner Korrektheitsschritt: Der Kern rechnet dann den Topf, den er wirklich bekommt. Verliert die Leiter, bleibt der Schalter aus; dann zuerst die River-Bluff-Schranke prüfen, denn dort zeigt das Audit den einzigen Verlust.
**Stufe 2 (Preflop-Tabellen) übernimmt preflop-voll** (abgestimmt am 15.11.). Es gibt EINEN Lauf „Live-Mikro“: Antes 0 plus `ChartRake::Micro`, für charts, multi, multi-deep und teilspiel (`pokerbench-preflop-mikro`). Der Job `rake-charts` (Mikro-Rake mit Antes) ist verworfen. Vorgeschlagen ist ein eigener Schalter, der nur unter `rake::live::active()` greift; dann lässt sich jede Stufe gepaart für sich messen. Offen in den Tabellen-Spielen bleibt der Preflop-Fold-Topf ab 5.5 bb, der am Tisch 0.5 bb zahlt.
Der ursprüngliche Plan war:
1. `messung_engine/logs/rake-charts.log` nach LF normalisieren und als `src/preflop/generated_charts_mikro.rs` ablegen.
2. In `preflop::generated_lookup` bei `rake::live::active()` die Mikro-Tabellen für NLHE und AOF wählen.
3. Die Preflop-Spots nachspielen und die Leiter erneut paaren.
Wichtig für Stufe 2: Die Mikro-Tabellen rechnen noch mit 0.96 bb Antes, so wie die alten. Die richtige Kombination ist Mikro-Rake **und** ante-frei, zusammen mit `PREFLOP_OHNE_ANTE` von preflop-voll. Am besten gibt es einen gemeinsamen Lauf `chartgen charts --rake mikro` ohne Ante, sonst misst man zwei Fehler gegeneinander.
**Rest:** die Multiway-Tabellen (gleiches Vorgehen), das Turn-Veto (nicht live) und der Preflop-Fold-Rake in den Tabellen-Spielen. Dazu kommt das Modell „Rake des Topfs, wie er jetzt endet“: Spätere Straßen sind nicht modelliert, genau wie in `odds::ev`.
## 7. Specs
- `tests/rake_rule.rs`: 22 grün, davon 6 neu für die Mikro-Regel und `ChartRake::Micro`.
- `tests/rake_live.rs`: 7 grün, neu. Ohne Scope bitgleich; Preis nach Rake; Rake auch beim Gewinn durch Fold; Deckel; gerakte Blätter für Sieg, Niederlage und Split; River-Bäume roh ohne Scope und gerakt mit Scope.
- Unit-Tests `rake::`, `cfr::river`, `cfr::turn_river_game`, `odds::`, `engine::bluff`, `engine::audit`, `preflop::open_jam`: 29 grün.
Die Specs liefen einzeln, nicht über `tests/lauf.py`.
## Dateien
- `spots_ziehen.py`: zieht die Postflop-Spots.
- `nachspiel.py`: Vergleich mit und ohne Schalter plus Audit der gekippten Spots.
- `nachspiel_postflop.md`: der Einzelnachweis.
- `*_anfragen.jsonl`, `post_*.jsonl`, `pre_*.jsonl`: Eingaben und Antworten.
- `bin/pokerbench-rake-*.exe`: Mess-Binaries.
## 8. Urteil der ersten Messung und Nachbesserung (15.11. mittags)
Erste Messung mit Cent-Stufe im Entscheidungs-Rake (`URTEIL.md`):
- Leiter gesamt **+4.43 ±1.01 bb/100**: 12 Gegner gewinnen, 7 offen, **station −0.16 ±0.16 ist Verlierer**.
- LBR an−aus −64.3 ±69.6, also nicht schlechter.
- Nach der Regel bleibt der Schalter damit aus.
**Ursache, zerlegt mit `diag_rake station` mit und ohne Schalter, verglichen mit `diag_diff.py`:**
- Das Orakel-Lesen gegen die station reproduziert den Verlust: −0.19 bb/100.
- **Fast alles sind River- und Turn-Value-Bets, die auf die kleinere Größe wechseln**, z. B. Topf 13.89: 9.26 → 4.63, Topf 2: 2 → 1.33.
- Zwei Gründe:
1. Die **Cent-Stufe** im Entscheidungsmodell. Ein Pot-Bet in 2 bb zahlte gerundet 0.5 bb, zwei Drittel Pot zahlten 0. Das sind künstliche EV-Sprünge zwischen Nachbargrößen. Am Tisch ist die Rundung echt. Aber die Entscheidung kennt den Endtopf nicht, und über diese Unsicherheit mittelt sich die Rundung weg. Behoben mit `rake::live::DECISION_RULE`: 5 % glatt, Deckel 10 bb. Das halbiert die geänderten Hände (46 → 16).
2. Der Rest, −0.05 bb/100 ohne Größenmix: Das Modell setzt die Equity im gecallten Fall gegen die station pessimistisch an, etwa 0.53. Mit 5 % Rake lohnen die Zusatz-Chips eines großen Value-Bets dann kaum noch (2·0.53·0.95 ≈ 1). Das ist kein Rake-Fehler. Der Rake legt eine Modellschwäche frei, nämlich die Spanne, mit der die station callt.
- Ausgeschaltet ist der Kern weiter byte-gleich mit 43e566f.
**Nachmessung eingereiht:**
- `rake-glatt-an` gegen das fertige `rake-basis`, mit FRUEHSTOPP.
- `rake-glatt-lbr-an` gegen das fertige `rake-lbr-aus`.
- Auswertung: `python messung_rake/auswerten.py glatt`.
## 9. Urteil der Nachmessung mit glattem Entscheidungs-Rake (`URTEIL_glatt.md`)
- **Leiter gesamt +4.60 ±0.99 bb/100, GEWINNER, kein Gegner verliert.** 10 Gegner gewinnen, 10 sind offen.
- **station:** −0.05 ±0.12 in der vollen Leiter, mit 64000 Deals allein −0.02 ±0.07. Beides ist offen; der Verlust ist weg.
- **LBR:** an−aus −65.0 ±66.7 bb/100, also nicht schlechter.
- **Vorschlag: `RAKE_LIVE=1` live setzen.** Den Zweig claude/rake-live dafür mergen; mit Schalter aus ist er bitgleich zu 43e566f.
+46
View File
@@ -0,0 +1,46 @@
# RAKE_LIVE Stufe 1: Urteil
## Leiter am Mikro-Tisch (SIM_RAKE=mikro), an - basis
```
A = D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-basis
B = D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-an
Gegner B-A bb/100 ±95% Deals geaendert Urteil
3bet-folder +1.88 3.59 8000 222 offen
balanciert +7.60 6.11 8000 422 GEWINNER
cbet-folder +8.38 7.66 8000 790 GEWINNER
check-raiser -1.07 5.03 8000 310 offen
fish +3.03 2.38 16000 1256 GEWINNER
gto +1.39 2.84 8000 318 offen
maniac +7.12 5.66 16000 1362 GEWINNER
micro-passiv -0.06 4.43 8000 635 offen
nemesis-1 +10.43 4.38 16000 553 GEWINNER
nemesis-2 +3.64 4.87 16000 881 offen
nemesis-3 +3.83 2.01 16000 253 GEWINNER
nit +1.95 1.91 16000 161 GEWINNER
polar +7.74 4.28 8000 396 GEWINNER
position +2.47 5.18 8000 353 offen
reg +6.12 3.01 16000 577 GEWINNER
station -0.16 0.16 16000 150 VERLIERER
tanker +8.53 4.39 8000 281 GEWINNER
textur-cbet +6.64 5.65 8000 249 GEWINNER
umgekehrt +1.66 4.85 8000 684 offen
wert-sizer +7.49 5.05 8000 288 GEWINNER
GESAMT +4.43 1.01 (Strata gleich gewichtet) GEWINNER
Kein Profil verliert: NEIN
```
## LBR (Konter gewinnt, bb/100; kleiner = besser)
| Arm | Hände | bb/100 | ±95 % |
|---|---|---|---|
| aus | 2000 | +587.4 | 125.6 |
| an | 2000 | +523.1 | 118.9 |
| **an − aus gepaart** | 2000 | **-64.3** | 69.6 |
## Urteil
- Leiter: VERLIERER (mind. eine Zeile oder gesamt sicher unter 0)
- LBR: nicht schlechter
- **Vorschlag: RAKE_LIVE bleibt aus.** Erst die Verlierer-Zeile(n) verstehen (Kandidat: River-Bluff-Schranke, dort zeigte das Audit den einzigen Verlust).
+58
View File
@@ -0,0 +1,58 @@
# RAKE_LIVE Stufe 1: Urteil (rake-glatt-an)
## Leiter am Mikro-Tisch (SIM_RAKE=mikro), an - basis
```
A = D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-basis
B = D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-glatt-an
Gegner B-A bb/100 ±95% Deals geaendert Urteil
3bet-folder +2.15 4.01 8000 224 offen
balanciert +2.87 6.16 8000 390 offen
cbet-folder +9.14 7.67 8000 695 GEWINNER
check-raiser +1.99 3.97 8000 314 offen
fish +3.15 2.21 16000 748 GEWINNER
gto +1.83 2.93 8000 328 offen
maniac +8.13 5.53 16000 1137 GEWINNER
micro-passiv +1.27 4.74 8000 495 offen
nemesis-1 +8.91 4.41 16000 610 GEWINNER
nemesis-2 +4.39 4.43 16000 732 offen
nemesis-3 +4.06 1.95 16000 234 GEWINNER
nit +1.95 1.95 16000 161 offen
polar +7.75 4.89 8000 380 GEWINNER
position +4.70 5.41 8000 400 offen
reg +5.64 3.34 16000 641 GEWINNER
station -0.05 0.12 16000 57 offen
tanker +8.22 4.12 8000 288 GEWINNER
textur-cbet +8.54 5.45 8000 300 GEWINNER
umgekehrt -0.94 3.84 8000 589 offen
wert-sizer +8.18 5.09 8000 263 GEWINNER
GESAMT +4.60 0.99 (Strata gleich gewichtet) GEWINNER
Kein Profil verliert: ja
```
## station allein (16 Ziehungen), an - basis
```
A = D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-station-basis
B = D:\Projects\pokerfreak\.claude\worktrees\determined-herschel-cdaa65\messung_rake\arme\rake-station-an
Gegner B-A bb/100 ±95% Deals geaendert Urteil
station -0.02 0.07 64000 229 offen
GESAMT -0.02 0.07 (Strata gleich gewichtet) offen
Kein Profil verliert: ja
```
## LBR (Konter gewinnt, bb/100; kleiner = besser)
| Arm | Hände | bb/100 | ±95 % |
|---|---|---|---|
| aus | 2000 | +587.4 | 125.6 |
| an | 2000 | +522.4 | 120.0 |
| **an − aus gepaart** | 2000 | **-65.0** | 66.7 |
## Urteil
- Leiter: kein Verlierer
- LBR: nicht schlechter
- **Vorschlag: RAKE_LIVE=1 live setzen** (Zweig claude/rake-live, aus bitgleich). Stufe 2 (Preflop-Tabellen Mikro ohne Antes) folgt von preflop-voll.
+86
View File
@@ -0,0 +1,86 @@
"""Urteil RAKE_LIVE Stufe 1: Leiter gepaart am Mikro-Tisch + LBR gepaart, mit Schaltvorschlag.
python messung_rake/auswerten.py (Pfade fest: arme/rake-basis, arme/rake-an, lbr/rake-lbr-*.txt)
python messung_rake/auswerten.py glatt (an-Arm = arme/rake-glatt-an, lbr/rake-glatt-lbr-an.txt)
Leiter: `messung_engine/ab.py` (je Gegner Delta an - basis in bb/100, 95 %-KI, gepoolt, Urteil).
LBR: je Hand `i wert_bb` (was der beste lokale Konter gegen den Kern gewinnt); gepaart ueber `i`
(Hand i ist deterministisch), Delta an - aus in bb/100 mit 95 %-KI. Positiv = ausbeutbarer = schlechter.
Schaltregel (BERICHT.md 6): Leiter kein Verlierer (keine Zeile mit KI ganz unter 0, Summe nicht
negativ) UND LBR nicht schlechter (KI des Deltas nicht ganz ueber 0).
"""
import math
import os
import subprocess
import sys
HIER = os.path.dirname(os.path.abspath(__file__))
AB = r"D:\Projects\pokerfreak\.claude\worktrees\engine-lecks-angreifen-de7b88\messung_engine\ab.py"
Z = 1.959964
def lbr(pfad):
werte = {}
if os.path.exists(pfad):
for z in open(pfad, encoding="utf-8"):
t = z.split()
if len(t) == 2:
werte[int(t[0])] = float(t[1])
return werte
def mittel_ki(xs):
n = len(xs)
if n < 2:
return float("nan"), float("nan"), n
m = sum(xs) / n
v = sum((x - m) ** 2 for x in xs) / (n - 1)
return 100 * m, 100 * Z * math.sqrt(v / n), n
def main():
sys.stdout.reconfigure(encoding="utf-8")
arm = "rake-glatt-an" if sys.argv[1:] == ["glatt"] else "rake-an"
lbr_an = "rake-glatt-lbr-an.txt" if arm == "rake-glatt-an" else "rake-lbr-an.txt"
basis, an = os.path.join(HIER, "arme", "rake-basis"), os.path.join(HIER, "arme", arm)
print(f"# RAKE_LIVE Stufe 1: Urteil ({arm})\n")
print("## Leiter am Mikro-Tisch (SIM_RAKE=mikro), an - basis\n")
leiter = subprocess.run([sys.executable, AB, basis, an], capture_output=True, text=True, encoding="utf-8", env=dict(os.environ, PYTHONIOENCODING="utf-8"))
print("```\n" + leiter.stdout.strip() + ("\n" + leiter.stderr.strip() if leiter.stderr.strip() else "") + "\n```\n")
verlierer = "VERLIERER" in leiter.stdout
st_basis, st_an = os.path.join(HIER, "arme", "rake-station-basis"), os.path.join(HIER, "arme", "rake-station-an")
station_fertig = True
if arm == "rake-glatt-an":
print("## station allein (16 Ziehungen), an - basis\n")
st = subprocess.run([sys.executable, AB, st_basis, st_an], capture_output=True, text=True, encoding="utf-8", env=dict(os.environ, PYTHONIOENCODING="utf-8"))
print("```\n" + st.stdout.strip() + ("\n" + st.stderr.strip() if st.stderr.strip() else "") + "\n```\n")
verlierer = verlierer or "VERLIERER" in st.stdout
n = lambda d: len(os.listdir(d)) if os.path.isdir(d) else 0
station_fertig = n(st_an) >= 16 and n(st_an) == n(st_basis) and "GESAMT" in st.stdout
aus, ein = lbr(os.path.join(HIER, "lbr", "rake-lbr-aus.txt")), lbr(os.path.join(HIER, "lbr", lbr_an))
gemeinsam = sorted(set(aus) & set(ein))
ma, ka, na = mittel_ki(list(aus.values()))
me, ke, ne = mittel_ki(list(ein.values()))
md, kd, nd = mittel_ki([ein[i] - aus[i] for i in gemeinsam])
print("## LBR (Konter gewinnt, bb/100; kleiner = besser)\n")
print("| Arm | Hände | bb/100 | ±95 % |\n|---|---|---|---|")
print(f"| aus | {na} | {ma:+.1f} | {ka:.1f} |\n| an | {ne} | {me:+.1f} | {ke:.1f} |")
print(f"| **an − aus gepaart** | {nd} | **{md:+.1f}** | {kd:.1f} |\n")
lbr_schlechter = nd >= 2 and md - kd > 0
print("## Urteil\n")
print(f"- Leiter: {'VERLIERER (mind. eine Zeile oder gesamt sicher unter 0)' if verlierer else 'kein Verlierer'}")
print(f"- LBR: {'SCHLECHTER (KI ganz ueber 0)' if lbr_schlechter else 'nicht schlechter'}")
zellen = lambda d: sorted(os.listdir(d)) if os.path.isdir(d) else []
vollstaendig = station_fertig and zellen(an) and zellen(an) == zellen(basis) and nd >= 2000 and "GESAMT" in leiter.stdout
if not vollstaendig:
print(f"- **UNVOLLSTAENDIG** (an-Zellen {len(zellen(an))}/{len(zellen(basis))}, LBR gepaart {nd}/2000): kein Urteil.")
elif verlierer or lbr_schlechter:
print("- **Vorschlag: RAKE_LIVE bleibt aus.** Erst die Verlierer-Zeile(n) mit `diag_rake` + `diag_diff.py` zerlegen (BERICHT.md 8).")
else:
print("- **Vorschlag: RAKE_LIVE=1 live setzen** (Zweig claude/rake-live, aus bitgleich). Stufe 2 (Preflop-Tabellen Mikro ohne Antes) folgt von preflop-voll.")
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
"""Diff zweier diag_rake-Ausgaben (aus, an): je Hand mit anderer Entscheidungsfolge die erste
abweichende Entscheidung, Netto-Delta (an - aus, bb) summiert nach Strasse und Richtung.
python messung_rake/diag_diff.py <aus.txt> <an.txt> [beispiele]
"""
import collections
import sys
def lies(p):
out = []
for z in open(p, encoding="utf-8"):
t = z.split()
out.append((float(t[2]), t[3:]))
return out
def art(c):
return c[0] if c[0] != "R" else "R"
def main():
a, b = lies(sys.argv[1]), lies(sys.argv[2])
n_bsp = int(sys.argv[3]) if len(sys.argv) > 3 else 12
summe = collections.defaultdict(lambda: [0, 0.0])
bsp = collections.defaultdict(list)
gesamt = 0.0
for i, ((na, da), (nb, db)) in enumerate(zip(a, b)):
gesamt += nb - na
if da == db:
continue
k = next(j for j in range(max(len(da), len(db))) if j >= len(da) or j >= len(db) or da[j] != db[j])
x = da[k].split(":") if k < len(da) else ["-"] * 5
y = db[k].split(":") if k < len(db) else ["-"] * 5
schl = (x[0], f"{art(x[3])}->{art(y[3])}" if x[0] != "-" and y[0] != "-" else "laenge")
summe[schl][0] += 1
summe[schl][1] += nb - na
bsp[schl].append(f"hand {i}: aus {' '.join(da[k:])} | an {' '.join(db[k:])} | delta {nb - na:+.2f}")
h = len(a)
print(f"Haende {h}, Delta gesamt {gesamt:+.2f} bb = {100 * gesamt / h:+.3f} bb/100\n")
print("| Strasse | aus->an | Haende | Delta bb | bb/100 |\n|---|---|---|---|---|")
for s, (n, d) in sorted(summe.items(), key=lambda kv: kv[1][1]):
print(f"| {s[0]} | {s[1]} | {n} | {d:+.2f} | {100 * d / h:+.3f} |")
for s, (n, d) in sorted(summe.items(), key=lambda kv: kv[1][1])[:3]:
print(f"\n### {s}")
for e in bsp[s][:n_bsp]:
print("- " + e)
if __name__ == "__main__":
main()
+105
View File
@@ -0,0 +1,105 @@
"""Rake-Nachspiel: dieselben echten Anfragen ohne und mit RAKE_LIVE, was kippt und was es laut Audit kostet.
python messung_rake/nachspiel.py <anfragen.jsonl> <aus.jsonl> <an.jsonl> <rechner.exe-ordner> > bericht.md
- `aus`/`an`: die Antworten des Kerns ohne / mit RAKE_LIVE=1 auf dieselben Zeilen (Zeile fuer Zeile).
- Fuer jede gekippte Entscheidung beide Aktionen ins Audit (`audit.exe`, plan D4), einmal mit Rake
(RAKE_LIVE=1: die Loesung zahlt den Mikro-Rake) und einmal ohne. Kosten des Rake-blinden Spiels =
Verlust(Aktion aus) - Verlust(Aktion an), im gerakten Audit, in bb. ABSTAIN spielt live als Check,
sonst Fold.
"""
import collections
import json
import os
import subprocess
import sys
def zeilen(p):
return [json.loads(z) for z in open(p, encoding="utf-8-sig") if z.strip()]
def gespielt(anfrage, antwort):
a = antwort["action"]
if a == "ABSTAIN":
a = "CHECK" if "CHECK" in anfrage.get("legalActions", []) else "FOLD"
menge = antwort.get("size") if a in ("BET", "RAISE", "ALL_IN") else None
if a == "ALL_IN" and menge is None:
menge = anfrage.get("maxRaiseTo")
return {"action": a, "amount": menge}
def audit(exe, zeilen_ein, rake):
env = dict(os.environ)
env.pop("RAKE_LIVE", None)
if rake:
env["RAKE_LIVE"] = "1"
ein = "".join(json.dumps(z) + "\n" for z in zeilen_ein)
aus = subprocess.run([exe], input=ein, capture_output=True, text=True, env=env, encoding="utf-8").stdout
return [json.loads(z) for z in aus.splitlines() if z.strip()]
def main():
anfragen, aus, an, ordner = zeilen(sys.argv[1]), zeilen(sys.argv[2]), zeilen(sys.argv[3]), sys.argv[4]
exe = os.path.join(ordner, "audit.exe")
n = collections.Counter()
kipp = collections.Counter()
wege = collections.defaultdict(collections.Counter)
groesse = collections.Counter()
faelle = []
for i, (q, x, y) in enumerate(zip(anfragen, aus, an)):
s = q.get("street")
n[s] += 1
gx, gy = gespielt(q, x), gespielt(q, y)
if gx["action"] != gy["action"]:
kipp[s] += 1
wege[s][f"{gx['action']}->{gy['action']}"] += 1
faelle.append((i, q, gx, gy))
elif gx != gy:
groesse[s] += 1
print(f"# Rake-Nachspiel: {sys.argv[1]}\n")
print(f"Anfragen {len(anfragen)}; Aktion gekippt {sum(kipp.values())}, nur Groesse anders {sum(groesse.values())}.\n")
print("| Strasse | Spots | Aktion gekippt | nur Groesse | Richtungen |\n|---|---|---|---|---|")
for s in ("PREFLOP", "FLOP", "TURN", "RIVER"):
if n[s]:
w = ", ".join(f"{k} {m}" for k, m in wege[s].most_common())
print(f"| {s} | {n[s]} | {kipp[s]} | {groesse[s]} | {w} |")
if not faelle:
return
ein = []
for i, q, gx, gy in faelle:
ein.append(dict(q, id=f"{i}:aus", taken=gx))
ein.append(dict(q, id=f"{i}:an", taken=gy))
mit = {r["id"]: r for r in audit(exe, ein, True)}
ohne = {r["id"]: r for r in audit(exe, ein, False)}
print("\n## Audit der gekippten Entscheidungen (bb; Verlust gegen die Loesung)\n")
print("| Strasse | gekippt | im Audit | Kosten Rake-blind, Audit mit Rake | dito Audit ohne Rake |\n|---|---|---|---|---|")
summe = collections.defaultdict(lambda: [0, 0.0, 0.0])
zeilen_detail = []
for i, q, gx, gy in faelle:
s = q.get("street")
a, b = mit.get(f"{i}:aus"), mit.get(f"{i}:an")
c, d = ohne.get(f"{i}:aus"), ohne.get(f"{i}:an")
if not (a and b and a.get("status") == "ok" and b.get("status") == "ok"):
zeilen_detail.append(f"| {i} | {s} | {gx['action']}->{gy['action']} | skip: {(a or {}).get('reason', '?')} | |")
continue
k_mit = a["loss_bb"] - b["loss_bb"]
k_ohne = (c["loss_bb"] - d["loss_bb"]) if c and d and c.get("status") == "ok" and d.get("status") == "ok" else 0.0
summe[s][0] += 1
summe[s][1] += k_mit
summe[s][2] += k_ohne
zeilen_detail.append(f"| {i} | {s} | {gx['action']}->{gy['action']} | {k_mit:+.2f} | {k_ohne:+.2f} |")
gesamt = [0, 0.0, 0.0]
for s in ("PREFLOP", "FLOP", "TURN", "RIVER"):
if kipp[s]:
z, km, ko = summe[s]
gesamt = [gesamt[0] + z, gesamt[1] + km, gesamt[2] + ko]
print(f"| {s} | {kipp[s]} | {z} | {km:+.2f} | {ko:+.2f} |")
print(f"| **alle** | {sum(kipp.values())} | {gesamt[0]} | **{gesamt[1]:+.2f}** | {gesamt[2]:+.2f} |")
print("\nPositiv = das Rake-blinde Spiel (aus) verliert so viele bb mehr gegen die Loesung als das Rake-Spiel (an).\n")
print("| Zeile | Strasse | aus->an | Kosten mit Rake | ohne Rake |\n|---|---|---|---|---|")
print("\n".join(zeilen_detail))
if __name__ == "__main__":
main()
+43
View File
@@ -0,0 +1,43 @@
# Rake-Nachspiel: messung_rake\postflop_anfragen.jsonl
Anfragen 1767; Aktion gekippt 20, nur Groesse anders 4.
| Strasse | Spots | Aktion gekippt | nur Groesse | Richtungen |
|---|---|---|---|---|
| FLOP | 816 | 7 | 2 | CALL->FOLD 6, RAISE->CHECK 1 |
| TURN | 578 | 8 | 1 | CALL->FOLD 6, RAISE->CHECK 1, RAISE->FOLD 1 |
| RIVER | 373 | 5 | 1 | RAISE->CHECK 5 |
## Audit der gekippten Entscheidungen (bb; Verlust gegen die Loesung)
| Strasse | gekippt | im Audit | Kosten Rake-blind, Audit mit Rake | dito Audit ohne Rake |
|---|---|---|---|---|
| FLOP | 7 | 0 | +0.00 | +0.00 |
| TURN | 8 | 8 | +23.68 | +22.71 |
| RIVER | 5 | 5 | -1.73 | -1.67 |
| **alle** | 20 | 13 | **+21.94** | +21.05 |
Positiv = das Rake-blinde Spiel (aus) verliert so viele bb mehr gegen die Loesung als das Rake-Spiel (an).
| Zeile | Strasse | aus->an | Kosten mit Rake | ohne Rake |
|---|---|---|---|---|
| 9 | RIVER | RAISE->CHECK | +0.02 | +0.11 |
| 166 | FLOP | CALL->FOLD | skip: multiway | |
| 187 | RIVER | RAISE->CHECK | +0.12 | +0.14 |
| 203 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 345 | TURN | CALL->FOLD | +21.72 | +20.62 |
| 440 | RIVER | RAISE->CHECK | -0.78 | -0.84 |
| 462 | TURN | CALL->FOLD | +1.32 | +1.33 |
| 555 | TURN | CALL->FOLD | +0.10 | +0.11 |
| 557 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 564 | RIVER | RAISE->CHECK | -0.70 | -0.68 |
| 588 | TURN | RAISE->CHECK | +0.79 | +1.17 |
| 624 | RIVER | RAISE->CHECK | -0.40 | -0.40 |
| 638 | TURN | CALL->FOLD | -0.56 | -0.69 |
| 846 | TURN | RAISE->FOLD | +1.88 | +2.22 |
| 1183 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 1327 | TURN | CALL->FOLD | -0.06 | -0.08 |
| 1461 | FLOP | RAISE->CHECK | skip: multiway | |
| 1626 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 1653 | TURN | CALL->FOLD | -1.52 | -1.98 |
| 1672 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
@@ -0,0 +1,43 @@
# Rake-Nachspiel: messung_rake\postflop_anfragen.jsonl
Anfragen 1767; Aktion gekippt 20, nur Groesse anders 4.
| Strasse | Spots | Aktion gekippt | nur Groesse | Richtungen |
|---|---|---|---|---|
| FLOP | 816 | 7 | 2 | CALL->FOLD 6, RAISE->CHECK 1 |
| TURN | 578 | 8 | 1 | CALL->FOLD 6, RAISE->CHECK 1, RAISE->FOLD 1 |
| RIVER | 373 | 5 | 1 | RAISE->CHECK 5 |
## Audit der gekippten Entscheidungen (bb; Verlust gegen die Loesung)
| Strasse | gekippt | im Audit | Kosten Rake-blind, Audit mit Rake | dito Audit ohne Rake |
|---|---|---|---|---|
| FLOP | 7 | 0 | +0.00 | +0.00 |
| TURN | 8 | 8 | +23.68 | +22.71 |
| RIVER | 5 | 5 | -1.73 | -1.67 |
| **alle** | 20 | 13 | **+21.94** | +21.05 |
Positiv = das Rake-blinde Spiel (aus) verliert so viele bb mehr gegen die Loesung als das Rake-Spiel (an).
| Zeile | Strasse | aus->an | Kosten mit Rake | ohne Rake |
|---|---|---|---|---|
| 9 | RIVER | RAISE->CHECK | +0.02 | +0.11 |
| 166 | FLOP | CALL->FOLD | skip: multiway | |
| 187 | RIVER | RAISE->CHECK | +0.12 | +0.14 |
| 203 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 345 | TURN | CALL->FOLD | +21.72 | +20.62 |
| 440 | RIVER | RAISE->CHECK | -0.78 | -0.84 |
| 462 | TURN | CALL->FOLD | +1.32 | +1.33 |
| 555 | TURN | CALL->FOLD | +0.10 | +0.11 |
| 557 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 564 | RIVER | RAISE->CHECK | -0.70 | -0.68 |
| 588 | TURN | RAISE->CHECK | +0.79 | +1.17 |
| 624 | RIVER | RAISE->CHECK | -0.40 | -0.40 |
| 638 | TURN | CALL->FOLD | -0.56 | -0.69 |
| 846 | TURN | RAISE->FOLD | +1.88 | +2.22 |
| 1183 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 1327 | TURN | CALL->FOLD | -0.06 | -0.08 |
| 1461 | FLOP | RAISE->CHECK | skip: multiway | |
| 1626 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
| 1653 | TURN | CALL->FOLD | -1.52 | -1.98 |
| 1672 | FLOP | CALL->FOLD | skip: not covered: flop without all-in: no flop solver yet (plan E) | |
+46
View File
@@ -0,0 +1,46 @@
"""Echte Postflop-Anfragen fuer das Rake-Nachspiel ziehen.
Quellen: die Schatten-Mitschriebe des Live-Laufs (`betrieb/scratch/shadow*.jsonl`, Feld `anfrage` =
die Kern-Anfrage wie gesendet) und die Live-Fixtures (`tests/live_fixture/*.jsonl`, Feld `spot`).
Entdoppelt ueber den Inhalt der Anfrage. Preflop kommt aus `preflop_anfragen.jsonl` (2776 Spots, vom
Zweig preflop-voll gezogen).
python messung_rake/spots_ziehen.py <shadow-ordner> > messung_rake/postflop_anfragen.jsonl
"""
import glob
import json
import os
import sys
def anfragen(ordner):
for p in sorted(glob.glob(os.path.join(ordner, "shadow*.jsonl"))):
for zeile in open(p, encoding="utf-8"):
try:
r = json.loads(zeile)
except ValueError:
continue
a = r.get("anfrage")
if isinstance(a, dict):
yield {k: v for k, v in a.items() if not k.startswith("_")}
for p in sorted(glob.glob("tests/live_fixture/*.jsonl")):
for zeile in open(p, encoding="utf-8"):
r = json.loads(zeile)
if isinstance(r.get("spot"), dict):
yield {k: v for k, v in r["spot"].items() if not k.startswith("_")}
def main():
gesehen = set()
for a in anfragen(sys.argv[1]):
if a.get("street") in (None, "PREFLOP"):
continue
schluessel = json.dumps(a, sort_keys=True)
if schluessel in gesehen:
continue
gesehen.add(schluessel)
print(json.dumps(a))
if __name__ == "__main__":
main()
+4
View File
@@ -7,6 +7,7 @@
//! The arm is chosen by environment so independent processes stay paired:
//! - `TURN_VETO`, `TURN_BUCKET`, `TURN_PER_STREET`: read by the turn track itself,
//! - `TURN_SPIEL=grund` (with `GRUNDSTRATEGIE`): the turn+river game with blueprint ranges (plan E3),
//! - `SIM_RAKE=mikro`: the live micro table (rake as at NL 0.01/0.02); `RAKE_LIVE=1`: rake in the engine,
//! - every other track adds its switch in `apply_arm` below (identity on the engine branch).
//!
//! Run: `ab_zelle <out-dir> [welt-deals=2000] [klassik-deals=4000] [draws=4] [rows=all|welt|klassik|a,b,..]`
@@ -42,6 +43,9 @@ const KLASSIK: [&str; 8] = ["station", "fish", "reg", "nit", "maniac", "nemesis-
/// Track switches read from the environment. Identity on the engine branch.
fn apply_arm() {
// SIM_RAKE=mikro: the whole ladder at the live micro table (5 %, cap 10 bb, preflop raked; the
// rake leaves the table). `RAKE_LIVE=1` (read by the engine itself) prices it in the decisions.
rechner::sim::session::set_ladder_rake(std::env::var("SIM_RAKE").as_deref() == Ok("mikro"));
// RIVER_SD=1: the river showdown read (world memory) into the session read (arm).
rechner::sim::memory::set_river_showdown(std::env::var("RIVER_SD").as_deref() == Ok("1"));
// READS=cbet,3bet,xr: the line-specific HUD reads (fold to c-bet / fold to 3-bet / check-raise).
+7 -1
View File
@@ -6,6 +6,7 @@
//! cargo run --release --bin chartgen -- equity --deck short > src/cfr/generated_equity_short.rs
//! cargo run --release --bin chartgen -- charts --deck short > src/preflop/generated_charts_short.rs
//! cargo run --release --bin chartgen -- multi > src/preflop/generated_charts_multi.rs
//! cargo run --release --bin chartgen -- charts --rake mikro > src/preflop/generated_charts_mikro.rs
//! ```
//!
//! Options: `--threads N` (default: all cores; the result never depends on it), `--deck full|short`,
@@ -100,6 +101,10 @@ fn equity(args: &[String]) -> Result<String, Fault> {
fn charts(args: &[String]) -> Result<String, Fault> {
let deck = deck(args);
let env = Environment::frozen_for(deck);
// `--rake mikro`: the leaves pay the live micro rake (`ChartRake::Micro`) instead of the 1000/2000
// table's; antes unchanged, so the tables differ from the default ones by the rake alone.
let mikro = option::<String>(args, "--rake").as_deref() == Some("mikro");
let env = if mikro { Environment { rake: rechner::rake::ChartRake::Micro, ..env } } else { env };
let push_iterations: Option<u32> = option(args, "--push-iterations");
let open_iterations: Option<u32> = option(args, "--open-iterations");
let (push_plan, open_plan) = (push_fold_plan(), open_plan());
@@ -122,7 +127,8 @@ fn charts(args: &[String]) -> Result<String, Fault> {
eprintln!("charts: all done in {:.1} s", started.elapsed().as_secs_f64());
let push = push.into_iter().collect::<Result<Vec<_>, _>>()?;
let open = open.into_iter().collect::<Result<Vec<_>, _>>()?;
Ok(render_charts(deck, &push, &open))
let text = render_charts(deck, &push, &open);
Ok(if mikro { rechner::cfr::render_charts::as_micro(&text) } else { text })
}
fn seat(args: &[String]) -> Result<Seat, Fault> {
+60
View File
@@ -0,0 +1,60 @@
//! Where does `RAKE_LIVE` change hero's play against one opponent? Plays the same deals at the raked
//! micro table (`TableCost::MICRO`) on the traced path and prints one line per hand: deal, seat,
//! luck-corrected net (bb) and every hero decision (street, pot, to_call, choice, equity). Run it
//! once without and once with `RAKE_LIVE=1` and diff the two outputs (`messung_rake/diag_diff.py`).
//!
//! Run: `diag_rake <opponent: station|fish|reg|nit|maniac|gto> [deals]`, oracle read.
use rechner::game::Choice;
use rechner::rng::Rng;
use rechner::sim::opponent::Opponent;
use rechner::sim::reader::Style;
use rechner::sim::table::{deal, play_hand_traced, HandRead, HandSetup, TableCost};
const SEED: u64 = 0x5EED_4A4E;
fn mix(seed: u64, n: u64) -> u64 {
Rng::seeded(seed ^ n.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64().0
}
fn main() {
let a: Vec<String> = std::env::args().collect();
let opponent = match a.get(1).map(String::as_str) {
Some("station") | None => Opponent::CallingStation,
Some("fish") => Opponent::Reader(Style::Fish),
Some("reg") => Opponent::Reader(Style::Reg),
Some("nit") => Opponent::Reader(Style::Nit),
Some("maniac") => Opponent::Reader(Style::Maniac),
Some("gto") => Opponent::Reader(Style::Gto),
Some(o) => panic!("unknown opponent {o}"),
};
let deals: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4000);
for d in 0..deals {
let (cards, _) = deal(2, Rng::seeded(mix(SEED, d)));
for hero_seat in 1..=2u8 {
let hand = HandSetup {
deal: &cards,
hero_seat,
opponent,
stack_bb: 100.0,
seed: mix(SEED ^ 0xA5A5, d << 8 | hero_seat as u64),
read: HandRead::Oracle,
};
let (res, trace) = play_hand_traced(&hand, TableCost::MICRO);
let decs: Vec<String> = trace
.iter()
.map(|x| {
let c = match x.choice {
Choice::Fold => "F".to_string(),
Choice::Check => "X".to_string(),
Choice::Call => "C".to_string(),
Choice::Raise { to } => format!("R{to:.2}"),
Choice::Abstain => "A".to_string(),
};
format!("{:?}:{:.2}:{:.2}:{}:{}", x.street, x.pot, x.to_call, c, x.equity.map_or("-".into(), |e| format!("{e:.3}")))
})
.collect();
println!("{d} {hero_seat} {:.4} {}", res.hero_net - res.luck, decs.join(" "));
}
}
}
+21
View File
@@ -80,6 +80,27 @@ fn header(deck: ChartDeck) -> String {
)
}
/// The default full-deck source text relabelled as the live micro rake set (`chartgen charts --rake
/// mikro` -> `preflop/generated_charts_mikro.rs`): the command line and the rake paragraph change,
/// nothing else (the data was solved with `ChartRake::Micro`).
pub fn as_micro(text: &str) -> String {
text.replacen(
"`cargo run --release --bin chartgen -- charts > src/preflop/generated_charts.rs`",
"`cargo run --release --bin chartgen -- charts --rake mikro > src/preflop/generated_charts_mikro.rs`",
1,
)
.replacen(
rake_lines(ChartDeck::Full),
"//! - Rake: the LIVE MICRO rule (`crate::rake::RakeRule::MICRO_BB`, NL 0.01/0.02, `ChartRake::Micro`):
//! an all-in 5 % of the pot rounded to half a big blind, capped at 10 bb; a pot with chips behind the
//! mean final rake of such flop pots at that stake. A fold pays none (at the stake a preflop pot of
//! 5.5 bb or more pays 0.5 bb; not modelled). Used only under `RAKE_LIVE` (`preflop::generated_lookup`).
//! Antes of six seats are dead money in every pot, as in the default tables (rake is the only change).
",
1,
)
}
fn rake_lines(deck: ChartDeck) -> &'static str {
match deck {
ChartDeck::Full => "\
+5 -5
View File
@@ -90,12 +90,12 @@ pub fn tree_with_chance(buckets: usize, chance: Vec<f64>, p: f64, s: f64) -> Tre
Node::Decision { player: 0, name: "hero", children: vec![1, 2] }, // 0: check -> 1, bet -> 2
Node::Decision { player: 1, name: "v_check", children: vec![3, 4] }, // 1: v check -> 3, v bet -> 4
Node::Decision { player: 1, name: "v_bet", children: vec![5, 6] }, // 2: v fold -> 5, v call -> 6
Node::Terminal(showdown(buckets, p)), // 3: check-check showdown
Node::Terminal(showdown(buckets, p).with_live_rake(buckets, p)), // 3: check-check showdown
Node::Decision { player: 0, name: "hero_vs_bet", children: vec![7, 8] }, // 4: hero fold -> 7, call -> 8
Node::Terminal(Payoff::Flat(p / 2.0)), // 5: hero bet, villain folds
Node::Terminal(showdown(buckets, pot_called)), // 6: hero bet, villain calls
Node::Terminal(Payoff::Flat(-p / 2.0)), // 7: hero checks, bets, hero folds
Node::Terminal(showdown(buckets, pot_called)), // 8: hero checks, bets, hero calls
Node::Terminal(Payoff::Flat(p / 2.0).with_live_rake(buckets, p)), // 5: hero bet, villain folds
Node::Terminal(showdown(buckets, pot_called).with_live_rake(buckets, pot_called)), // 6: hero bet, villain calls
Node::Terminal(Payoff::Flat(-p / 2.0).with_live_rake(buckets, p)), // 7: hero checks, bets, hero folds
Node::Terminal(showdown(buckets, pot_called).with_live_rake(buckets, pot_called)), // 8: hero checks, bets, hero calls
];
Tree { classes: buckets, chance, nodes, root: 0 }
}
+6 -3
View File
@@ -163,15 +163,18 @@ impl Builder<'_> {
let child = match *a {
Act::Fold => {
let value = if to_act == 0 { -(b.pot / 2.0 + c[0]) } else { b.pot / 2.0 + c[1] };
self.push(Node::Terminal(Payoff::Flat(value)), Vec::new())
// The pot the bettor takes: the folder's chips matched, the rest goes back.
let won = b.pot + 2.0 * c[to_act];
self.push(Node::Terminal(Payoff::Flat(value).with_live_rake(self.n, won)), Vec::new())
}
Act::Check if checked || to_act != b.first => {
self.push(Node::Terminal(showdown(self.n, b.pot + c[0] + c[1])), Vec::new())
let q = b.pot + c[0] + c[1];
self.push(Node::Terminal(showdown(self.n, q).with_live_rake(self.n, q)), Vec::new())
}
Act::Check => self.node(other, c, true, raises, next_depth),
Act::Call => {
let q = b.pot + 2.0 * c[other];
self.push(Node::Terminal(showdown(self.n, q)), Vec::new())
self.push(Node::Terminal(showdown(self.n, q).with_live_rake(self.n, q)), Vec::new())
}
Act::Bet(to) | Act::Raise(to) => {
let mut nc = c;
+20
View File
@@ -20,6 +20,26 @@ pub enum Payoff {
Raked { pair: Vec<f64>, rake: f64 },
}
impl Payoff {
/// This heads-up leaf with the room's rake of `pot` (chips) taken from whoever wins it
/// (`rake::live`): a positive result for player 0 is a pot player 0 wins, a negative one a pot
/// player 1 wins, an exact 0 a split (each pays half). Without a live rake scope, or at a pot the
/// room does not rake, the leaf is returned unchanged.
pub fn with_live_rake(self, classes: usize, pot: f64) -> Payoff {
let rake = crate::rake::live::of_pot(pot);
if !(rake > 0.0) {
return self;
}
let cut = |v: f64| if v > 0.0 { v - rake } else if v < 0.0 { v } else { -rake / 2.0 };
let pair = match self {
Payoff::Flat(v) => vec![cut(v); classes * classes],
Payoff::Pair(m) => m.into_iter().map(cut).collect(),
other => return other,
};
Payoff::Raked { pair, rake }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Node {
Decision { player: usize, name: &'static str, children: Vec<usize> },
+41 -17
View File
@@ -72,14 +72,21 @@ impl TrBets {
pub enum TNode {
/// `street`: 0 = turn, 1 = river.
Dec { player: usize, street: u8, kids: Vec<usize> },
/// `folder` loses `amt` (its contribution counting `pot / 2` of the start pot), the other wins it.
Fold { folder: usize, amt: f64 },
/// Showdown on the river card: the better hand wins `half`, the worse loses it.
Show { half: f64 },
/// `folder` loses `amt` (its contribution counting `pot / 2` of the start pot), the other wins it
/// less `rake` (the room's rake of the pot `2 amt`, `rake::live`; 0 without a live rake scope).
Fold { folder: usize, amt: f64, rake: f64 },
/// Showdown on the river card: the better hand wins `half` less `rake`, the worse loses `half`, a
/// split pays `rake / 2` each (`rake` of the pot `2 half`; 0 without a live rake scope).
Show { half: f64, rake: f64 },
/// The river card is dealt; `child` is the river betting (or a showdown).
Chance { child: usize },
}
/// A showdown leaf over the pot `2 half`, with the room's rake under a live rake scope.
fn show_node(half: f64) -> TNode {
TNode::Show { half, rake: crate::rake::live::of_pot(2.0 * half) }
}
/// A built turn+river game.
pub struct TrGame {
pub nodes: Vec<TNode>,
@@ -112,7 +119,7 @@ impl Builder<'_> {
fn to_river(&mut self, total: f64) -> usize {
let b = self.b;
let child = if total >= b.stack - 1e-9 {
self.push(TNode::Show { half: b.pot / 2.0 + total }, Vec::new())
self.push(show_node(b.pot / 2.0 + total), Vec::new())
} else {
self.street(1, b.first, total, [0.0, 0.0], false, 0, None)
};
@@ -172,12 +179,15 @@ impl Builder<'_> {
_ => None,
};
let kid = match *a {
Act::Fold => self.push(TNode::Fold { folder: to_act, amt: b.pot / 2.0 + base + c[to_act] }, Vec::new()),
Act::Fold => {
let amt = b.pot / 2.0 + base + c[to_act];
self.push(TNode::Fold { folder: to_act, amt, rake: crate::rake::live::of_pot(2.0 * amt) }, Vec::new())
}
Act::Check if checked || to_act != b.first => {
if street == 0 {
self.to_river(base)
} else {
self.push(TNode::Show { half: b.pot / 2.0 + base }, Vec::new())
self.push(show_node(b.pot / 2.0 + base), Vec::new())
}
}
Act::Check => self.street(street, other, base, c, true, raises, next_depth),
@@ -186,7 +196,7 @@ impl Builder<'_> {
if street == 0 {
self.to_river(total)
} else {
self.push(TNode::Show { half: b.pot / 2.0 + total }, Vec::new())
self.push(show_node(b.pot / 2.0 + total), Vec::new())
}
}
Act::Bet(to) | Act::Raise(to) => {
@@ -555,6 +565,19 @@ impl TrSolver {
out
}
/// Showdown values with the room's rake: `(half - rake/2) x (win - lose) - rake/2 x all` (winner
/// nets `half - rake`, loser `-half`, a split `-rake/2`). `rake == 0`: exactly `show`.
fn show_raked(&self, p: usize, r: usize, opp: &[f64], half: f64, rake: f64) -> Vec<f64> {
if rake == 0.0 {
return self.show(p, r, opp, half);
}
let mut out = self.show(p, r, opp, half - rake / 2.0);
for (o, d) in out.iter_mut().zip(self.disjoint(p, opp)) {
*o -= rake / 2.0 * d;
}
out
}
/// `show` into `out` (every entry written).
fn show_into(&self, p: usize, r: usize, opp: &[f64], half: f64, out: &mut [f64]) {
if self.eq.is_some() {
@@ -659,17 +682,18 @@ impl TrSolver {
fn walk(&mut self, node: usize, p: usize, own: &[f64], opp: &[f64], r: usize, weight: f64) -> Vec<f64> {
let game = std::sync::Arc::clone(&self.game);
match game.nodes[node] {
TNode::Fold { folder, amt } => {
let v = if folder == p { -amt } else { amt };
TNode::Fold { folder, amt, rake } => {
let v = if folder == p { -amt } else { amt - rake };
let mut out = self.take(self.n[p]);
self.fold_into(p, opp, v, &mut out);
out
}
TNode::Show { half } => {
TNode::Show { half, rake } if rake == 0.0 => {
let mut out = self.take(self.n[p]);
self.show_into(p, r, opp, half, &mut out);
out
}
TNode::Show { half, rake } => self.show_raked(p, r, opp, half, rake),
TNode::Chance { child } => {
let mut total = self.take(self.n[p]);
let mut o = self.take(own.len());
@@ -783,11 +807,11 @@ impl TrSolver {
/// Best-response values of player `p` (per own combo) against `strategy`.
fn br(&self, strategy: &TrStrategy, node: usize, p: usize, opp: &[f64], r: usize) -> Vec<f64> {
match &self.game.nodes[node] {
TNode::Fold { folder, amt } => {
let v = if *folder == p { -amt } else { *amt };
TNode::Fold { folder, amt, rake } => {
let v = if *folder == p { -amt } else { *amt - *rake };
self.disjoint(p, opp).into_iter().map(|x| x * v).collect()
}
TNode::Show { half } => self.show(p, r, opp, *half),
TNode::Show { half, rake } => self.show_raked(p, r, opp, *half, *rake),
TNode::Chance { child } => {
let mut total = vec![0.0; self.n[p]];
for ri in 0..self.rc.len() {
@@ -850,11 +874,11 @@ impl TrSolver {
fn follow(&self, strategy: &TrStrategy, node: usize, p: usize, opp: &[f64], r: usize, own: &[f64]) -> Vec<f64> {
match &self.game.nodes[node] {
TNode::Fold { folder, amt } => {
let v = if *folder == p { -amt } else { *amt };
TNode::Fold { folder, amt, rake } => {
let v = if *folder == p { -amt } else { *amt - *rake };
self.disjoint(p, opp).into_iter().map(|x| x * v).collect()
}
TNode::Show { half } => self.show(p, r, opp, *half),
TNode::Show { half, rake } => self.show_raked(p, r, opp, *half, *rake),
TNode::Chance { child } => {
let mut total = vec![0.0; self.n[p]];
for ri in 0..self.rc.len() {
+3
View File
@@ -164,6 +164,9 @@ impl Default for Opts {
/// Audit one decision. River: the full river game. Turn: the turn+river game. Preflop and flop:
/// all-in prices and short-stack push/fold (`audit_allin`).
pub fn audit(spot: &Spot, taken: Taken, opts: Opts) -> Result<Audit, Skip> {
// RAKE_LIVE: the audit prices the river game and the all-in prices net of the room's rake, as the
// live decision does (`rake::live`). The turn+river game (`cfr::turn_river_game`) stays raw.
let _rake = crate::rake::live::cash_scope(spot.big_blind);
match spot.street {
Street::River => audit_river(spot, taken, opts),
Street::Turn => audit_turn(spot, taken, opts),
+2 -2
View File
@@ -164,7 +164,7 @@ fn price_jam(spot: &Spot, taken: Taken, jam: &OpenJam) -> Result<Audit, Skip> {
call / pot,
if behind { "; players behind not modelled" } else { "" }
);
Ok(two_way(0.0, Act::Call, equity * pot - call, go, RangeSource::Model, "jam_preis", note, 1))
Ok(two_way(0.0, Act::Call, equity * crate::rake::live::net(pot) - call, go, RangeSource::Model, "jam_preis", note, 1))
}
fn push_or_fold(spot: &Spot, taken: Taken) -> Result<Audit, Skip> {
@@ -274,7 +274,7 @@ pub fn audit_flop(spot: &Spot, taken: Taken) -> Result<Audit, Skip> {
let refund = (spot.to_call - spot.hero_stack).max(0.0);
let pot = spot.pot - refund + call;
let note = format!("equity {equity:.3} vs {} villain range ({} combos), price {:.3}", source.name(), list.len(), call / pot);
Ok(two_way(0.0, Act::Call, equity * pot - call, go, source, "allin_equity", note, 1))
Ok(two_way(0.0, Act::Call, equity * crate::rake::live::net(pot) - call, go, source, "allin_equity", note, 1))
}
#[cfg(test)]
+6 -5
View File
@@ -18,6 +18,7 @@ use crate::exploit::street_continuation::continuations;
use crate::game::{line, Spot, Villain};
use crate::odds::break_even::break_even;
use crate::odds::ev::final_pot;
use crate::rake::live::net;
use crate::read::hand_read::HandRead;
use crate::read::made::Made;
use crate::read::tier::{tier, Tier};
@@ -60,8 +61,8 @@ pub struct Branches {
/// `fold` = P(every villain folds), `called_share` = hero's (realised) share against the
/// calling range. Hero adds `to` (nothing committed on this street, see `odds::ev`).
pub fn branches(spot: &Spot, to: f64, fold: f64, called_share: f64) -> Branches {
let fold_branch = fold * spot.pot;
let called = (1.0 - fold) * (called_share * final_pot(spot.pot, spot.to_call, to) - to);
let fold_branch = fold * net(spot.pot);
let called = (1.0 - fold) * (called_share * net(final_pot(spot.pot, spot.to_call, to)) - to);
Branches { fold: fold_branch, called, total: fold_branch + called }
}
@@ -109,8 +110,8 @@ pub fn branches_vs_raise(
profile: Option<&Profile>,
) -> Branches {
let keep = 1.0 - rho;
let fold_branch = keep * fold * spot.pot;
let called = keep * (1.0 - fold) * (called_share * final_pot(spot.pot, spot.to_call, to) - to)
let fold_branch = keep * fold * net(spot.pot);
let called = keep * (1.0 - fold) * (called_share * net(final_pot(spot.pot, spot.to_call, to)) - to)
+ rho * raise_response(spot, to, kind, profile);
Branches { fold: fold_branch, called, total: fold_branch + called }
}
@@ -126,7 +127,7 @@ pub fn raise_response(spot: &Spot, to: f64, kind: RaiseKind, profile: Option<&Pr
let raise_to = CHECK_RAISE_MULTIPLE * to;
let ratio = (raise_to - to) / (spot.pot + 2.0 * to);
let beats = bluff_share(profile, Some(ratio), spot.street);
let call = beats * (spot.pot + 2.0 * raise_to) - raise_to;
let call = beats * net(spot.pot + 2.0 * raise_to) - raise_to;
call.max(fold)
}
_ => fold,
+7
View File
@@ -227,6 +227,13 @@ pub fn decide(spot: &Spot) -> Decision {
/// `decide` with an optional tournament situation (`icm`). Without one: cash. With one
/// that cannot be priced: ABSTAIN.
pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision {
// RAKE_LIVE (`rake::live`, off by default): a cash spot prices every pot net of the room's rake;
// a tournament pays none, also a chip-linear one that plays the cash path below
// (the scope is decided on the original situation). Off: no scope, nothing changes.
let _rake = match lage {
None => crate::rake::live::cash_scope(spot.big_blind),
Some(_) => crate::rake::live::enabled().then(crate::rake::live::Scope::none),
};
// Chip-lineares Geld (der Sieger nimmt alles, alle Verbliebenen gleich bezahlt, p1 > p2 = ... = pn):
// ICM IST Chip-EV, also genau der Cash-Pfad. Eine unbepreisbare Lage bleibt ein Aussetzen.
let lage = lage.filter(|l| !(l.is_usable() && l.is_chip_linear()));
+1 -1
View File
@@ -143,7 +143,7 @@ pub fn scored(
RaiseKind::Bluff => {
fe >= PURE_BLUFF_MIN_FOLD
&& b.total > 0.0
&& b.total >= floor + PURE_BLUFF_EDGE * spot.pot
&& b.total >= floor + PURE_BLUFF_EDGE * crate::rake::live::net(spot.pot)
}
};
keep.then_some(Scored { choice: Choice::Raise { to }, ev: b.total, kind: Some(kind) })
+3 -2
View File
@@ -1,9 +1,10 @@
/// Equity share needed for a call to break even: `to_call / (pot + to_call)`.
/// Equity share needed for a call to break even: `to_call / net(pot + to_call)`, the pot hero takes
/// home after the room's rake (`rake::live`; the identity outside a `RAKE_LIVE` cash scope).
/// Total: degenerate input (non-finite, negative, empty denominator) yields 0.
pub fn break_even(pot: f64, to_call: f64) -> f64 {
let total = pot + to_call;
if pot.is_finite() && to_call.is_finite() && to_call > 0.0 && total > 0.0 {
to_call / total
to_call / crate::rake::live::net(total)
} else {
0.0
}
+12 -7
View File
@@ -5,20 +5,24 @@
//! * If a raise is called, exactly one villain calls and adds `X - to_call`
//! (the existing bet is already in the pot); the rest fold.
//! * `share` (equity) is realised in full; no later-street betting is modelled.
//! * Every pot hero wins is the pot it takes home, `rake::live::net` (the room's rake off). Outside a
//! `RAKE_LIVE` cash scope `net` is the identity and every formula is the raw one, bit for bit.
use crate::rake::live::net;
/// Folding is the reference point.
pub fn fold() -> f64 {
0.0
}
/// Free check: hero keeps `share` of the current pot.
/// Free check: hero keeps `share` of the current pot (net of rake).
pub fn check(share: f64, pot: f64) -> f64 {
share * pot
share * net(pot)
}
/// Call: `share * (pot + to_call) - to_call`.
/// Call: `share * net(pot + to_call) - to_call`.
pub fn call(share: f64, pot: f64, to_call: f64) -> f64 {
share * (pot + to_call) - to_call
share * net(pot + to_call) - to_call
}
/// Pot after a raise adding `added` chips that one villain calls:
@@ -29,8 +33,9 @@ pub fn final_pot(pot: f64, to_call: f64, added: f64) -> f64 {
}
/// Raise adding `added` chips, with fold probability `fe`:
/// `fe * pot + (1 - fe) * (share * final_pot - added)` where
/// `final_pot = pot + added + max(added - to_call, 0)`.
/// `fe * net(pot) + (1 - fe) * (share * net(final_pot) - added)` where
/// `final_pot = pot + added + max(added - to_call, 0)`. A pot won by a fold is raked too (no "no
/// flop, no drop" at the live stake).
pub fn raise(share: f64, pot: f64, to_call: f64, added: f64, fe: f64) -> f64 {
fe * pot + (1.0 - fe) * (share * final_pot(pot, to_call, added) - added)
fe * net(pot) + (1.0 - fe) * (share * net(final_pot(pot, to_call, added)) - added)
}
+5 -3
View File
@@ -23,8 +23,9 @@
//! a rational jammer does not have. Equity is exact per class with card removal
//! (`cfr::wake_range::equity_against`, the frozen class-vs-class matrix).
//!
//! Not modelled (stated, not hidden): players still to act behind hero (they can overcall) and rake
//! (micro rule unmeasured, `rake`). Both only make a call worse, so the rule errs towards calling.
//! Not modelled (stated, not hidden): players still to act behind hero (they can overcall). It only
//! makes a call worse, so the rule errs towards calling. The rake is priced under `RAKE_LIVE`
//! (`rake::live`: the price is `call / net(final pot)`); off, the raw price as before.
//!
//! Switch `OPEN_JAM=1` (read once; `set_open_jam` for tests and ladder arms). Default off: the old
//! behaviour, until the owner's switch point (`betrieb/kern_schalter.txt`).
@@ -205,7 +206,8 @@ pub fn call_vs_jam(spot: &Spot, margin: f64) -> Option<PreflopPlan> {
if !(call > 0.0 && pot > 0.0) {
return None;
}
let need = call / pot + margin.max(0.0);
// The pot hero takes home: net of the room's rake under RAKE_LIVE (`rake::live`), raw otherwise.
let need = call / crate::rake::live::net(pot) + margin.max(0.0);
let continue_ = if spot.rules().shape == ActionShape::Binary { ChartAction::Jam } else { ChartAction::Call };
let action = if equity >= need { continue_ } else { ChartAction::Fold };
let verb = if action == ChartAction::Fold { "fold" } else { "call" };
+152
View File
@@ -0,0 +1,152 @@
//! The rake inside the live decision (`RAKE_LIVE`).
//!
//! Every money comparison of a cash decision — pot odds, call / check / raise EV, the fold branch of a
//! bet, the MDF floor's break-even, the river veto's tree, the open-jam price — is about the pot hero
//! *takes home*, not the pot on the table. At NL 0.01/0.02 the room keeps 5 % of every pot (cap 10 bb,
//! preflop pots too: `RakeRule::MICRO_BB`), so a call that breaks even on the raw pot loses.
//!
//! **Switch.** `RAKE_LIVE=1` (read once). Off by default: then no scope is ever entered, `net` returns
//! its argument unchanged and every result is bit-identical to the engine without this module.
//!
//! **Scope.** The rake only exists at a cash table: `engine::decide::decide_with` enters a `Scope` for a
//! spot without a tournament situation (tournaments pay no rake per pot). The scope is thread-local and
//! restored on drop, so parallel simulations and nested decisions stay independent. Inside it the pot
//! is in the spot's chips; the rule is in big blinds, so the scope carries the spot's big blind.
//!
//! **Model.** The rake of a pot is the rule applied to the pot as it would end *now* (heads-up cap,
//! flop dealt or not makes no difference at this stake). Later streets are not modelled, exactly as
//! the EV formulas of `odds::ev` do not model them.
//!
//! **Smooth, not to the cent.** The table rounds to the cent (0.5 bb), but a decision does not know
//! the pot the hand will end with, and over that uncertainty the rounding averages out: the expected
//! rake is 5 % of the pot up to the cap (`DECISION_RULE`). Pricing the rounded step instead puts
//! artificial jumps of 0.5 bb between neighbouring sizes (a pot bet into 2 bb paid 0.5, two thirds
//! paid 0) and pushed value bets to the smaller size: measured against the station, −0.19 bb/100
//! (`messung_rake/URTEIL.md`). The simulator's table (`TableCost::MICRO`) keeps the exact cents.
use super::{HandEnd, RakeRule};
use std::cell::Cell;
use std::sync::OnceLock;
/// The rule the live tables take (big blinds), to the cent.
pub const LIVE_RULE: RakeRule = RakeRule::MICRO_BB;
/// The rule a decision prices with: the live rule without the rounding step (its expectation).
pub const DECISION_RULE: RakeRule = RakeRule { step: 0.0, ..LIVE_RULE };
/// `RAKE_LIVE=1` switches the rake into the live decision. Read once per process.
pub fn enabled() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("RAKE_LIVE").as_deref() == Ok("1"))
}
thread_local! {
/// Big blind of the cash spot being decided on this thread; `None` = no rake.
static BIG_BLIND: Cell<Option<f64>> = const { Cell::new(None) };
}
/// While alive, `net` and `of_pot` rake pots in chips of a table with this big blind.
#[must_use]
pub struct Scope {
previous: Option<f64>,
}
impl Scope {
/// Enter unconditionally (tests, measurement tools). A non-positive or broken big blind means no
/// rake.
pub fn enter(big_blind: f64) -> Scope {
let value = (big_blind.is_finite() && big_blind > 0.0).then_some(big_blind);
Scope { previous: BIG_BLIND.with(|b| b.replace(value)) }
}
/// No rake inside, whatever the outer scope said (a tournament decision nested in a cash run).
pub fn none() -> Scope {
Scope { previous: BIG_BLIND.with(|b| b.replace(None)) }
}
}
impl Drop for Scope {
fn drop(&mut self) {
BIG_BLIND.with(|b| b.set(self.previous));
}
}
/// The scope of a cash decision: entered only when `RAKE_LIVE` is on, `None` otherwise (and then
/// nothing changes anywhere).
pub fn cash_scope(big_blind: f64) -> Option<Scope> {
enabled().then(|| Scope::enter(big_blind))
}
/// Is a rake scope active on this thread?
pub fn active() -> bool {
BIG_BLIND.with(Cell::get).is_some()
}
/// Rake of `pot` (chips) at the current table; 0 outside a scope.
pub fn of_pot(pot: f64) -> f64 {
match BIG_BLIND.with(Cell::get) {
None => 0.0,
Some(bb) if pot.is_finite() && pot > 0.0 => DECISION_RULE.of_hand(pot / bb, 2, HandEnd::FlopDealt) * bb,
Some(_) => 0.0,
}
}
/// What the winner of `pot` takes home. Outside a scope `pot` itself, unchanged to the bit.
pub fn net(pot: f64) -> f64 {
if BIG_BLIND.with(Cell::get).is_none() {
return pot;
}
pot - of_pot(pot)
}
#[cfg(test)]
mod tests {
use super::*;
fn near(a: f64, b: f64) {
assert!((a - b).abs() < 1e-12, "{a} != {b}");
}
#[test]
fn without_a_scope_nothing_is_raked_and_the_pot_is_returned_bit_for_bit() {
for pot in [0.0, 0.03, 0.11, 1.0, 7.123_456_789, 1e9, f64::NAN] {
assert_eq!(net(pot).to_bits(), pot.to_bits());
assert_eq!(of_pot(pot), 0.0);
}
assert!(!active());
}
#[test]
fn a_decision_prices_five_percent_smooth_capped_at_twenty_cents() {
let _s = Scope::enter(0.02);
near(of_pot(0.10), 0.005);
near(of_pot(0.33), 0.0165);
near(of_pot(3.38), 0.169);
near(of_pot(4.03), 0.20);
near(of_pot(50.0), 0.20);
near(net(1.0), 0.95);
}
#[test]
fn the_scope_is_restored_on_drop_and_nests() {
{
let _a = Scope::enter(0.02);
assert!(active());
{
let _b = Scope::none();
assert!(!active());
}
assert!(active());
}
assert!(!active());
}
#[test]
fn in_big_blinds_neighbouring_sizes_pay_no_step() {
let _s = Scope::enter(1.0);
near(of_pot(4.67), 0.2335);
near(of_pot(6.0), 0.3);
near(of_pot(20.0), 1.0);
near(of_pot(400.0), 10.0);
}
}
+37 -4
View File
@@ -16,7 +16,17 @@
//! the micro tables contradict their configuration (0.05/0.10 configures 0.6 and 0.25 yet took
//! 1.0 twice; 0.02/0.05 configures 0.3 and 0.13 yet took 0.5 four times, once with four players
//! in the pot). Those tables also rake some preflop pots (`rakeGTPPf` 5). Only the rule of
//! 1000/2000 is therefore treated as measured; no micro rule is modelled here.
//! 1000/2000 is therefore treated as measured by those tables.
//!
//! **The live stake NL 0.01/0.02 (`RakeRule::MICRO_BB`, measured 15.11.).** 857 hands of the live
//! micro runs (14.11., 16 tables; `archiv/rohlog` plus the client's current logs, `potAmount`
//! against `potAmountAfterRake` per hand): 5 % of the pot rounded to the cent (half to even), capped
//! at 0.20 = **10 bb**. 425 of 429 hands with a flop match exactly (the rest are merged log lines),
//! and the hands without a flop pay the same rule (50 of 428 raked: every pot of 0.11 or more, none
//! of 0.10 or less) — **no "no flop, no drop"** at this stake. In big blinds the cent is half a big
//! blind. The engine prices it only behind `RAKE_LIVE` (`rake::live`).
pub mod live;
/// Rake of one table. All amounts in the pot's currency.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -27,6 +37,10 @@ pub struct RakeRule {
pub cap: f64,
/// Cap with more than three players in the pot (`rakeCapGT3`).
pub cap_more_than_three: f64,
/// The rake is rounded to this unit, half to even (the cent); 0 = not rounded.
pub step: f64,
/// A hand that ends before the flop pays no rake ("no flop, no drop").
pub no_flop_no_drop: bool,
}
/// How far a hand got: rake is taken once a flop is dealt, whoever is left.
@@ -42,15 +56,22 @@ const PERCENT: f64 = 100.0;
impl RakeRule {
/// The measured table in big blinds: 5 %, cap 1 bb (2000 at blinds 1000/2000).
pub const MEASURED_BB: RakeRule = RakeRule { percent: 5.0, cap: 1.0, cap_more_than_three: 1.0 };
pub const MEASURED_BB: RakeRule =
RakeRule { percent: 5.0, cap: 1.0, cap_more_than_three: 1.0, step: 0.0, no_flop_no_drop: true };
/// The live stake NL 0.01/0.02 in big blinds: 5 % rounded to the cent (0.5 bb, half to even),
/// cap 10 bb, preflop pots raked as well.
pub const MICRO_BB: RakeRule =
RakeRule { percent: 5.0, cap: 10.0, cap_more_than_three: 10.0, step: 0.5, no_flop_no_drop: false };
/// Rake of a whole hand. `pot` is everything contested, antes included, uncalled chips not.
pub fn of_hand(&self, pot: f64, players_in_pot: usize, end: HandEnd) -> f64 {
if end == HandEnd::NoFlop {
if end == HandEnd::NoFlop && self.no_flop_no_drop {
return 0.0;
}
let cap = if players_in_pot > PLAYERS_ON_THE_PLAIN_CAP { self.cap_more_than_three } else { self.cap };
(pot * self.percent / PERCENT).max(0.0).min(cap)
let raw = pot * self.percent / PERCENT;
let rounded = if self.step > 0.0 { (raw / self.step).round_ties_even() * self.step } else { raw };
rounded.max(0.0).min(cap)
}
}
@@ -83,11 +104,19 @@ pub const CHART_ANTES_BB: f64 = CHART_SEATS * MEASURED_ANTE_BB;
/// pot still grows after the flop. Above the last bound the means stop rising (0.91 to 0.95).
const MEAN_RAKE_BY_FLOP_POT: [(f64, f64); 5] = [(6.0, 0.489), (10.0, 0.720), (15.0, 0.850), (25.0, 0.906), (f64::INFINITY, 0.950)];
/// The same for the live micro stake (`RakeRule::MICRO_BB`): 413 hands of NL 0.01/0.02 that saw a
/// flop, mean final rake in bb by the pot at the start of the flop (bb, upper bound of the bucket;
/// 107 / 177 / 50 / 41 / 22 / 16 hands). With a 10 bb cap the rake keeps rising with the pot.
const MICRO_MEAN_RAKE_BY_FLOP_POT: [(f64, f64); 6] =
[(6.0, 0.500), (10.0, 0.808), (15.0, 1.890), (25.0, 2.061), (40.0, 2.545), (f64::INFINITY, 5.500)];
/// What a leaf of the chart games pays, for a pot with the antes in it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChartRake {
None,
Measured,
/// The live micro stake (`RakeRule::MICRO_BB`, `MICRO_MEAN_RAKE_BY_FLOP_POT`).
Micro,
}
impl ChartRake {
@@ -96,6 +125,7 @@ impl ChartRake {
match self {
ChartRake::None => 0.0,
ChartRake::Measured => RakeRule::MEASURED_BB.of_hand(pot, 2, HandEnd::FlopDealt),
ChartRake::Micro => RakeRule::MICRO_BB.of_hand(pot, 2, HandEnd::FlopDealt),
}
}
@@ -106,6 +136,9 @@ impl ChartRake {
ChartRake::Measured => {
MEAN_RAKE_BY_FLOP_POT.iter().find(|(bound, _)| pot < *bound).map_or(0.0, |(_, rake)| *rake)
}
ChartRake::Micro => {
MICRO_MEAN_RAKE_BY_FLOP_POT.iter().find(|(bound, _)| pot < *bound).map_or(0.0, |(_, rake)| *rake)
}
}
}
}
+20 -2
View File
@@ -93,9 +93,27 @@ pub fn deal_samples(setup: &Setup) -> (Vec<f64>, Measurement) {
(corrected, m)
}
/// `deal_samples` plus the session memory at the end (its counts feed the population-prior fit).
/// Table of the paired ladder (`ab_zelle`): the free table unless `set_ladder_rake(true)` (arm
/// `SIM_RAKE=mikro`) puts it on the live micro table (`TableCost::MICRO`), where the rake is real.
static LADDER_RAKE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Put the paired ladder on the raked micro table (`true`) or the free table (`false`, default).
pub fn set_ladder_rake(on: bool) {
LADDER_RAKE.store(on, std::sync::atomic::Ordering::Relaxed);
}
fn ladder_cost() -> TableCost {
if LADDER_RAKE.load(std::sync::atomic::Ordering::Relaxed) {
TableCost::MICRO
} else {
TableCost::FREE
}
}
/// `deal_samples` plus the session memory at the end (its counts feed the population-prior fit), at
/// the ladder's table (`set_ladder_rake`; the free table by default).
pub fn deal_samples_memory(setup: &Setup) -> (Vec<f64>, Measurement, SessionMemory) {
let (corrected, _, m, memory) = deal_samples_at(setup, TableCost::FREE);
let (corrected, _, m, memory) = deal_samples_at(setup, ladder_cost());
(corrected, m, memory)
}
+3
View File
@@ -37,6 +37,9 @@ impl TableCost {
pub const FREE: TableCost = TableCost { ante_bb: 0.0, rake: None };
/// The table measured in `rake`: ante 0.16 bb, 5 % capped at 1 bb.
pub const MEASURED: TableCost = TableCost { ante_bb: MEASURED_ANTE_BB, rake: Some(RakeRule::MEASURED_BB) };
/// The live micro table NL 0.01/0.02: no ante, 5 % to the half big blind, cap 10 bb, preflop pots
/// raked too (`RakeRule::MICRO_BB`).
pub const MICRO: TableCost = TableCost { ante_bb: 0.0, rake: Some(RakeRule::MICRO_BB) };
}
/// Cards for one hand: `holes[seat - 1]` and the full board in deal order.
+107
View File
@@ -0,0 +1,107 @@
//! Spezifikation von `RAKE_LIVE` (`rake::live`): der Rake in der Live-Entscheidung.
//!
//! Ausserhalb eines Rake-Scopes rechnet alles roh, bit für bit; im Scope (Cash-Spot unter
//! `RAKE_LIVE=1`) ist jeder Topf, den hero gewinnt, der Topf nach Rake. Die Tests betreten den Scope
//! direkt (`Scope::enter`) und lassen den Prozess-Schalter in Ruhe.
use rechner::cfr::river::tree_with_chance;
use rechner::cfr::river_game::{build, Bets};
use rechner::cfr::tree::{Node, Payoff};
use rechner::odds::{break_even::break_even, ev};
use rechner::rake::live::{active, net, of_pot, Scope};
fn near(a: f64, b: f64) {
assert!((a - b).abs() < 1e-9, "{a} != {b}");
}
#[test]
fn without_a_scope_every_price_is_the_raw_one_to_the_bit() {
assert!(!active());
for (share, pot, call) in [(0.3, 0.19, 0.07), (0.55, 12.0, 4.0), (0.12, 1.0, 1.0)] {
assert_eq!(ev::call(share, pot, call).to_bits(), (share * (pot + call) - call).to_bits());
assert_eq!(ev::check(share, pot).to_bits(), (share * pot).to_bits());
assert_eq!(break_even(pot, call).to_bits(), (call / (pot + call)).to_bits());
let raw = 0.4 * pot + (1.0 - 0.4) * (share * ev::final_pot(pot, call, 2.0 * call) - 2.0 * call);
assert_eq!(ev::raise(share, pot, call, 2.0 * call, 0.4).to_bits(), raw.to_bits());
}
}
#[test]
fn in_the_scope_a_call_needs_the_price_of_the_pot_after_rake() {
let _s = Scope::enter(0.02);
// Topf 0.20 + Call 0.10 = 0.30, erwarteter Rake 5 % = 0.015 (glatt, nicht auf den Cent):
// break-even 0.10 / 0.285.
near(break_even(0.20, 0.10), 0.10 / 0.285);
near(ev::call(0.5, 0.20, 0.10), 0.5 * 0.285 - 0.10);
near(ev::check(0.5, 0.20), 0.5 * 0.19);
}
#[test]
fn a_pot_won_by_a_fold_is_raked_too() {
let _s = Scope::enter(1.0);
// Topf 20 bb: Rake 1 bb, auch wenn niemand callt (keine "no flop, no drop" am Mikro-Tisch).
near(ev::raise(0.0, 20.0, 0.0, 10.0, 1.0), 19.0);
}
#[test]
fn the_decision_rake_is_smooth_up_to_the_cap() {
let _s = Scope::enter(1.0);
// Keine Cent-Stufe zwischen Nachbargroessen (die Stufe trieb Value-Bets auf die kleine Groesse).
near(of_pot(4.67), 0.2335);
near(of_pot(6.0), 0.3);
near(net(4.0), 3.8);
near(of_pot(1000.0), 10.0);
}
#[test]
fn a_raked_leaf_takes_the_rake_from_the_winner_only() {
let _s = Scope::enter(1.0);
// Showdown um 20 bb (je 10), Rake 1: Sieger +9, Verlierer -10, Split je -0.5.
let leaf = Payoff::Pair(vec![0.0, -10.0, 10.0, 0.0]).with_live_rake(2, 20.0);
match leaf {
Payoff::Raked { pair, rake } => {
near(rake, 1.0);
assert_eq!(pair, vec![-0.5, -10.0, 9.0, -0.5]);
}
other => panic!("not raked: {other:?}"),
}
// Fold: wer gewinnt, zahlt.
match Payoff::Flat(10.0).with_live_rake(2, 20.0) {
Payoff::Raked { pair, rake } => {
near(rake, 1.0);
assert!(pair.iter().all(|v| (v - 9.0).abs() < 1e-12));
}
other => panic!("not raked: {other:?}"),
}
match Payoff::Flat(-10.0).with_live_rake(2, 20.0) {
Payoff::Raked { pair, .. } => assert!(pair.iter().all(|v| (v + 10.0).abs() < 1e-12)),
other => panic!("not raked: {other:?}"),
}
}
#[test]
fn without_a_scope_the_river_trees_are_the_raw_ones() {
let raw = tree_with_chance(3, vec![1.0 / 9.0; 9], 6.0, 4.0);
assert!(raw.nodes.iter().all(|n| !matches!(n, Node::Terminal(Payoff::Raked { .. }))));
let g = build(3, vec![1.0 / 9.0; 9], &Bets::standard(6.0, 50.0, 0), &[]);
assert!(g.tree.nodes.iter().all(|n| !matches!(n, Node::Terminal(Payoff::Raked { .. }))));
}
#[test]
fn in_the_scope_every_river_leaf_pays_the_rake_of_its_pot() {
let _s = Scope::enter(1.0);
let t = tree_with_chance(3, vec![1.0 / 9.0; 9], 30.0, 20.0);
let rakes: Vec<f64> = t
.nodes
.iter()
.filter_map(|n| match n {
Node::Terminal(Payoff::Raked { rake, .. }) => Some(*rake),
_ => None,
})
.collect();
// check-check 30 -> 1.5, Fold-Toepfe 30 -> 1.5, gecallt 70 -> 3.5.
assert_eq!(rakes.len(), 5);
assert!(rakes.iter().all(|r| [1.5, 3.5].contains(r)), "{rakes:?}");
let g = build(3, vec![1.0 / 9.0; 9], &Bets::standard(30.0, 100.0, 0), &[]);
assert!(g.tree.nodes.iter().all(|n| !matches!(n, Node::Terminal(Payoff::Pair(_) | Payoff::Flat(_)))));
}
+61 -2
View File
@@ -4,7 +4,7 @@
use rechner::rake::{split_over_pots, uncalled, ChartRake, HandEnd, RakeRule, MEASURED_ANTE_BB};
/// Der gemessene Tisch in seiner eigenen Währung.
const TABLE: RakeRule = RakeRule { percent: 5.0, cap: 2000.0, cap_more_than_three: 2000.0 };
const TABLE: RakeRule = RakeRule { percent: 5.0, cap: 2000.0, cap_more_than_three: 2000.0, ..RakeRule::MEASURED_BB };
fn near(a: f64, b: f64) {
assert!((a - b).abs() < 1e-9, "{a} != {b}");
@@ -44,7 +44,7 @@ fn a_hand_that_ends_before_the_flop_pays_nothing() {
#[test]
fn more_than_three_players_use_their_own_cap_and_three_do_not() {
let rule = RakeRule { percent: 5.0, cap: 100.0, cap_more_than_three: 40.0 };
let rule = RakeRule { percent: 5.0, cap: 100.0, cap_more_than_three: 40.0, ..RakeRule::MEASURED_BB };
near(rule.of_hand(10_000.0, 3, HandEnd::FlopDealt), 100.0);
near(rule.of_hand(10_000.0, 4, HandEnd::FlopDealt), 40.0);
near(rule.of_hand(500.0, 4, HandEnd::FlopDealt), 25.0);
@@ -133,3 +133,62 @@ fn the_postflop_rake_never_shrinks_with_the_pot_and_never_passes_the_cap() {
last = r;
}
}
// -- Der Live-Tisch NL 0.01/0.02 (`RakeRule::MICRO_BB`) ---------------------------------------
// Gemessen 15.11. an 857 Händen der Mikro-Läufe vom 14.11. (`potAmount` gegen `potAmountAfterRake`).
/// Der Mikro-Tisch in Cent: 1 bb = 0.02.
fn micro(pot: f64, end: HandEnd) -> f64 {
RakeRule::MICRO_BB.of_hand(pot / 0.02, 2, end) * 0.02
}
#[test]
fn the_micro_table_takes_five_percent_rounded_to_the_cent() {
// Hand für Hand gemessen: 0.11 -> 0.01, 0.33 -> 0.02, 3.38 -> 0.17.
near(micro(0.11, HandEnd::FlopDealt), 0.01);
near(micro(0.33, HandEnd::FlopDealt), 0.02);
near(micro(3.38, HandEnd::FlopDealt), 0.17);
}
#[test]
fn half_a_cent_rounds_to_even() {
// 0.10 -> 0.005 -> 0 (15 Hände gemessen, alle ohne Rake); 0.30 -> 0.015 -> 0.02.
near(micro(0.10, HandEnd::FlopDealt), 0.0);
near(micro(0.30, HandEnd::FlopDealt), 0.02);
}
#[test]
fn the_micro_cap_is_ten_big_blinds() {
near(micro(4.03, HandEnd::FlopDealt), 0.20);
near(micro(7.99, HandEnd::FlopDealt), 0.20);
near(RakeRule::MICRO_BB.of_hand(1000.0, 6, HandEnd::FlopDealt), 10.0);
}
#[test]
fn at_the_micro_table_a_pot_without_flop_pays_too() {
// 50 von 428 Händen ohne Flop zahlten: jeder Topf ab 0.11.
near(micro(0.13, HandEnd::NoFlop), 0.01);
near(micro(0.41, HandEnd::NoFlop), 0.02);
near(micro(0.03, HandEnd::NoFlop), 0.0);
}
#[test]
fn the_measured_big_table_is_unchanged_by_the_micro_fields() {
assert_eq!(RakeRule::MEASURED_BB.step, 0.0);
assert!(RakeRule::MEASURED_BB.no_flop_no_drop);
assert_eq!(RakeRule::MEASURED_BB.of_hand(5.96, 2, HandEnd::FlopDealt), 0.05 * 5.96);
}
#[test]
fn the_micro_chart_rake_rises_with_the_pot_up_to_the_cap() {
near(ChartRake::Micro.all_in(200.0), 10.0);
near(ChartRake::Micro.all_in(5.5), 0.5);
near(ChartRake::Micro.postflop(6.5), 0.808);
near(ChartRake::Micro.postflop(20.0), 2.061);
let mut last = 0.0;
for k in 0..400 {
let r = ChartRake::Micro.postflop(k as f64 * 0.5);
assert!(r >= last && r <= 10.0, "{k}: {r}");
last = r;
}
}