poker-flopsolve 0.5.0-beta.0 → 0.5.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -975,6 +975,7 @@ function buildShowdownTable(runouts, relevant) {
975
975
  const onBoard = new Uint8Array(DECK);
976
976
  const strength = new Int32Array(COMBOS);
977
977
  const live = new Uint16Array(COMBOS);
978
+ const keys = new Float64Array(COMBOS);
978
979
  for (let board = 0; board < boards; board++) {
979
980
  const base = board * width;
980
981
  onBoard.fill(0);
@@ -996,8 +997,10 @@ function buildShowdownTable(runouts, relevant) {
996
997
  );
997
998
  live[count++] = combo;
998
999
  }
1000
+ for (let i2 = 0; i2 < count; i2++) keys[i2] = strength[live[i2]] * 2048 + live[i2];
1001
+ keys.subarray(0, count).sort();
999
1002
  const slice = live.subarray(0, count);
1000
- slice.sort((x, y) => strength[x] - strength[y]);
1003
+ for (let i2 = 0; i2 < count; i2++) slice[i2] = keys[i2] % 2048;
1001
1004
  order.set(slice, board * stride);
1002
1005
  liveCount[board] = count;
1003
1006
  const groupBase = board * (stride + 1);
@@ -1039,7 +1042,16 @@ function buildHandSpace(runouts, players, lists) {
1039
1042
  void players;
1040
1043
  const indexOf = new Int32Array(COMBOS).fill(-1);
1041
1044
  const upStart = [new Int32Array(0)];
1042
- const up = [];
1045
+ let upLength = 0;
1046
+ for (let round = 1; round < runouts.rounds; round++) {
1047
+ const orbitStart = runouts.orbitStart[round];
1048
+ for (let child = 0; child < runouts.counts[round]; child++) {
1049
+ const deals = orbitStart[child + 1] - orbitStart[child];
1050
+ upLength += deals * (span(lists, round, child, 0)[1] + span(lists, round, child, 1)[1]);
1051
+ }
1052
+ }
1053
+ const up = new Uint16Array(upLength);
1054
+ let upAt = 0;
1043
1055
  for (let round = 1; round < runouts.rounds; round++) {
1044
1056
  const orbitStart = runouts.orbitStart[round];
1045
1057
  const starts = new Int32Array(runouts.orbitMap[round].length * 2);
@@ -1051,12 +1063,12 @@ function buildHandSpace(runouts, players, lists) {
1051
1063
  const [childFrom, childCount] = span(lists, round, child, player);
1052
1064
  for (let m = orbitStart[child]; m < orbitStart[child + 1]; m++) {
1053
1065
  const back = runouts.maps.combo[runouts.maps.inverse(runouts.orbitMap[round][m])];
1054
- starts[m * 2 + player] = up.length;
1066
+ starts[m * 2 + player] = upAt;
1055
1067
  for (let k = 0; k < childCount; k++) {
1056
1068
  const real = back[lists.list[childFrom + k]];
1057
1069
  const at = indexOf[real];
1058
1070
  if (at < 0) throw new Error("A relabelled hand is not in its range; the relabelling must preserve both ranges");
1059
- up.push(at);
1071
+ up[upAt++] = at;
1060
1072
  }
1061
1073
  }
1062
1074
  markMembers(lists, parentFrom, parentCount, indexOf, true);
@@ -1066,7 +1078,8 @@ function buildHandSpace(runouts, players, lists) {
1066
1078
  }
1067
1079
  const slots = lists.roundBase[runouts.rounds] * 2;
1068
1080
  const sameStart = new Int32Array(slots + 1);
1069
- const same = [];
1081
+ const same = new Int32Array(lists.list.length);
1082
+ let sameAt = 0;
1070
1083
  for (let round = 0; round < runouts.rounds; round++) {
1071
1084
  for (let board = 0; board < runouts.counts[round]; board++) {
1072
1085
  for (let player = 0; player < 2; player++) {
@@ -1074,14 +1087,14 @@ function buildHandSpace(runouts, players, lists) {
1074
1087
  const [otherFrom, otherCount] = span(lists, round, board, 1 - player);
1075
1088
  markMembers(lists, otherFrom, otherCount, indexOf, false);
1076
1089
  const [from, count] = span(lists, round, board, player);
1077
- sameStart[slot] = same.length;
1078
- for (let i = 0; i < count; i++) same.push(indexOf[lists.list[from + i]]);
1090
+ sameStart[slot] = sameAt;
1091
+ for (let i = 0; i < count; i++) same[sameAt++] = indexOf[lists.list[from + i]];
1079
1092
  markMembers(lists, otherFrom, otherCount, indexOf, true);
1080
1093
  }
1081
1094
  }
1082
1095
  }
1083
- sameStart[slots] = same.length;
1084
- return { upStart, up: Uint16Array.from(up), sameStart, same: Int32Array.from(same) };
1096
+ sameStart[slots] = sameAt;
1097
+ return { upStart, up, sameStart, same };
1085
1098
  }
1086
1099
  function foldValuesHands(oppReach, cardA, cardB, oppFrom, oppCount, myFrom, myCount, same, sameFrom, payoff, sums, out) {
1087
1100
  let total = 0;
@@ -1191,7 +1204,7 @@ function treeDepth(ctx) {
1191
1204
  }
1192
1205
  function makeBuffers(ctx, width) {
1193
1206
  const depth = treeDepth(ctx);
1194
- const make = (factory) => Array.from({ length: depth }, factory);
1207
+ const make = (factory2) => Array.from({ length: depth }, factory2);
1195
1208
  const actions = ctx.layout.maxActions;
1196
1209
  return {
1197
1210
  value: make(() => new Float64Array(width * COMBOS)),
@@ -1477,52 +1490,20 @@ function simdAvailable() {
1477
1490
  }
1478
1491
 
1479
1492
  // src/cfr.ts
1480
- function buildPlayerIndex(weights) {
1493
+ function buildPlayerIndex(weights, reserve) {
1481
1494
  const combos = [];
1482
1495
  const slot = new Int32Array(COMBOS).fill(-1);
1483
1496
  for (let combo = 0; combo < COMBOS; combo++) {
1484
- if (weights[combo] > 0) {
1497
+ if (weights[combo] > 0 || reserve !== void 0 && reserve[combo] > 0) {
1485
1498
  slot[combo] = combos.length;
1486
1499
  combos.push(combo);
1487
1500
  }
1488
1501
  }
1489
1502
  return { combos: Uint16Array.from(combos), count: combos.length, slot, weights };
1490
1503
  }
1491
- function orbitLeader(runouts, round, board, combo) {
1492
- const from = runouts.stabiliserStart[round][board];
1493
- const to = runouts.stabiliserStart[round][board + 1];
1494
- for (let k = from + 1; k < to; k++) {
1495
- if (runouts.maps.combo[runouts.stabiliserMap[round][k]][combo] < combo) return false;
1496
- }
1497
- return true;
1498
- }
1499
1504
  var INT32_MAX = 2 ** 31 - 1;
1500
1505
  function buildLayout(tree, runouts, players, bytesPerElement, alias, compact) {
1501
- const roundBase = new Int32Array(runouts.rounds + 1);
1502
- for (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];
1503
- const rowStart = new Int32Array(roundBase[runouts.rounds] * 2);
1504
- const totals = new Int32Array(runouts.rounds * 2);
1505
- const onBoard = new Uint8Array(DECK);
1506
- for (let round = 0; round < runouts.rounds; round++) {
1507
- const width2 = runouts.width[round];
1508
- const cards = runouts.cards[round];
1509
- for (let board = 0; board < runouts.counts[round]; board++) {
1510
- onBoard.fill(0);
1511
- for (let i = 0; i < width2; i++) onBoard[cards[board * width2 + i]] = 1;
1512
- for (let player = 0; player < 2; player++) {
1513
- const index = players[player];
1514
- let live = 0;
1515
- for (let i = 0; i < index.count; i++) {
1516
- const combo = index.combos[i];
1517
- if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1518
- if (!orbitLeader(runouts, round, board, combo)) continue;
1519
- live++;
1520
- }
1521
- rowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];
1522
- totals[round * 2 + player] += live;
1523
- }
1524
- }
1525
- }
1506
+ const { roundBase, rowStart, totals } = liveRows(runouts, players);
1526
1507
  const offset = new Float64Array(tree.nodeCount).fill(-1);
1527
1508
  const blockOffset = new Int32Array(tree.nodeCount).fill(-1);
1528
1509
  const compactFrom = compact ? compact.from : runouts.rounds;
@@ -1609,6 +1590,50 @@ function buildLayout(tree, runouts, players, bytesPerElement, alias, compact) {
1609
1590
  chunkStart
1610
1591
  };
1611
1592
  }
1593
+ var liveRowsOf = /* @__PURE__ */ new WeakMap();
1594
+ function liveRows(runouts, players) {
1595
+ const kept = liveRowsOf.get(runouts);
1596
+ if (kept && kept.players[0] === players[0] && kept.players[1] === players[1]) return kept.rows;
1597
+ const roundBase = new Int32Array(runouts.rounds + 1);
1598
+ for (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];
1599
+ const rowStart = new Int32Array(roundBase[runouts.rounds] * 2);
1600
+ const totals = new Int32Array(runouts.rounds * 2);
1601
+ const onBoard = new Uint8Array(DECK);
1602
+ const comboMaps = runouts.maps.combo;
1603
+ for (let round = 0; round < runouts.rounds; round++) {
1604
+ const width = runouts.width[round];
1605
+ const cards = runouts.cards[round];
1606
+ const stabStart = runouts.stabiliserStart[round];
1607
+ const stabMap = runouts.stabiliserMap[round];
1608
+ for (let board = 0; board < runouts.counts[round]; board++) {
1609
+ onBoard.fill(0);
1610
+ for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1611
+ const stabFrom = stabStart[board] + 1;
1612
+ const stabTo = stabStart[board + 1];
1613
+ for (let player = 0; player < 2; player++) {
1614
+ const index = players[player];
1615
+ let live = 0;
1616
+ for (let i = 0; i < index.count; i++) {
1617
+ const combo = index.combos[i];
1618
+ if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1619
+ let leader = 1;
1620
+ for (let k = stabFrom; k < stabTo; k++) {
1621
+ if (comboMaps[stabMap[k]][combo] < combo) {
1622
+ leader = 0;
1623
+ break;
1624
+ }
1625
+ }
1626
+ live += leader;
1627
+ }
1628
+ rowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];
1629
+ totals[round * 2 + player] += live;
1630
+ }
1631
+ }
1632
+ }
1633
+ const rows = { roundBase, rowStart, totals };
1634
+ liveRowsOf.set(runouts, { players, rows });
1635
+ return rows;
1636
+ }
1612
1637
  function sharedNodes(tree, alias) {
1613
1638
  const marks = new Uint8Array(tree.nodeCount);
1614
1639
  for (let node = 0; node < tree.nodeCount; node++) {
@@ -1764,116 +1789,123 @@ function buildActiveLists(runouts, players, showdown = null) {
1764
1789
  const start = new Int32Array(slots);
1765
1790
  const count = new Uint16Array(slots);
1766
1791
  const packedSlot = new Uint8Array(slots);
1767
- const entries = [];
1768
- const entrySlots = [];
1769
- const memberStart = [];
1770
- const members = [];
1792
+ const capacity = roundBase[runouts.rounds] * (players[0].count + players[1].count);
1793
+ const list = new Uint16Array(capacity);
1794
+ const entrySlot = new Uint16Array(capacity);
1795
+ const strength = new Int32Array(capacity);
1796
+ const memberStart = new Int32Array(capacity + 1);
1797
+ let members = new Uint16Array(capacity);
1771
1798
  const onBoard = new Uint8Array(DECK);
1772
1799
  const seen = new Uint8Array(COMBOS);
1800
+ const comboMaps = runouts.maps.combo;
1801
+ const last = runouts.rounds - 1;
1802
+ let entries = 0;
1803
+ let memberCount = 0;
1773
1804
  for (let round = 0; round < runouts.rounds; round++) {
1774
1805
  const width = runouts.width[round];
1775
1806
  const cards = runouts.cards[round];
1776
1807
  const stabStart = runouts.stabiliserStart[round];
1777
1808
  const stabMap = runouts.stabiliserMap[round];
1809
+ const ranked = showdown !== null && round === last ? showdown : null;
1778
1810
  for (let board = 0; board < runouts.counts[round]; board++) {
1779
1811
  onBoard.fill(0);
1780
1812
  for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1781
- const symmetric = stabStart[board + 1] - stabStart[board] > 1;
1813
+ const stabFrom = stabStart[board] + 1;
1814
+ const stabTo = stabStart[board + 1];
1815
+ const symmetric = stabTo > stabFrom;
1816
+ if (memberCount + (players[0].count + players[1].count) * (stabTo - stabFrom + 1) > members.length) {
1817
+ const grown = new Uint16Array(Math.max(members.length * 2, memberCount + (players[0].count + players[1].count) * (stabTo - stabFrom + 1)));
1818
+ grown.set(members.subarray(0, memberCount));
1819
+ members = grown;
1820
+ }
1782
1821
  for (let player = 0; player < 2; player++) {
1783
1822
  const index = players[player];
1784
1823
  const slot = (roundBase[round] + board) * 2 + player;
1785
- start[slot] = entries.length;
1786
- const here = [];
1787
- for (let i = 0; i < index.count; i++) {
1788
- const combo = index.combos[i];
1789
- if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1790
- if (symmetric && !orbitLeader(runouts, round, board, combo)) continue;
1791
- here.push(i);
1792
- }
1793
- if (showdown !== null && round === runouts.rounds - 1) {
1794
- const group = strengthOn(showdown, board);
1795
- here.sort((x, y) => group[index.combos[x]] - group[index.combos[y]] || x - y);
1796
- }
1797
- for (const i of here) {
1798
- const combo = index.combos[i];
1799
- entries.push(combo);
1800
- entrySlots.push(i);
1801
- memberStart.push(members.length);
1802
- members.push(combo);
1803
- if (!symmetric) continue;
1804
- seen[combo] = 1;
1805
- for (let k = stabStart[board] + 1; k < stabStart[board + 1]; k++) {
1806
- const image = runouts.maps.combo[stabMap[k]][combo];
1807
- if (seen[image]) continue;
1808
- seen[image] = 1;
1809
- members.push(image);
1810
- packedSlot[slot] = 1;
1824
+ start[slot] = entries;
1825
+ const candidates = ranked ? ranked.liveCount[board] : index.count;
1826
+ const orderBase = ranked ? board * ranked.stride : 0;
1827
+ const groupBase = ranked ? board * (ranked.stride + 1) : 0;
1828
+ let group = 0;
1829
+ for (let c = 0; c < candidates; c++) {
1830
+ let combo;
1831
+ let at;
1832
+ if (ranked) {
1833
+ while (c >= ranked.groupStart[groupBase + group + 1]) group++;
1834
+ combo = ranked.order[orderBase + c];
1835
+ at = index.slot[combo];
1836
+ if (at < 0) continue;
1837
+ } else {
1838
+ at = c;
1839
+ combo = index.combos[c];
1840
+ if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1841
+ }
1842
+ let leader = true;
1843
+ for (let k = stabFrom; k < stabTo; k++) {
1844
+ if (comboMaps[stabMap[k]][combo] < combo) {
1845
+ leader = false;
1846
+ break;
1847
+ }
1811
1848
  }
1812
- for (let m = memberStart[memberStart.length - 1]; m < members.length; m++) seen[members[m]] = 0;
1849
+ if (!leader) continue;
1850
+ list[entries] = combo;
1851
+ entrySlot[entries] = at;
1852
+ strength[entries] = group;
1853
+ memberStart[entries] = memberCount;
1854
+ members[memberCount++] = combo;
1855
+ if (symmetric) {
1856
+ const first = memberCount - 1;
1857
+ seen[combo] = 1;
1858
+ for (let k = stabFrom; k < stabTo; k++) {
1859
+ const image = comboMaps[stabMap[k]][combo];
1860
+ if (seen[image]) continue;
1861
+ seen[image] = 1;
1862
+ members[memberCount++] = image;
1863
+ packedSlot[slot] = 1;
1864
+ }
1865
+ for (let m = first; m < memberCount; m++) seen[members[m]] = 0;
1866
+ }
1867
+ entries++;
1813
1868
  }
1814
- count[slot] = entries.length - start[slot];
1869
+ count[slot] = entries - start[slot];
1815
1870
  }
1816
1871
  }
1817
1872
  }
1818
- memberStart.push(members.length);
1819
- const list = Uint16Array.from(entries);
1820
- const cardA = new Uint8Array(list.length);
1821
- const cardB = new Uint8Array(list.length);
1822
- const multiplicity = new Float64Array(list.length);
1823
- for (let e = 0; e < list.length; e++) {
1873
+ memberStart[entries] = memberCount;
1874
+ const cardA = new Uint8Array(entries);
1875
+ const cardB = new Uint8Array(entries);
1876
+ const multiplicity = new Float64Array(entries);
1877
+ for (let e = 0; e < entries; e++) {
1824
1878
  cardA[e] = COMBO_CARDS[list[e] * 2];
1825
1879
  cardB[e] = COMBO_CARDS[list[e] * 2 + 1];
1826
1880
  multiplicity[e] = memberStart[e + 1] - memberStart[e];
1827
1881
  }
1828
- const memberCombo = Uint16Array.from(members);
1829
- const memberA = new Uint8Array(members.length);
1830
- const memberB = new Uint8Array(members.length);
1831
- for (let m = 0; m < members.length; m++) {
1832
- memberA[m] = COMBO_CARDS[members[m] * 2];
1833
- memberB[m] = COMBO_CARDS[members[m] * 2 + 1];
1834
- }
1835
- const strength = new Int32Array(list.length);
1836
- if (showdown !== null) {
1837
- const last = runouts.rounds - 1;
1838
- for (let board = 0; board < runouts.counts[last]; board++) {
1839
- const group = strengthOn(showdown, board);
1840
- for (let player = 0; player < 2; player++) {
1841
- const slot = (roundBase[last] + board) * 2 + player;
1842
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) strength[e] = group[list[e]];
1843
- }
1844
- }
1882
+ const memberCombo = members.slice(0, memberCount);
1883
+ const memberA = new Uint8Array(memberCount);
1884
+ const memberB = new Uint8Array(memberCount);
1885
+ for (let m = 0; m < memberCount; m++) {
1886
+ memberA[m] = COMBO_CARDS[memberCombo[m] * 2];
1887
+ memberB[m] = COMBO_CARDS[memberCombo[m] * 2 + 1];
1845
1888
  }
1846
1889
  return {
1847
1890
  start,
1848
1891
  count,
1849
- list,
1850
- slot: Uint16Array.from(entrySlots),
1892
+ list: list.slice(0, entries),
1893
+ slot: entrySlot.slice(0, entries),
1851
1894
  roundBase,
1852
1895
  cardA,
1853
1896
  cardB,
1854
- strength,
1897
+ strength: strength.slice(0, entries),
1855
1898
  packed: packedSlot,
1856
1899
  multiplicity,
1857
- memberStart: Int32Array.from(memberStart),
1900
+ memberStart: memberStart.slice(0, entries + 1),
1858
1901
  memberCombo,
1859
1902
  memberA,
1860
1903
  memberB
1861
1904
  };
1862
1905
  }
1863
- var strengthScratch = new Int32Array(COMBOS);
1864
- function strengthOn(table, board) {
1865
- const orderBase = board * table.stride;
1866
- const groupBase = board * (table.stride + 1);
1867
- for (let g = 0; g < table.groupCount[board]; g++) {
1868
- for (let i = table.groupStart[groupBase + g]; i < table.groupStart[groupBase + g + 1]; i++) {
1869
- strengthScratch[table.order[orderBase + i]] = g;
1870
- }
1871
- }
1872
- return strengthScratch;
1873
- }
1874
1906
  function makeBuffers2(tree, maxActions, simd) {
1875
1907
  const depth = treeDepth2(tree) + 2;
1876
- const make = (factory) => Array.from({ length: depth }, factory);
1908
+ const make = (factory2) => Array.from({ length: depth }, factory2);
1877
1909
  const kernels = simd ? loadKernels(depth, maxActions * COMBOS) : null;
1878
1910
  return {
1879
1911
  kernels,
@@ -2571,7 +2603,7 @@ function makeSolver(ctx) {
2571
2603
  const [from, count] = listOf(0, 0, traverser);
2572
2604
  let sum = 0;
2573
2605
  for (let i = 0; i < count; i++) sum += weights[lists.list[from + i]] * lists.multiplicity[from + i] * values[i];
2574
- return sum / ctx.totalMass;
2606
+ return sum / (matchupMass(ctx.players[0].weights, ctx.players[1].weights) * ctx.runoutWeight[0]);
2575
2607
  };
2576
2608
  return {
2577
2609
  ctx,
@@ -2611,7 +2643,7 @@ function makeSolver(ctx) {
2611
2643
  const [total1, values1] = one(1);
2612
2644
  return { totals: [total0, total1], values: [values0, values1] };
2613
2645
  },
2614
- handEvs(player, values) {
2646
+ handEvs(player, values, unit = (chips) => chips) {
2615
2647
  const opponent = ctx.players[1 - player];
2616
2648
  const evs = new Float64Array(COMBOS);
2617
2649
  const [from, count] = listOf(0, 0, player);
@@ -2631,7 +2663,7 @@ function makeSolver(ctx) {
2631
2663
  const d = COMBO_CARDS[other * 2 + 1];
2632
2664
  if (c !== a && c !== b && d !== a && d !== b) mass += opponent.weights[other];
2633
2665
  }
2634
- evs[combo] = mass > 0 ? values[i] / (mass * scale) : 0;
2666
+ evs[combo] = mass > 0 ? unit(values[i] / (mass * scale)) : 0;
2635
2667
  }
2636
2668
  }
2637
2669
  return evs;
@@ -2747,14 +2779,71 @@ function spawnWorker(setup, onError) {
2747
2779
  }
2748
2780
  };
2749
2781
  }
2750
- function spawnEngineWorker(setup, onError) {
2782
+ var ENGINE_POOL_KEY = /* @__PURE__ */ Symbol.for("poker-flopsolve.node-engine-threads");
2783
+ function enginePool() {
2784
+ const holder = globalThis;
2785
+ holder[ENGINE_POOL_KEY] ??= { idle: [], kept: 0 };
2786
+ return holder[ENGINE_POOL_KEY];
2787
+ }
2788
+ var ENGINE_THREAD_LINGER_MS = 3e4;
2789
+ function engineWorker(setup) {
2751
2790
  const url = new URL(import.meta.url.endsWith(".ts") ? "../engine-worker.ts" : "./engine-worker.js", import.meta.url);
2752
- const thread = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });
2753
- thread.on("error", onError);
2754
- thread.unref();
2791
+ const worker = new Worker(fileURLToPath(url), { workerData: setup, execArgv: workerFlags() });
2792
+ worker.unref();
2793
+ return worker;
2794
+ }
2795
+ function dropIdle(thread) {
2796
+ if (thread.linger) clearTimeout(thread.linger);
2797
+ thread.linger = null;
2798
+ void thread.worker.terminate();
2799
+ const { idle } = enginePool();
2800
+ const at = idle.indexOf(thread);
2801
+ if (at >= 0) idle.splice(at, 1);
2802
+ }
2803
+ function setLingers() {
2804
+ const pool = enginePool();
2805
+ pool.idle.forEach((thread, i) => {
2806
+ if (i < pool.kept) {
2807
+ if (thread.linger) clearTimeout(thread.linger);
2808
+ thread.linger = null;
2809
+ } else if (!thread.linger) {
2810
+ thread.linger = setTimeout(() => dropIdle(thread), ENGINE_THREAD_LINGER_MS);
2811
+ thread.linger.unref();
2812
+ }
2813
+ });
2814
+ }
2815
+ function warmEngineThreads(count) {
2816
+ const { idle } = enginePool();
2817
+ try {
2818
+ while (idle.length < count) {
2819
+ const thread = { worker: engineWorker(null), linger: null };
2820
+ thread.worker.on("error", () => dropIdle(thread));
2821
+ idle.push(thread);
2822
+ }
2823
+ } catch {
2824
+ }
2825
+ setLingers();
2826
+ }
2827
+ function spawnEngineWorker(setup, onError) {
2828
+ const waiting = enginePool().idle.shift();
2829
+ let worker;
2830
+ if (waiting) {
2831
+ if (waiting.linger) clearTimeout(waiting.linger);
2832
+ worker = waiting.worker;
2833
+ worker.removeAllListeners("error");
2834
+ worker.on("error", onError);
2835
+ worker.postMessage(setup);
2836
+ } else {
2837
+ worker = engineWorker(setup);
2838
+ worker.on("error", onError);
2839
+ }
2840
+ let released = false;
2755
2841
  return {
2756
2842
  terminate() {
2757
- void thread.terminate();
2843
+ if (released) return;
2844
+ released = true;
2845
+ void worker.terminate();
2846
+ warmEngineThreads(enginePool().idle.length + 1);
2758
2847
  }
2759
2848
  };
2760
2849
  }
@@ -2999,8 +3088,46 @@ function compiledStorage(source, kind) {
2999
3088
  if (!cache) storageModules.set(source, cache = { plain: void 0, shared: void 0 });
3000
3089
  return compileInto(cache, kind, source[kind]);
3001
3090
  }
3091
+ var PROFILE = { traversals: 0, collect: 1, override: 2, wait: 3, reduce: 4, run: 5, busy: 6 };
3092
+ var threadProfiles = /* @__PURE__ */ new WeakMap();
3093
+ function scheduleBytes(boards) {
3094
+ return Math.ceil(boards / 2) * 8 + 2 * boards * 8;
3095
+ }
3096
+ function scheduleViews(buffer, boards) {
3097
+ return {
3098
+ order: new Int32Array(buffer, 0, boards),
3099
+ cost: new Float64Array(buffer, Math.ceil(boards / 2) * 8, 2 * boards)
3100
+ };
3101
+ }
3102
+ var TOUCH_STEP = 4096;
3103
+ function touchShares(ranges, shares) {
3104
+ const total = ranges.reduce((sum, [from, to]) => sum + (to - from), 0);
3105
+ const each = Math.ceil(total / shares / TOUCH_STEP) * TOUCH_STEP;
3106
+ const out = Array.from({ length: shares }, () => []);
3107
+ let share = 0;
3108
+ let room = each;
3109
+ for (const [start, to] of ranges) {
3110
+ let from = start;
3111
+ while (from < to) {
3112
+ const take = Math.min(room, to - from);
3113
+ out[share].push(from, from + take);
3114
+ from += take;
3115
+ room -= take;
3116
+ if (room === 0 && share < shares - 1) {
3117
+ share++;
3118
+ room = each;
3119
+ }
3120
+ }
3121
+ }
3122
+ return out;
3123
+ }
3124
+ function touchStorage(bytes, share) {
3125
+ for (let r = 0; r < share.length; r += 2) {
3126
+ for (let at = share[r]; at < share[r + 1]; at += TOUCH_STEP) bytes[at] = 0;
3127
+ }
3128
+ }
3002
3129
  var MAX_MEMORY = 4294901760;
3003
- var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 };
3130
+ var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, next: 7, size: 8 };
3004
3131
  function createEngine(input, pool) {
3005
3132
  const shared = pool !== void 0;
3006
3133
  const storage = input.storage ?? null;
@@ -3023,15 +3150,16 @@ function createEngine(input, pool) {
3023
3150
  const [upRound, upStart] = flatten(hands.upStart);
3024
3151
  const [childRound, childStart] = flatten(runouts.childStart);
3025
3152
  const [orbitRound, orbitStart] = flatten(runouts.orbitStart);
3026
- const maxCount = Math.max(4, ...active.count);
3153
+ let maxCount = 4;
3154
+ for (let i = 0; i < active.count.length; i++) if (active.count[i] > maxCount) maxCount = active.count[i];
3027
3155
  const stride = Math.ceil(maxCount / 4) * 4;
3028
3156
  const maxActions = Math.max(1, layout.maxActions);
3029
3157
  const depths = treeDepth2(tree) + 2;
3030
3158
  const rowBytes = stride * 4;
3031
3159
  const depthBytes = rowBytes * (3 + 2 * maxActions);
3032
3160
  const pieces = [];
3033
- const add = (data, bytes2 = data ? data.byteLength : 0) => {
3034
- pieces.push({ data, bytes: Math.ceil(Math.max(bytes2, 4) / 16) * 16 });
3161
+ const add = (data, bytes2 = data ? data.byteLength : 0, empty = data === null) => {
3162
+ pieces.push({ data, bytes: Math.ceil(Math.max(bytes2, 4) / 16) * 16, empty });
3035
3163
  return pieces.length - 1;
3036
3164
  };
3037
3165
  const common = [
@@ -3046,12 +3174,12 @@ function createEngine(input, pool) {
3046
3174
  add(layout.rowStart),
3047
3175
  add(active.roundBase),
3048
3176
  add(active.start),
3049
- add(Int32Array.from(active.count)),
3177
+ add(new Int32Array(active.count)),
3050
3178
  add(active.cardA),
3051
3179
  add(active.cardB),
3052
3180
  add(active.strength),
3053
3181
  add(active.packed),
3054
- add(Float32Array.from(active.multiplicity)),
3182
+ add(new Float32Array(active.multiplicity)),
3055
3183
  add(active.memberStart),
3056
3184
  add(active.memberA),
3057
3185
  add(active.memberB),
@@ -3077,13 +3205,13 @@ function createEngine(input, pool) {
3077
3205
  cardSums: add(null, 52 * 8 + stride * 8),
3078
3206
  rootMe: add(null, rowBytes),
3079
3207
  rootOpp: add(null, rowBytes),
3080
- header: add(null, 40 * 4)
3208
+ header: add(null, 40 * 4, false)
3081
3209
  }));
3082
3210
  const entries = pool ? pool.plan.entryNodes.length : 0;
3083
3211
  const entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;
3084
3212
  const reach = pool ? add(null, entries * 2 * rowBytes) : -1;
3085
3213
  const values = pool ? add(null, entries * rowBytes) : -1;
3086
- const partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;
3214
+ const boardValues = pool ? add(null, pool.plan.boards * entries * rowBytes) : -1;
3087
3215
  const plan = input.sampling;
3088
3216
  const sample = plan ? {
3089
3217
  baseOffset: add(plan.baseOffset),
@@ -3101,13 +3229,13 @@ function createEngine(input, pool) {
3101
3229
  } : null;
3102
3230
  const chunks = compact ? layout.chunkSlots.length : 0;
3103
3231
  const stored = storage ? {
3104
- block: add(null, 128),
3232
+ block: add(null, 128, false),
3105
3233
  blockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),
3106
3234
  regretScale: quantised ? add(null, layout.blocks * 8) : -1,
3107
3235
  sumScale: quantised ? add(null, layout.blocks * 8) : -1,
3108
3236
  compactChunk: compact ? add(layout.compactChunk) : -1,
3109
- handOffset: compact ? add(Int32Array.from(layout.handOffset)) : -1,
3110
- tables: compact ? add(null, chunks * 4 * 5) : -1,
3237
+ handOffset: compact ? add(new Int32Array(layout.handOffset)) : -1,
3238
+ tables: compact ? add(null, chunks * 4 * 5, false) : -1,
3111
3239
  regrets: layout.chunkSlots.map((slots) => add(null, slots * (compact.float ? 4 : 1))),
3112
3240
  shifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],
3113
3241
  sums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],
@@ -3127,6 +3255,10 @@ function createEngine(input, pool) {
3127
3255
  pieces.forEach((piece, i) => {
3128
3256
  if (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);
3129
3257
  });
3258
+ const touch = touchShares(
3259
+ pieces.flatMap((piece, i) => piece.empty && piece.bytes >= 16 * TOUCH_STEP ? [[offsets[i], offsets[i] + piece.bytes]] : []),
3260
+ threads
3261
+ );
3130
3262
  for (const mine of own) {
3131
3263
  const head = new Uint32Array(memory.buffer, offsets[mine.header], 40);
3132
3264
  common.forEach((slot, i) => head[i] = offsets[slot]);
@@ -3231,14 +3363,22 @@ function createEngine(input, pool) {
3231
3363
  };
3232
3364
  let control = null;
3233
3365
  let settings = null;
3366
+ let profile = null;
3367
+ let schedule = null;
3234
3368
  const workers = [];
3235
3369
  let failure = null;
3370
+ if (!pool) touchStorage(bytes, touch[0]);
3236
3371
  if (pool) {
3237
3372
  const plan2 = pool.plan;
3238
3373
  const controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);
3239
3374
  const settingsBuffer = new SharedArrayBuffer(8 * 8);
3240
3375
  control = new Int32Array(controlBuffer);
3241
3376
  settings = new Float64Array(settingsBuffer);
3377
+ const profileBuffer = new SharedArrayBuffer(8 * (PROFILE.busy + threads));
3378
+ profile = new Float64Array(profileBuffer);
3379
+ const scheduleBuffer = new SharedArrayBuffer(scheduleBytes(plan2.boards));
3380
+ schedule = scheduleViews(scheduleBuffer, plan2.boards);
3381
+ for (let i = 0; i < plan2.boards; i++) schedule.order[i] = i;
3242
3382
  exports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);
3243
3383
  for (let w = 1; w < threads; w++) {
3244
3384
  const setup = {
@@ -3247,17 +3387,20 @@ function createEngine(input, pool) {
3247
3387
  header: offsets[own[w].header],
3248
3388
  maxActions,
3249
3389
  exchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],
3250
- shard: [plan2.round, plan2.bounds[w], plan2.bounds[w + 1]],
3390
+ shard: [plan2.round, plan2.boards],
3251
3391
  entryNodes: plan2.entryNodes,
3252
3392
  rootMe: offsets[own[w].rootMe],
3253
3393
  rootOpp: offsets[own[w].rootOpp],
3254
- partial: offsets[partials] + (w - 1) * entries * rowBytes,
3394
+ boardValues: offsets[boardValues],
3395
+ schedule: scheduleBuffer,
3255
3396
  stride,
3256
3397
  control: controlBuffer,
3257
3398
  settings: settingsBuffer,
3258
3399
  ...share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] } : {},
3259
3400
  ...stored ? { storage: true } : {},
3260
- ...samplingArgs ? { sampling: samplingArgs } : {}
3401
+ ...samplingArgs ? { sampling: samplingArgs } : {},
3402
+ profile: [profileBuffer, PROFILE.busy + w],
3403
+ touch: touch[w]
3261
3404
  };
3262
3405
  workers.push(pool.spawn(setup, (error) => {
3263
3406
  failure ??= error;
@@ -3267,6 +3410,7 @@ function createEngine(input, pool) {
3267
3410
  Atomics.notify(control, ENGINE_CONTROL.ready);
3268
3411
  }));
3269
3412
  }
3413
+ touchStorage(bytes, touch[0]);
3270
3414
  const deadline = Date.now() + WORKER_START_MS;
3271
3415
  for (; ; ) {
3272
3416
  const ready = Atomics.load(control, ENGINE_CONTROL.ready);
@@ -3321,25 +3465,41 @@ function createEngine(input, pool) {
3321
3465
  };
3322
3466
  const runThreaded = (mode, traverser, apply, positive, negative, sum, weight, clamp) => {
3323
3467
  const plan2 = pool.plan;
3468
+ const { order, cost } = schedule;
3469
+ const clock = performance.now();
3324
3470
  exports.setShard(plan2.round, 0, 0);
3325
3471
  exports.setPhase(1, 0);
3326
3472
  exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);
3473
+ const collected = performance.now();
3474
+ const costs = cost.subarray(traverser * plan2.boards, (traverser + 1) * plan2.boards);
3475
+ const timed = mode === Mode.Train && apply === 1;
3476
+ order.sort((a, b) => costs[b] - costs[a] || a - b);
3327
3477
  settings.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);
3328
3478
  Atomics.store(control, ENGINE_CONTROL.done, 0);
3479
+ Atomics.store(control, ENGINE_CONTROL.next, 0);
3329
3480
  Atomics.store(control, ENGINE_CONTROL.mode, mode);
3330
3481
  Atomics.store(control, ENGINE_CONTROL.traverser, traverser);
3331
3482
  Atomics.store(control, ENGINE_CONTROL.command, 0);
3332
3483
  Atomics.add(control, ENGINE_CONTROL.generation, 1);
3333
3484
  Atomics.notify(control, ENGINE_CONTROL.generation);
3334
3485
  const dispatched = performance.now();
3335
- exports.setShard(plan2.round, plan2.bounds[0], plan2.bounds[1]);
3336
3486
  exports.setPhase(0, apply);
3337
- const valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);
3338
- for (let entry = 0; entry < entries; entry++) {
3339
- const slot = offsets[reach] + entry * 2 * rowBytes;
3340
- const out = exports.runChance(mode, traverser, plan2.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 0;
3341
- valueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);
3487
+ const heap = new Float32Array(memory.buffer);
3488
+ const into = offsets[boardValues] >>> 2;
3489
+ for (; ; ) {
3490
+ const taken = Atomics.add(control, ENGINE_CONTROL.next, 1);
3491
+ if (taken >= plan2.boards) break;
3492
+ const board = order[taken];
3493
+ exports.setShard(plan2.round, board, board + 1);
3494
+ const started = performance.now();
3495
+ for (let entry = 0; entry < entries; entry++) {
3496
+ const slot = offsets[reach] + entry * 2 * rowBytes;
3497
+ const out = exports.runChance(mode, traverser, plan2.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 2;
3498
+ heap.copyWithin(into + (board * entries + entry) * stride, out, out + stride);
3499
+ }
3500
+ if (timed) costs[board] = performance.now() - started;
3342
3501
  }
3502
+ const walked = performance.now();
3343
3503
  failure ??= awaitThreads(
3344
3504
  control,
3345
3505
  ENGINE_CONTROL.done,
@@ -3350,15 +3510,28 @@ function createEngine(input, pool) {
3350
3510
  );
3351
3511
  const dead = failed();
3352
3512
  if (dead) throw dead;
3353
- const partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);
3354
- for (let w = 0; w < threads - 1; w++) {
3355
- for (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];
3513
+ const waited = performance.now();
3514
+ const valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);
3515
+ valueView.fill(0);
3516
+ for (let board = 0; board < plan2.boards; board++) {
3517
+ const rows = into + board * entries * stride;
3518
+ for (let i = 0; i < entries * stride; i++) valueView[i] += heap[rows + i];
3356
3519
  }
3520
+ const reduced = performance.now();
3357
3521
  exports.setShard(plan2.round, 0, 0);
3358
3522
  exports.setPhase(2, apply);
3359
3523
  const at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;
3360
3524
  exports.setPhase(0, 1);
3361
3525
  exports.setShard(-1, 0, 0);
3526
+ const p = profile;
3527
+ const finished = performance.now();
3528
+ p[PROFILE.traversals]++;
3529
+ p[PROFILE.collect] += collected - clock;
3530
+ p[PROFILE.busy] += walked - dispatched;
3531
+ p[PROFILE.wait] += waited - walked;
3532
+ p[PROFILE.reduce] += reduced - waited;
3533
+ p[PROFILE.override] += finished - reduced;
3534
+ p[PROFILE.run] += finished - clock;
3362
3535
  return at;
3363
3536
  };
3364
3537
  return {
@@ -3370,6 +3543,7 @@ function createEngine(input, pool) {
3370
3543
  sampling: samplingViews,
3371
3544
  discounted,
3372
3545
  threads,
3546
+ profile,
3373
3547
  root(dcfr) {
3374
3548
  return (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);
3375
3549
  },
@@ -3529,70 +3703,119 @@ function warmStart(to, from, averages, cards, tolerance = SIZE_TOLERANCE) {
3529
3703
  const newSum = new Float64Array(width);
3530
3704
  const keepsRegrets = (ctx) => ctx.regret.length > 0 || (ctx.compactRegret ?? null) !== null;
3531
3705
  const hasRegret = keepsRegrets(to) && keepsRegrets(from);
3532
- const position = new Int32Array(COMBOS).fill(-1);
3706
+ const rounds = to.runouts.rounds;
3707
+ const nodesOf = Array.from({ length: rounds * 2 }, () => []);
3708
+ const actionsOf = /* @__PURE__ */ new Map();
3533
3709
  let matched = 0;
3534
3710
  for (const node of tree.decisionNodes) {
3535
3711
  const old = match[node];
3536
3712
  if (old < 0) continue;
3537
3713
  matched++;
3538
- const round = tree.round[node];
3539
- const owner = tree.player[node];
3540
3714
  const actions = tree.numEdges[node];
3541
- const oldActions = from.tree.numEdges[old];
3542
3715
  const actionOf = new Int32Array(actions).fill(-1);
3543
3716
  for (let e = 0; e < actions; e++) {
3544
3717
  const other = matchEdge(tree, tree.firstEdge[node] + e, node, from.tree, old, tolerance);
3545
3718
  if (other >= 0) actionOf[e] = other - from.tree.firstEdge[old];
3546
3719
  }
3720
+ actionsOf.set(node, actionOf);
3721
+ nodesOf[tree.round[node] * 2 + tree.player[node]].push(node);
3722
+ }
3723
+ const position = new Int32Array(COMBOS).fill(-1);
3724
+ const sourceOf = new Int32Array(COMBOS);
3725
+ const sourceEnd = new Int32Array(COMBOS);
3726
+ for (let round = 0; round < rounds; round++) {
3727
+ if (nodesOf[round * 2].length + nodesOf[round * 2 + 1].length === 0) continue;
3547
3728
  for (let board = 0; board < to.runouts.counts[round]; board++) {
3548
3729
  const resolved = resolveBoard(from.runouts, asSource(realCards(to.runouts, round, board)));
3549
- const oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;
3550
- const oldFrom = from.active.start[oldSlot];
3551
- const oldCount = from.active.count[oldSlot];
3552
- const oldBlock = from.layout.blockOffset[old] + resolved.board;
3553
- const oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];
3554
- const oldLength = oldActions * oldCount;
3555
- if (round >= from.layout.compactFrom) {
3556
- readCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);
3557
- } else {
3558
- if (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);
3559
- readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);
3560
- }
3561
- markMembers(from.active, oldFrom, oldCount, position, false);
3562
- const newSlot = (to.active.roundBase[round] + board) * 2 + owner;
3563
- const newFrom = to.active.start[newSlot];
3564
- const count = to.active.count[newSlot];
3565
- const length = actions * count;
3566
- newRegret.fill(0, 0, length);
3567
- newSum.fill(0, 0, length);
3568
- for (let i = 0; i < count; i++) {
3569
- const firstMember = to.active.memberStart[newFrom + i];
3570
- const membersEnd = to.active.memberStart[newFrom + i + 1];
3571
- const share = 1 / (membersEnd - firstMember);
3572
- for (let m = firstMember; m < membersEnd; m++) {
3573
- const j = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];
3574
- if (j < 0) continue;
3730
+ for (let owner = 0; owner < 2; owner++) {
3731
+ const nodes = nodesOf[round * 2 + owner];
3732
+ if (nodes.length === 0) continue;
3733
+ const oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;
3734
+ const oldFrom = from.active.start[oldSlot];
3735
+ const oldCount = from.active.count[oldSlot];
3736
+ const newSlot = (to.active.roundBase[round] + board) * 2 + owner;
3737
+ const newFrom = to.active.start[newSlot];
3738
+ const count = to.active.count[newSlot];
3739
+ markMembers(from.active, oldFrom, oldCount, position, false);
3740
+ let sources = 0;
3741
+ for (let i = 0; i < count; i++) {
3742
+ for (let m = to.active.memberStart[newFrom + i]; m < to.active.memberStart[newFrom + i + 1]; m++) {
3743
+ sourceOf[sources++] = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];
3744
+ }
3745
+ sourceEnd[i] = sources;
3746
+ }
3747
+ markMembers(from.active, oldFrom, oldCount, position, true);
3748
+ const direct = sources === count && round < from.layout.compactFrom && round < to.layout.compactFrom && from.regretScale === null && to.regretScale === null;
3749
+ for (const node of nodes) {
3750
+ const old = match[node];
3751
+ const actions = tree.numEdges[node];
3752
+ const oldActions = from.tree.numEdges[old];
3753
+ const actionOf = actionsOf.get(node);
3754
+ const oldBlock = from.layout.blockOffset[old] + resolved.board;
3755
+ const oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];
3756
+ const oldLength = oldActions * oldCount;
3757
+ if (direct) {
3758
+ const base2 = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3759
+ if (hasRegret) copyRows(to.regret, base2, from.regret, oldBase, actionOf, count, oldCount, sourceOf);
3760
+ if (averages) copyRows(to.strategySum, base2, from.strategySum, oldBase, actionOf, count, oldCount, sourceOf);
3761
+ continue;
3762
+ }
3763
+ if (round >= from.layout.compactFrom) {
3764
+ readCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);
3765
+ } else {
3766
+ if (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);
3767
+ if (averages) readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);
3768
+ }
3769
+ const length = actions * count;
3770
+ newRegret.fill(0, 0, length);
3771
+ if (averages) newSum.fill(0, 0, length);
3575
3772
  for (let e = 0; e < actions; e++) {
3576
3773
  const action = actionOf[e];
3577
3774
  if (action < 0) continue;
3578
- newRegret[e * count + i] += share * oldRegret[action * oldCount + j];
3579
- newSum[e * count + i] += share * oldSum[action * oldCount + j];
3775
+ const row = e * count;
3776
+ const oldRow = action * oldCount;
3777
+ let first = 0;
3778
+ for (let i = 0; i < count; i++) {
3779
+ const end = sourceEnd[i];
3780
+ const share = 1 / (end - first);
3781
+ for (let k = first; k < end; k++) {
3782
+ const j = sourceOf[k];
3783
+ if (j < 0) continue;
3784
+ if (hasRegret) newRegret[row + i] += share * oldRegret[oldRow + j];
3785
+ if (averages) newSum[row + i] += share * oldSum[oldRow + j];
3786
+ }
3787
+ first = end;
3788
+ }
3789
+ }
3790
+ const block = to.layout.blockOffset[node] + board;
3791
+ const base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3792
+ if (round >= to.layout.compactFrom) {
3793
+ writeCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);
3794
+ } else {
3795
+ if (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS2, block, base, length, newRegret);
3796
+ if (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS2, block, base, length, newSum);
3580
3797
  }
3581
3798
  }
3582
3799
  }
3583
- markMembers(from.active, oldFrom, oldCount, position, true);
3584
- const block = to.layout.blockOffset[node] + board;
3585
- const base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3586
- if (round >= to.layout.compactFrom) {
3587
- writeCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);
3588
- } else {
3589
- if (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS2, block, base, length, newRegret);
3590
- if (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS2, block, base, length, newSum);
3591
- }
3592
3800
  }
3593
3801
  }
3594
3802
  return { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };
3595
3803
  }
3804
+ function copyRows(to, base, from, oldBase, actionOf, count, oldCount, sourceOf) {
3805
+ for (let e = 0; e < actionOf.length; e++) {
3806
+ const action = actionOf[e];
3807
+ const row = base + e * count;
3808
+ if (action < 0) {
3809
+ to.fill(0, row, row + count);
3810
+ continue;
3811
+ }
3812
+ const oldRow = oldBase + action * oldCount;
3813
+ for (let i = 0; i < count; i++) {
3814
+ const j = sourceOf[i];
3815
+ to[row + i] = j < 0 ? 0 : from[oldRow + j];
3816
+ }
3817
+ }
3818
+ }
3596
3819
  function checkRelabelling(cards, a, b) {
3597
3820
  const seen = new Uint8Array(DECK);
3598
3821
  if (cards.length !== DECK) throw new Error(`A card relabelling maps all ${DECK} cards; got ${cards.length}`);
@@ -3922,6 +4145,1473 @@ function linesWithin(solution, maxBytes, options = {}) {
3922
4145
  return lines(low);
3923
4146
  }
3924
4147
 
4148
+ // src/vendor/range-compress.js
4149
+ function factory() {
4150
+ const RANKS2 = "23456789TJQKA", SUITS2 = "cdhs";
4151
+ const cardFromStr = (s) => RANKS2.indexOf(s[0]) * 4 + SUITS2.indexOf(s[1]);
4152
+ const cardToStr = (c) => RANKS2[c >> 2] + SUITS2[c & 3];
4153
+ const handToStr = (a, b) => a > b ? cardToStr(a) + cardToStr(b) : cardToStr(b) + cardToStr(a);
4154
+ const hid = (h) => h.a * 52 + h.b;
4155
+ const cls = (h) => {
4156
+ const r1 = h.a >> 2, r2 = h.b >> 2, hi = Math.max(r1, r2), lo = Math.min(r1, r2);
4157
+ return (h.a & 3) === (h.b & 3) ? hi * 13 + lo : lo * 13 + hi;
4158
+ };
4159
+ function parseRange2(text) {
4160
+ const out = /* @__PURE__ */ new Map();
4161
+ const re = /\[(\d+(?:\.\d+)?)\]([^\[]*)\[\/\1\]|([^\[\],\s]+)/g;
4162
+ let m;
4163
+ const add = (tok, w) => {
4164
+ tok = tok.trim();
4165
+ if (!tok) return;
4166
+ if (tok.length !== 4) throw new Error("unsupported token " + tok);
4167
+ let a = cardFromStr(tok.slice(0, 2)), b = cardFromStr(tok.slice(2, 4));
4168
+ if (a > b) {
4169
+ const t = a;
4170
+ a = b;
4171
+ b = t;
4172
+ }
4173
+ out.set(a * 52 + b, { a, b, w });
4174
+ };
4175
+ while (m = re.exec(text)) {
4176
+ if (m[2] !== void 0) {
4177
+ const w = parseFloat(m[1]) / 100;
4178
+ const parts = m[2].split(",");
4179
+ for (let i = 0; i < parts.length; i++) add(parts[i], w);
4180
+ } else add(m[3], 1);
4181
+ }
4182
+ return [...out.values()].filter((h) => h.w > 0).sort((x, y) => x.a - y.a || x.b - y.b);
4183
+ }
4184
+ function rangeToString(hands) {
4185
+ const groups = /* @__PURE__ */ new Map();
4186
+ for (const h of hands) {
4187
+ const k = (Math.round(h.w * 1e4) / 100).toFixed(2);
4188
+ if (!groups.has(k)) groups.set(k, []);
4189
+ groups.get(k).push(handToStr(h.a, h.b));
4190
+ }
4191
+ const parts = [];
4192
+ for (const [k, v] of [...groups.entries()].sort((x, y) => x[0] - y[0])) {
4193
+ if (k === "100.00") parts.push(v.join(", "));
4194
+ else parts.unshift("[" + k + "]" + v.join(", ") + "[/" + k + "]");
4195
+ }
4196
+ return parts.join(", ");
4197
+ }
4198
+ const KERNELS_B64 = "AGFzbQEAAAABQAdgBH9/f38Bf2AHf39/f39/fwF/YAV/f39/fwF/YAV/f39/fwBgBH9/f38AYAF/AGANf39/f39/f39/f39/fAACDwEDZW52Bm1lbW9yeQIAAAMIBwABAgMEBQYGEAN/AUEAC38BQQALfwFBAAsHSwcJaW52ZXJ0U1BEAAQHb2JzUGljawACCW9ic1JlbW92ZQABCGFkZFN0YXRlAAYEbm5scwADCmVxdWl0eVBhc3MABQZtZW1vcnkCAArJNgelAwEBfyADBEBBHyADZ2siAUEQdEGAgMADckEfIABBfiABd3Fna0EMdHIPCyABIAJBf3NxIQEgAgRAIAJBfkEfIAJnayICd3EiAwRAIAJBEHRBgICAA3JBHyAD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IA5BAnRqKAIAIhMEfyAGIBIgE2pBAWtBAnRqKAIAIBFGBUEACwRAIAcgEiATakEBa0EDdGoiDiAOKwMAIBWgOQMABSAGIBIgE2oiEkECdGogETYCACAHIBJBA3RqIBU5AwAgCCAOQQJ0aiATQQFqNgIACwsLIA9BAWohDwwBCwsDQCAEIBBKBEAgBSAQbCIAIAggEEECdGooAgBqIQIDQCAAIAJIBEAgCiAGIABBAnRqKAIAIgFBA3RqIgMgAysDACAHIABBA3RqKwMAIhQgDKIiFSAUoqA5AwAgCSABIAtsQQN0aiEDIABBAWohAQNAIAEgAkgEQCADIAYgAUECdGooAgBBA3RqIg0gDSsDACAVIAcgAUEDdGorAwCioDkDACABQQFqIQEMAQsLIABBAWohAAwBCwsgEEEBaiEQDAELCws=";
4199
+ let WK = null, arena = false, wasmOn = true, wasmP = null;
4200
+ const FULL = { full: true };
4201
+ function wasm3() {
4202
+ if (WK !== null) return WK;
4203
+ WK = false;
4204
+ if (!KERNELS_B64 || typeof WebAssembly === "undefined") return WK;
4205
+ let bin, mem, imports;
4206
+ const setup = (inst) => {
4207
+ new Uint8Array(mem.buffer, 16384, 8192).set(POPC);
4208
+ new Int8Array(mem.buffer, 16384 + 8192, 8192).set(STRT);
4209
+ new Int32Array(mem.buffer, 16384 + 16384, 8192).set(FLUSHV);
4210
+ return { mem, ex: inst.exports, top: 65536, limit: 0, buf: null, tab: 16384 };
4211
+ };
4212
+ try {
4213
+ bin = typeof atob === "function" ? Uint8Array.from(atob(KERNELS_B64), (c) => c.charCodeAt(0)) : new Uint8Array(Buffer.from(KERNELS_B64, "base64"));
4214
+ mem = new WebAssembly.Memory({ initial: 64 });
4215
+ imports = { env: { memory: mem, abort() {
4216
+ } } };
4217
+ WK = setup(new WebAssembly.Instance(new WebAssembly.Module(bin), imports));
4218
+ } catch (e) {
4219
+ WK = false;
4220
+ try {
4221
+ if (bin && mem) wasmP = WebAssembly.instantiate(bin, imports).then((r) => {
4222
+ WK = setup(r.instance);
4223
+ return true;
4224
+ }, () => false);
4225
+ } catch (e2) {
4226
+ wasmP = null;
4227
+ }
4228
+ }
4229
+ return WK;
4230
+ }
4231
+ function releaseMemory() {
4232
+ if (!arena) {
4233
+ WK = null;
4234
+ wasmP = null;
4235
+ }
4236
+ }
4237
+ function ready() {
4238
+ const w = wasm3();
4239
+ return w ? Promise.resolve(true) : wasmP || Promise.resolve(false);
4240
+ }
4241
+ function withArena(bytes, fn) {
4242
+ const w = wasmOn && !arena ? wasm3() : false;
4243
+ if (!w) return fn();
4244
+ try {
4245
+ const need = 65536 + bytes, have = w.mem.buffer.byteLength;
4246
+ if (need > have) w.mem.grow(Math.ceil((need - have) / 65536));
4247
+ w.top = 65536;
4248
+ w.buf = w.mem.buffer;
4249
+ w.limit = w.buf.byteLength;
4250
+ arena = true;
4251
+ return fn();
4252
+ } catch (e) {
4253
+ if (e !== FULL) throw e;
4254
+ arena = false;
4255
+ return fn();
4256
+ } finally {
4257
+ arena = false;
4258
+ }
4259
+ }
4260
+ function mk(Type, n, zero) {
4261
+ if (!arena) return new Type(n);
4262
+ const p = WK.top + 15 & ~15, bytes = n * Type.BYTES_PER_ELEMENT;
4263
+ if (p + bytes > WK.limit) throw FULL;
4264
+ WK.top = p + bytes;
4265
+ const a = new Type(WK.buf, p, n);
4266
+ if (zero) a.fill(0);
4267
+ return a;
4268
+ }
4269
+ const inW = (a) => arena && a.buffer === WK.buf;
4270
+ const POPC = new Uint8Array(8192), STRT = new Int8Array(8192).fill(-1), FLUSHV = new Int32Array(8192);
4271
+ const top5 = (m) => {
4272
+ let v = 0;
4273
+ for (let sh = 16; sh >= 0; sh -= 4) {
4274
+ const r = 31 - Math.clz32(m);
4275
+ v |= r << sh;
4276
+ m &= ~(1 << r);
4277
+ }
4278
+ return v;
4279
+ };
4280
+ for (let m = 1; m < 8192; m++) {
4281
+ POPC[m] = POPC[m >> 1] + (m & 1);
4282
+ for (let hi = 12; hi >= 4; hi--) if ((m >> hi - 4 & 31) === 31) {
4283
+ STRT[m] = hi;
4284
+ break;
4285
+ }
4286
+ if (STRT[m] < 0 && (m & 4111) === 4111) STRT[m] = 3;
4287
+ }
4288
+ for (let m = 1; m < 8192; m++) if (POPC[m] >= 5) FLUSHV[m] = STRT[m] >= 0 ? 8 << 20 | STRT[m] << 16 : 5 << 20 | top5(m);
4289
+ function rankEval(m1, m2, m3, m4) {
4290
+ if (m4) {
4291
+ const q = 31 - Math.clz32(m4);
4292
+ return 7 << 20 | q << 16 | 31 - Math.clz32(m1 & ~(1 << q)) << 12;
4293
+ }
4294
+ const pairs = m2 & ~m3;
4295
+ if (m3) {
4296
+ const t = 31 - Math.clz32(m3);
4297
+ const rest = m3 & ~(1 << t);
4298
+ if (rest) return 6 << 20 | t << 16 | 31 - Math.clz32(rest) << 12;
4299
+ if (pairs) return 6 << 20 | t << 16 | 31 - Math.clz32(pairs) << 12;
4300
+ const st2 = STRT[m1];
4301
+ if (st2 >= 0) return 4 << 20 | st2 << 16;
4302
+ let r = m1 & ~(1 << t);
4303
+ const k1 = 31 - Math.clz32(r);
4304
+ r &= ~(1 << k1);
4305
+ return 3 << 20 | t << 16 | k1 << 12 | 31 - Math.clz32(r) << 8;
4306
+ }
4307
+ const st = STRT[m1];
4308
+ if (st >= 0) return 4 << 20 | st << 16;
4309
+ if (pairs) {
4310
+ const p1 = 31 - Math.clz32(pairs);
4311
+ const rest = pairs & ~(1 << p1);
4312
+ if (rest) {
4313
+ const p2 = 31 - Math.clz32(rest);
4314
+ return 2 << 20 | p1 << 16 | p2 << 12 | 31 - Math.clz32(m1 & ~(1 << p1) & ~(1 << p2)) << 8;
4315
+ }
4316
+ let r = m1 & ~(1 << p1);
4317
+ const k1 = 31 - Math.clz32(r);
4318
+ r &= ~(1 << k1);
4319
+ const k2 = 31 - Math.clz32(r);
4320
+ r &= ~(1 << k2);
4321
+ return 1 << 20 | p1 << 16 | k1 << 12 | k2 << 8 | 31 - Math.clz32(r) << 4;
4322
+ }
4323
+ return top5(m1);
4324
+ }
4325
+ function eval7(c0, c1, c2, c3, c4, c5, c6) {
4326
+ const cs = [c0, c1, c2, c3, c4, c5, c6];
4327
+ const lane = [0, 0, 0, 0];
4328
+ let m1 = 0, m2 = 0, m3 = 0, m4 = 0;
4329
+ for (const c of cs) {
4330
+ const bit = 1 << (c >> 2);
4331
+ lane[c & 3] |= bit;
4332
+ if (m3 & bit) m4 |= bit;
4333
+ else if (m2 & bit) m3 |= bit;
4334
+ else if (m1 & bit) m2 |= bit;
4335
+ else m1 |= bit;
4336
+ }
4337
+ let v = rankEval(m1, m2, m3, m4);
4338
+ for (let s = 0; s < 4; s++) if (POPC[lane[s]] >= 5 && FLUSHV[lane[s]] > v) v = FLUSHV[lane[s]];
4339
+ return v;
4340
+ }
4341
+ function deckStates(flop, blankMask = 0) {
4342
+ if (flop.length > 3) {
4343
+ if (blankMask) throw new Error("blankSuits is only for a three-card flop");
4344
+ const base = flop.slice(0, 3), fixed = flop.slice(3), rivers2 = [];
4345
+ if (fixed.length === 2) rivers2.push([Math.min(fixed[0], fixed[1]), Math.max(fixed[0], fixed[1]), 1]);
4346
+ else for (let y = 0; y < 52; y++) if (!flop.includes(y)) rivers2.push([Math.min(fixed[0], y), Math.max(fixed[0], y), 1]);
4347
+ return { rivers: rivers2, turns: [], blankMask: 0, base, fixed };
4348
+ }
4349
+ const fm = new Set(flop);
4350
+ const blank = (s) => blankMask >> s & 1;
4351
+ const fc = [0, 0, 0, 0];
4352
+ flop.forEach((c) => fc[c & 3]++);
4353
+ const pri = [0, 1, 2, 3].filter(blank).sort((x, y) => fc[x] - fc[y] || x - y);
4354
+ const proxy = (card, dead) => {
4355
+ if (!blank(card & 3)) return card;
4356
+ for (const s of pri) {
4357
+ const c = card & ~3 | s;
4358
+ if (!dead.has(c)) return c;
4359
+ }
4360
+ throw new Error("no proxy");
4361
+ };
4362
+ const tw = /* @__PURE__ */ new Map();
4363
+ for (let x = 0; x < 52; x++) if (!fm.has(x)) {
4364
+ const t = proxy(x, fm);
4365
+ tw.set(t, (tw.get(t) || 0) + 1);
4366
+ }
4367
+ const rivers = [], rIdx = /* @__PURE__ */ new Map(), turns = [];
4368
+ for (const [t, wt] of tw) {
4369
+ const dead = new Set(flop);
4370
+ dead.add(t);
4371
+ const rw = /* @__PURE__ */ new Map();
4372
+ for (let y = 0; y < 52; y++) if (!dead.has(y)) {
4373
+ const u = proxy(y, dead);
4374
+ rw.set(u, (rw.get(u) || 0) + 1);
4375
+ }
4376
+ const rivs = [];
4377
+ for (const [u, wu] of rw) {
4378
+ const key = Math.min(t, u) * 52 + Math.max(t, u);
4379
+ if (!rIdx.has(key)) {
4380
+ rIdx.set(key, rivers.length);
4381
+ rivers.push([Math.min(t, u), Math.max(t, u), 0]);
4382
+ }
4383
+ const i = rIdx.get(key);
4384
+ rivers[i][2] += wt * wu;
4385
+ rivs.push([i, wu]);
4386
+ }
4387
+ turns.push({ card: t, w: wt, rivs });
4388
+ }
4389
+ return { rivers, turns, blankMask, base: flop, fixed: [] };
4390
+ }
4391
+ function dealtKey(st, k, p) {
4392
+ const r = st.rivers[k], fx = st.fixed;
4393
+ let a = -1, b = -1;
4394
+ for (let q = 0; q < 2; q++) {
4395
+ let c = r[q];
4396
+ if (fx.length && fx.includes(c)) continue;
4397
+ if (p) c = c & ~3 | p[c & 3];
4398
+ if (a < 0) a = c;
4399
+ else b = c;
4400
+ }
4401
+ return b < 0 ? a : a < b ? a * 52 + b + 52 : b * 52 + a + 52;
4402
+ }
4403
+ const DCAP = 91 + 64;
4404
+ function side(h, other, R, T, want) {
4405
+ const n = h.length;
4406
+ const o = /* @__PURE__ */ new Map();
4407
+ for (const x of other) o.set(hid(x), x.w);
4408
+ const s = {
4409
+ hands: h,
4410
+ n,
4411
+ want,
4412
+ ca: mk(Uint8Array, n),
4413
+ cb: mk(Uint8Array, n),
4414
+ cl: mk(Uint8Array, n),
4415
+ w: mk(Float64Array, n),
4416
+ same: mk(Float64Array, n),
4417
+ id: mk(Uint8Array, n),
4418
+ dd: mk(Uint8Array, n),
4419
+ start: mk(Int32Array, DCAP + 3),
4420
+ ord: mk(Int32Array, n),
4421
+ totC: mk(Float64Array, 52),
4422
+ tot: 0,
4423
+ E: want ? mk(Float32Array, R * n).fill(NaN) : null,
4424
+ fS: mk(Float64Array, n, true),
4425
+ fW: mk(Float64Array, n, true),
4426
+ tS: want ? mk(Float64Array, T * n, true) : null,
4427
+ tW: want ? mk(Float64Array, T * n, true) : null
4428
+ };
4429
+ for (let i = 0; i < n; i++) {
4430
+ const a = h[i].a, b = h[i].b;
4431
+ s.ca[i] = a;
4432
+ s.cb[i] = b;
4433
+ s.w[i] = h[i].w;
4434
+ s.same[i] = o.get(hid(h[i])) || 0;
4435
+ const r1 = a >> 2, r2 = b >> 2, hi = r1 > r2 ? r1 : r2, lo = r1 > r2 ? r2 : r1;
4436
+ s.cl[i] = hi * (hi + 1) / 2 + lo;
4437
+ }
4438
+ return s;
4439
+ }
4440
+ function equitiesBoth(hA, hB, flop, states, wantA = true, wantB = true, perms = null, only = null) {
4441
+ const R = states.rivers.length, T = states.turns.length;
4442
+ const S = [side(hA, hB, R, T, wantA), side(hB, hA, R, T, wantB)];
4443
+ const mir = [];
4444
+ if (perms && perms.length > 1) {
4445
+ const ridx = new Map(states.rivers.map((r, k) => [dealtKey(states, k), k]));
4446
+ for (const p of perms) {
4447
+ if (p[0] === 0 && p[1] === 1 && p[2] === 2 && p[3] === 3) continue;
4448
+ const bmap = mk(Int32Array, R);
4449
+ for (let k = 0; k < R; k++) bmap[k] = ridx.get(dealtKey(states, k, p));
4450
+ const hmap = S.map((s) => {
4451
+ const idx = new Map(s.hands.map((h, i) => [hid(h), i]));
4452
+ const out = mk(Int32Array, s.n);
4453
+ s.hands.forEach((h, i) => {
4454
+ let a = h.a & ~3 | p[h.a & 3], b = h.b & ~3 | p[h.b & 3];
4455
+ if (a > b) {
4456
+ const t = a;
4457
+ a = b;
4458
+ b = t;
4459
+ }
4460
+ out[i] = idx.get(a * 52 + b);
4461
+ });
4462
+ return out;
4463
+ });
4464
+ mir.push({ bmap, hmap });
4465
+ }
4466
+ }
4467
+ const done = mk(Uint8Array, R, true);
4468
+ if (only) for (let k = 0; k < R; k++) done[k] = only[k] ? 0 : 1;
4469
+ const present2 = mk(Uint8Array, 91, true);
4470
+ for (const s of S) for (let i = 0; i < s.n; i++) present2[s.cl[i]] = 1;
4471
+ const t1 = mk(Int32Array, R).fill(-1), t2 = mk(Int32Array, R).fill(-1), u1 = mk(Float64Array, R, true), u2 = mk(Float64Array, R, true);
4472
+ states.turns.forEach((t, ti) => {
4473
+ for (const [k, wu] of t.rivs) {
4474
+ if (t1[k] < 0) {
4475
+ t1[k] = ti;
4476
+ u1[k] = wu;
4477
+ } else {
4478
+ t2[k] = ti;
4479
+ u2[k] = wu;
4480
+ }
4481
+ }
4482
+ });
4483
+ const fl = [0, 0, 0, 0];
4484
+ let f1 = 0, f2 = 0, f3 = 0, f4 = 0;
4485
+ for (const c of states.base || flop) {
4486
+ const bit = 1 << (c >> 2);
4487
+ fl[c & 3] |= bit;
4488
+ if (f3 & bit) f4 |= bit;
4489
+ else if (f2 & bit) f3 |= bit;
4490
+ else if (f1 & bit) f2 |= bit;
4491
+ else f1 |= bit;
4492
+ }
4493
+ const cv = mk(Int32Array, 91), keys = mk(Float64Array, DCAP), denseOf = mk(Uint8Array, DCAP);
4494
+ const fStamp = mk(Int32Array, 8192).fill(-1), fSlot = mk(Uint8Array, 8192), lane = new Int32Array(4), ltC = mk(Float64Array, 52, true), eqC = mk(Float64Array, 52, true);
4495
+ if (arena && WK.ex.equityPass) {
4496
+ const rT = mk(Uint8Array, R), rR = mk(Uint8Array, R), rW = mk(Float64Array, R);
4497
+ for (let k = 0; k < R; k++) {
4498
+ rT[k] = states.rivers[k][0];
4499
+ rR[k] = states.rivers[k][1];
4500
+ rW[k] = states.rivers[k][2];
4501
+ }
4502
+ const sb = S.map((s) => {
4503
+ const tot = mk(Float64Array, 1), b = mk(Int32Array, 18);
4504
+ const o = (a) => a ? a.byteOffset : 0;
4505
+ b.set([s.n, s.want ? 1 : 0, o(s.ca), o(s.cb), o(s.cl), o(s.w), o(s.same), o(s.id), o(s.dd), o(s.start), o(s.ord), o(s.totC), o(s.E), o(s.fS), o(s.fW), o(s.tS), o(s.tW), o(tot)]);
4506
+ return b;
4507
+ });
4508
+ const mb = mk(Int32Array, Math.max(1, mir.length * 3));
4509
+ mir.forEach((x, q) => {
4510
+ mb[q * 3] = x.bmap.byteOffset;
4511
+ mb[q * 3 + 1] = x.hmap[0].byteOffset;
4512
+ mb[q * 3 + 2] = x.hmap[1].byteOffset;
4513
+ });
4514
+ const pb = mk(Int32Array, 32);
4515
+ pb.set([
4516
+ R,
4517
+ mir.length,
4518
+ rT.byteOffset,
4519
+ rR.byteOffset,
4520
+ rW.byteOffset,
4521
+ t1.byteOffset,
4522
+ t2.byteOffset,
4523
+ u1.byteOffset,
4524
+ u2.byteOffset,
4525
+ done.byteOffset,
4526
+ present2.byteOffset,
4527
+ cv.byteOffset,
4528
+ keys.byteOffset,
4529
+ denseOf.byteOffset,
4530
+ fStamp.byteOffset,
4531
+ fSlot.byteOffset,
4532
+ ltC.byteOffset,
4533
+ eqC.byteOffset,
4534
+ fl[0],
4535
+ fl[1],
4536
+ fl[2],
4537
+ fl[3],
4538
+ f1,
4539
+ f2,
4540
+ f3,
4541
+ f4,
4542
+ sb[0].byteOffset,
4543
+ sb[1].byteOffset,
4544
+ mb.byteOffset,
4545
+ WK.tab,
4546
+ WK.tab + 8192,
4547
+ WK.tab + 16384
4548
+ ]);
4549
+ WK.ex.equityPass(pb.byteOffset);
4550
+ } else for (let k = 0; k < R; k++) {
4551
+ if (done[k]) continue;
4552
+ const t = states.rivers[k][0], r = states.rivers[k][1], wgt = states.rivers[k][2];
4553
+ let m1 = f1, m2 = f2, m3 = f3, m4 = f4;
4554
+ lane[0] = fl[0];
4555
+ lane[1] = fl[1];
4556
+ lane[2] = fl[2];
4557
+ lane[3] = fl[3];
4558
+ let bit = 1 << (t >> 2);
4559
+ lane[t & 3] |= bit;
4560
+ if (m3 & bit) m4 |= bit;
4561
+ else if (m2 & bit) m3 |= bit;
4562
+ else if (m1 & bit) m2 |= bit;
4563
+ else m1 |= bit;
4564
+ bit = 1 << (r >> 2);
4565
+ lane[r & 3] |= bit;
4566
+ if (m3 & bit) m4 |= bit;
4567
+ else if (m2 & bit) m3 |= bit;
4568
+ else if (m1 & bit) m2 |= bit;
4569
+ else m1 |= bit;
4570
+ let c = 0, nk = 0;
4571
+ for (let hi = 0; hi < 13; hi++) {
4572
+ const bh = 1 << hi;
4573
+ let a1 = m1, a2 = m2, a3 = m3, a4 = m4;
4574
+ if (a3 & bh) a4 |= bh;
4575
+ else if (a2 & bh) a3 |= bh;
4576
+ else if (a1 & bh) a2 |= bh;
4577
+ else a1 |= bh;
4578
+ for (let lo = 0; lo <= hi; lo++) {
4579
+ const bl = 1 << lo;
4580
+ let b1 = a1, b2 = a2, b3 = a3, b4 = a4;
4581
+ if (b3 & bl) b4 |= bl;
4582
+ else if (b2 & bl) b3 |= bl;
4583
+ else if (b1 & bl) b2 |= bl;
4584
+ else b1 |= bl;
4585
+ if (!present2[c]) {
4586
+ c++;
4587
+ continue;
4588
+ }
4589
+ const v = rankEval(b1, b2, b3, b4);
4590
+ cv[c] = v;
4591
+ keys[nk++] = v * 256 + c;
4592
+ c++;
4593
+ }
4594
+ }
4595
+ let F = -1, need = 9, fLane = 0;
4596
+ for (let s = 0; s < 4; s++) if (POPC[lane[s]] >= 3) {
4597
+ F = s;
4598
+ fLane = lane[s];
4599
+ need = 5 - POPC[lane[s]];
4600
+ }
4601
+ let slot = 91;
4602
+ for (let p = 0; p < 2; p++) {
4603
+ const s = S[p], n = s.n, ca = s.ca, cb = s.cb, cl = s.cl, id = s.id;
4604
+ if (F < 0) {
4605
+ for (let i = 0; i < n; i++) {
4606
+ const a = ca[i], b = cb[i];
4607
+ id[i] = a === t || a === r || b === t || b === r ? 255 : cl[i];
4608
+ }
4609
+ } else {
4610
+ for (let i = 0; i < n; i++) {
4611
+ const a = ca[i], b = cb[i];
4612
+ if (a === t || a === r || b === t || b === r) {
4613
+ id[i] = 255;
4614
+ continue;
4615
+ }
4616
+ let cnt = 0, mk2 = fLane;
4617
+ if ((a & 3) === F) {
4618
+ cnt++;
4619
+ mk2 |= 1 << (a >> 2);
4620
+ }
4621
+ if ((b & 3) === F) {
4622
+ cnt++;
4623
+ mk2 |= 1 << (b >> 2);
4624
+ }
4625
+ if (cnt >= need) {
4626
+ const fv = FLUSHV[mk2];
4627
+ if (fv > cv[cl[i]]) {
4628
+ if (fStamp[mk2] !== k) {
4629
+ fStamp[mk2] = k;
4630
+ fSlot[mk2] = slot;
4631
+ keys[nk++] = fv * 256 + slot;
4632
+ slot++;
4633
+ }
4634
+ id[i] = fSlot[mk2];
4635
+ continue;
4636
+ }
4637
+ }
4638
+ id[i] = cl[i];
4639
+ }
4640
+ }
4641
+ }
4642
+ const ks = nk === DCAP ? keys : keys.subarray(0, nk);
4643
+ ks.sort();
4644
+ let D = -1, prev = -1;
4645
+ for (let q = 0; q < nk; q++) {
4646
+ const key = ks[q];
4647
+ const v = key / 256 >>> 0;
4648
+ if (v !== prev) {
4649
+ D++;
4650
+ prev = v;
4651
+ }
4652
+ denseOf[key - v * 256] = D;
4653
+ }
4654
+ D++;
4655
+ for (let p = 0; p < 2; p++) {
4656
+ const s = S[p], n = s.n, ca = s.ca, cb = s.cb, id = s.id, dd = s.dd, w = s.w, totC = s.totC, start = s.start, ord = s.ord;
4657
+ start.fill(0, 0, D + 2);
4658
+ totC.fill(0);
4659
+ let tot = 0;
4660
+ for (let i = 0; i < n; i++) {
4661
+ const x = id[i];
4662
+ if (x === 255) continue;
4663
+ const d = denseOf[x];
4664
+ dd[i] = d;
4665
+ start[d + 2]++;
4666
+ const wi = w[i];
4667
+ totC[ca[i]] += wi;
4668
+ totC[cb[i]] += wi;
4669
+ tot += wi;
4670
+ }
4671
+ for (let d = 2; d <= D + 1; d++) start[d] += start[d - 1];
4672
+ for (let i = 0; i < n; i++) {
4673
+ if (id[i] === 255) continue;
4674
+ ord[start[dd[i] + 1]++] = i;
4675
+ }
4676
+ s.tot = tot;
4677
+ }
4678
+ const ta = t1[k], tb = t2[k], wa = u1[k], wb = u2[k];
4679
+ for (let p = 0; p < 2; p++) {
4680
+ const s = S[p];
4681
+ if (!s.want) continue;
4682
+ const v = S[1 - p];
4683
+ const n = s.n, ca = s.ca, cb = s.cb, same = s.same, E = s.E, fS = s.fS, fW = s.fW, tS = s.tS, tW = s.tW, hs = s.start, ho = s.ord;
4684
+ const va = v.ca, vb = v.cb, vw = v.w, vs = v.start, vo = v.ord, totC = v.totC, tot = v.tot;
4685
+ const base = k * n, oa = ta * n, ob = tb * n;
4686
+ ltC.fill(0);
4687
+ let ltT = 0;
4688
+ for (let d = 0; d < D; d++) {
4689
+ const v0 = vs[d], v1 = vs[d + 1], h0 = hs[d], h1 = hs[d + 1];
4690
+ let eqT = 0;
4691
+ if (h0 < h1) {
4692
+ for (let q = v0; q < v1; q++) {
4693
+ const j = vo[q], wj = vw[j];
4694
+ eqC[va[j]] += wj;
4695
+ eqC[vb[j]] += wj;
4696
+ eqT += wj;
4697
+ }
4698
+ for (let q = h0; q < h1; q++) {
4699
+ const i = ho[q], a = ca[i], b = cb[i], sw = same[i];
4700
+ const all = tot - totC[a] - totC[b] + sw;
4701
+ const e = all > 1e-12 ? (ltT - ltC[a] - ltC[b] + 0.5 * (eqT - eqC[a] - eqC[b] + sw)) / all : 0.5;
4702
+ E[base + i] = e;
4703
+ fS[i] += wgt * e;
4704
+ fW[i] += wgt;
4705
+ if (ta >= 0) {
4706
+ tS[oa + i] += wa * e;
4707
+ tW[oa + i] += wa;
4708
+ }
4709
+ if (tb >= 0) {
4710
+ tS[ob + i] += wb * e;
4711
+ tW[ob + i] += wb;
4712
+ }
4713
+ }
4714
+ for (let q = v0; q < v1; q++) {
4715
+ const j = vo[q], wj = vw[j];
4716
+ const a = va[j], b = vb[j];
4717
+ ltC[a] += wj;
4718
+ ltC[b] += wj;
4719
+ eqC[a] = 0;
4720
+ eqC[b] = 0;
4721
+ }
4722
+ ltT += eqT;
4723
+ } else {
4724
+ for (let q = v0; q < v1; q++) {
4725
+ const j = vo[q], wj = vw[j];
4726
+ ltC[va[j]] += wj;
4727
+ ltC[vb[j]] += wj;
4728
+ ltT += wj;
4729
+ }
4730
+ }
4731
+ }
4732
+ }
4733
+ for (let q = 0; q < mir.length; q++) {
4734
+ const k2 = mir[q].bmap[k];
4735
+ if (k2 === k || done[k2]) continue;
4736
+ done[k2] = 1;
4737
+ const w2 = states.rivers[k2][2], ta2 = t1[k2], tb2 = t2[k2], wa2 = u1[k2], wb2 = u2[k2];
4738
+ for (let p = 0; p < 2; p++) {
4739
+ const s = S[p];
4740
+ if (!s.want) continue;
4741
+ const n = s.n, id = s.id, E = s.E, hm = mir[q].hmap[p], fS = s.fS, fW = s.fW, tS = s.tS, tW = s.tW;
4742
+ const b1 = k * n, b2 = k2 * n, oa = ta2 * n, ob = tb2 * n;
4743
+ for (let i = 0; i < n; i++) {
4744
+ if (id[i] === 255) continue;
4745
+ const e = E[b1 + i], j = hm[i];
4746
+ E[b2 + j] = e;
4747
+ fS[j] += w2 * e;
4748
+ fW[j] += w2;
4749
+ if (ta2 >= 0) {
4750
+ tS[oa + j] += wa2 * e;
4751
+ tW[oa + j] += wa2;
4752
+ }
4753
+ if (tb2 >= 0) {
4754
+ tS[ob + j] += wb2 * e;
4755
+ tW[ob + j] += wb2;
4756
+ }
4757
+ }
4758
+ }
4759
+ }
4760
+ }
4761
+ return S.map((s) => {
4762
+ if (!s.want) return null;
4763
+ const n = s.n;
4764
+ const ef = mk(Float32Array, n), et = mk(Float32Array, T * n);
4765
+ for (let i = 0; i < n; i++) ef[i] = s.fW[i] ? s.fS[i] / s.fW[i] : 0.5;
4766
+ for (let q = 0; q < T * n; q++) et[q] = s.tW[q] ? s.tS[q] / s.tW[q] : NaN;
4767
+ return { E: s.E, ef, et, fS: s.fS, fW: s.fW, tS: s.tS, tW: s.tW };
4768
+ });
4769
+ }
4770
+ const ALL_PERMS = (() => {
4771
+ const out = [];
4772
+ const rec = (a, rest) => {
4773
+ if (!rest.length) return out.push(a);
4774
+ rest.forEach((x, i) => rec(a.concat(x), rest.filter((_, j) => j !== i)));
4775
+ };
4776
+ rec([], [0, 1, 2, 3]);
4777
+ return out;
4778
+ })();
4779
+ function flopPerms(flop) {
4780
+ const key = (cs) => cs.slice().sort((x, y) => x - y).join(",");
4781
+ const k0 = key(flop);
4782
+ return ALL_PERMS.filter((p) => key(flop.map((c) => c & ~3 | p[c & 3])) === k0);
4783
+ }
4784
+ function orbits(hero, flop, symmetric) {
4785
+ const perms = symmetric ? flopPerms(flop) : [[0, 1, 2, 3]];
4786
+ const idx = new Map(hero.map((h, i) => [hid(h), i]));
4787
+ const orb = new Int32Array(hero.length).fill(-1);
4788
+ const list = [];
4789
+ hero.forEach((h, i) => {
4790
+ if (orb[i] >= 0) return;
4791
+ const o = list.length, mem = [];
4792
+ for (const p of perms) {
4793
+ let a = h.a & ~3 | p[h.a & 3], b = h.b & ~3 | p[h.b & 3];
4794
+ if (a > b) {
4795
+ const t = a;
4796
+ a = b;
4797
+ b = t;
4798
+ }
4799
+ const j = idx.get(a * 52 + b);
4800
+ if (j !== void 0 && orb[j] < 0) {
4801
+ orb[j] = o;
4802
+ mem.push(j);
4803
+ }
4804
+ }
4805
+ list.push(mem);
4806
+ });
4807
+ return { orb, list, perms };
4808
+ }
4809
+ function isSymmetric(hands, perms) {
4810
+ const idx = new Map(hands.map((h) => [hid(h), h.w]));
4811
+ for (const p of perms) for (const h of hands) {
4812
+ let a = h.a & ~3 | p[h.a & 3], b = h.b & ~3 | p[h.b & 3];
4813
+ if (a > b) {
4814
+ const t = a;
4815
+ a = b;
4816
+ b = t;
4817
+ }
4818
+ const w = idx.get(a * 52 + b);
4819
+ if (w === void 0 || Math.abs(w - h.w) > 1e-9) return false;
4820
+ }
4821
+ return true;
4822
+ }
4823
+ function prepareBoth(hA, hB, flop, states, wantA = true, wantB = true, only = null) {
4824
+ states = states || deckStates(flop, 0);
4825
+ const perms = states.blankMask ? [[0, 1, 2, 3]] : flopPerms(flop);
4826
+ const sym = perms.length > 1 && isSymmetric(hA, perms) && isSymmetric(hB, perms);
4827
+ const eq = equitiesBoth(hA, hB, flop, states, wantA, wantB, sym ? perms : null, only);
4828
+ const one = (h, e, v) => e && { hero: h, villain: v, flop, states, n: h.length, R: states.rivers.length, E: e.E, ef: e.ef, et: e.et, boardSym: sym, perms, sums: e };
4829
+ return [one(hA, eq[0], hB), one(hB, eq[1], hA)];
4830
+ }
4831
+ let lastPair = null;
4832
+ function prepare(hero, villain, flop, states) {
4833
+ states = states || deckStates(flop, 0);
4834
+ if (lastPair && lastPair.states === states && lastPair.a === villain && lastPair.b === hero) return lastPair.res[1];
4835
+ const res = prepareBoth(hero, villain, flop, states);
4836
+ lastPair = { a: hero, b: villain, states, res };
4837
+ return res[0];
4838
+ }
4839
+ function distances(P) {
4840
+ if (P.D) return P.D;
4841
+ const { n, R, E, states } = P;
4842
+ const D = new Float32Array(n * n), S2 = new Float64Array(n * n), C2 = new Float64Array(n * n);
4843
+ const live = new Int32Array(n), ev = new Float64Array(n);
4844
+ for (let k = 0; k < R; k++) {
4845
+ const w = states.rivers[k][2], base = k * n;
4846
+ let c = 0;
4847
+ for (let i = 0; i < n; i++) {
4848
+ const e = E[base + i];
4849
+ if (e === e) {
4850
+ live[c] = i;
4851
+ ev[c] = e;
4852
+ c++;
4853
+ }
4854
+ }
4855
+ for (let p = 0; p < c; p++) {
4856
+ const row = live[p] * n, ep = ev[p];
4857
+ for (let q = p + 1; q < c; q++) {
4858
+ const d = ep - ev[q];
4859
+ S2[row + live[q]] += w * d * d;
4860
+ C2[row + live[q]] += w;
4861
+ }
4862
+ }
4863
+ }
4864
+ for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
4865
+ const c = C2[i * n + j];
4866
+ D[i * n + j] = D[j * n + i] = c ? Math.sqrt(S2[i * n + j] / c) : 1;
4867
+ }
4868
+ return P.D = D;
4869
+ }
4870
+ function walker(P, opts = {}) {
4871
+ const B = opts.bins || 16, sw = opts.streetWeights || [1, 1, 1];
4872
+ const symmetric = opts.symmetric !== false && !P.states.blankMask;
4873
+ const rsOpt = opts.riverSample || 1;
4874
+ const key = B + "|" + sw.join(",") + "|" + symmetric + "|" + rsOpt;
4875
+ if (P.walkKey === key) return P.walk;
4876
+ const { hero, flop, n, R, states } = P;
4877
+ const ob = orbits(hero, flop, symmetric);
4878
+ const list = [["ef", 0, sw[0]]];
4879
+ const tw = states.turns.reduce((s, t) => s + t.w, 0);
4880
+ states.turns.forEach((t, ti) => list.push(["et", ti * n, sw[1] * t.w / tw]));
4881
+ const rws = [], rks = [];
4882
+ const mirrored = symmetric && P.boardSym && ob.perms.length > 1;
4883
+ const done = new Uint8Array(R), ridx = mirrored ? new Map(states.rivers.map((r, k) => [dealtKey(states, k), k])) : null, repQ = new Int32Array(R);
4884
+ for (let k = 0; k < R; k++) {
4885
+ if (done[k]) continue;
4886
+ let wsum = states.rivers[k][2];
4887
+ repQ[k] = rks.length;
4888
+ if (mirrored) {
4889
+ wsum = 0;
4890
+ for (const p of ob.perms) {
4891
+ const j = ridx.get(dealtKey(states, k, p));
4892
+ if (!done[j]) {
4893
+ done[j] = 1;
4894
+ repQ[j] = rks.length;
4895
+ wsum += states.rivers[j][2];
4896
+ }
4897
+ }
4898
+ }
4899
+ rks.push(k);
4900
+ rws.push(wsum);
4901
+ }
4902
+ const rs = rsOpt === "auto" ? Math.max(1, Math.min(3, Math.floor(rks.length / 300))) : rsOpt;
4903
+ let rw = 0;
4904
+ const use = [];
4905
+ for (let q = 0; q < rks.length; q++) if (q % rs === 0) {
4906
+ use.push(q);
4907
+ rw += rws[q];
4908
+ }
4909
+ const rivers = use.map((q) => ["E", rks[q] * n, sw[2] * rws[q] / rw, q]);
4910
+ P.walkKey = key;
4911
+ P.gramKey = null;
4912
+ P.walk = { key, B, ob, m: ob.list.length, fixed: list, rivers, sets: rks.length, repQ };
4913
+ return P.walk;
4914
+ }
4915
+ function fillBins(arr, off, order, cnt, keyOf, B, n, binK, binV, binN) {
4916
+ const Bm1 = B - 1, Bm2 = B - 2;
4917
+ binN.fill(0);
4918
+ for (let q = 0; q < cnt; q++) {
4919
+ const i = order[q];
4920
+ const e = arr[off + i];
4921
+ if (e !== e) continue;
4922
+ const o = keyOf[i];
4923
+ const x = (e < 0 ? 0 : e > 1 ? 1 : e) * Bm1;
4924
+ let b0 = x | 0;
4925
+ if (b0 > Bm2) b0 = Bm2;
4926
+ const f = x - b0;
4927
+ if (f < 1) {
4928
+ const base = b0 * n, c = binN[b0];
4929
+ if (c && binK[base + c - 1] === o) binV[base + c - 1] += 1 - f;
4930
+ else {
4931
+ binK[base + c] = o;
4932
+ binV[base + c] = 1 - f;
4933
+ binN[b0] = c + 1;
4934
+ }
4935
+ }
4936
+ if (f > 0) {
4937
+ const b1 = b0 + 1, base = b1 * n, c = binN[b1];
4938
+ if (c && binK[base + c - 1] === o) binV[base + c - 1] += f;
4939
+ else {
4940
+ binK[base + c] = o;
4941
+ binV[base + c] = f;
4942
+ binN[b1] = c + 1;
4943
+ }
4944
+ }
4945
+ }
4946
+ }
4947
+ function addPairs(U, diag, stride, binK, binV, from, to, lam) {
4948
+ for (let p = from; p < to; p++) {
4949
+ const op = binK[p], v = binV[p], vp = v * lam, row = op * stride;
4950
+ diag[op] += vp * v;
4951
+ let q = p + 1;
4952
+ for (const e = to - 3; q < e; q += 4) {
4953
+ U[row + binK[q]] += vp * binV[q];
4954
+ U[row + binK[q + 1]] += vp * binV[q + 1];
4955
+ U[row + binK[q + 2]] += vp * binV[q + 2];
4956
+ U[row + binK[q + 3]] += vp * binV[q + 3];
4957
+ }
4958
+ for (; q < to; q++) U[row + binK[q]] += vp * binV[q];
4959
+ }
4960
+ }
4961
+ const symmetrize = (U, diag, m) => {
4962
+ for (let a = 0; a < m; a++) {
4963
+ U[a * m + a] = diag[a] + 2 * U[a * m + a];
4964
+ for (let b = a + 1; b < m; b++) {
4965
+ const v = U[a * m + b] + U[b * m + a];
4966
+ U[a * m + b] = v;
4967
+ U[b * m + a] = v;
4968
+ }
4969
+ }
4970
+ return U;
4971
+ };
4972
+ function accumulate(P, W, entries, U, diag) {
4973
+ const { n } = P, { B, ob, m } = W, orb = ob.orb;
4974
+ const order = mk(Int32Array, n);
4975
+ {
4976
+ let c = 0;
4977
+ for (const mem of ob.list) for (const i of mem) order[c++] = i;
4978
+ }
4979
+ U = U || mk(Float64Array, m * m, true);
4980
+ diag = diag || mk(Float64Array, m, true);
4981
+ const binK = mk(Int32Array, B * n), binV = mk(Float64Array, B * n), binN = mk(Int32Array, B);
4982
+ const src = (e) => P[e[0]];
4983
+ if (entries.length && inW(U) && entries.every((e) => inW(src(e)))) {
4984
+ const key = mk(Int32Array, n);
4985
+ key.set(orb);
4986
+ const ex = WK.ex;
4987
+ for (const e of entries) ex.addState(src(e).byteOffset + e[1] * 4, order.byteOffset, n, key.byteOffset, B, n, binK.byteOffset, binV.byteOffset, binN.byteOffset, U.byteOffset, diag.byteOffset, m, e[2]);
4988
+ } else for (const e of entries) {
4989
+ fillBins(src(e), e[1], order, n, orb, B, n, binK, binV, binN);
4990
+ for (let b = 0; b < B; b++) addPairs(U, diag, m, binK, binV, b * n, b * n + binN[b], e[2]);
4991
+ }
4992
+ return { U, diag };
4993
+ }
4994
+ function gram(P, opts = {}) {
4995
+ const W = walker(P, opts);
4996
+ if (P.gramKey === W.key) return P.gramRes;
4997
+ const a = accumulate(P, W, W.fixed.concat(W.rivers));
4998
+ const Go = symmetrize(a.U, a.diag, W.m);
4999
+ if (P.states.fixed && P.states.fixed.length === 2 && P.villain) addOpponentSide(P, W, Go);
5000
+ P.gramKey = W.key;
5001
+ P.gramRes = { Go, ob: W.ob, m: W.m };
5002
+ return P.gramRes;
5003
+ }
5004
+ function addOpponentSide(P, W, Go) {
5005
+ const { hero, villain, n } = P, bd = P.states.base.concat(P.states.fixed), m = W.m, orb = W.ob.orb, nv = villain.length;
5006
+ const hv = hero.map((h) => eval7(h.a, h.b, bd[0], bd[1], bd[2], bd[3], bd[4])), vv = villain.map((h) => eval7(h.a, h.b, bd[0], bd[1], bd[2], bd[3], bd[4]));
5007
+ const vals = Array.from(new Set(hv.concat(vv))).sort((x, y) => x - y), rank = new Map(vals.map((v, d) => [v, d])), D = vals.length, D1 = D + 1;
5008
+ const cumT = new Float64Array(D1), cumC = new Float64Array(52 * D1), at = new Int32Array(52 * 52).fill(-1), vr = new Int32Array(nv), vw = new Float64Array(nv);
5009
+ let vt = 0;
5010
+ for (const v of villain) vt += v.w;
5011
+ if (!(vt > 0)) return;
5012
+ villain.forEach((v, j) => {
5013
+ const d = rank.get(vv[j]), w = v.w / vt;
5014
+ vr[j] = d;
5015
+ vw[j] = w;
5016
+ cumT[d + 1] += w;
5017
+ cumC[v.a * D1 + d + 1] += w;
5018
+ cumC[v.b * D1 + d + 1] += w;
5019
+ at[v.a * 52 + v.b] = j;
5020
+ at[v.b * 52 + v.a] = j;
5021
+ });
5022
+ for (let d = 1; d <= D; d++) cumT[d] += cumT[d - 1];
5023
+ for (let c = 0; c < 52; c++) {
5024
+ const o = c * D1;
5025
+ for (let d = 1; d <= D; d++) cumC[o + d] += cumC[o + d - 1];
5026
+ }
5027
+ const hr = Int32Array.from(hv, (v) => rank.get(v)), Gv = new Float64Array(m * m), U = [0, 0, 0, 0];
5028
+ for (let i = 0; i < n; i++) {
5029
+ const a = hero[i].a, b = hero[i].b, ri = hr[i], oi = orb[i];
5030
+ for (let j = i; j < n; j++) {
5031
+ const a2 = hero[j].a, b2 = hero[j].b, rj = hr[j], x = ri < rj ? ri : rj, y = ri < rj ? rj : ri, tie = x === y;
5032
+ let nu = 2;
5033
+ U[0] = a;
5034
+ U[1] = b;
5035
+ if (a2 !== a && a2 !== b) U[nu++] = a2;
5036
+ if (b2 !== a && b2 !== b) U[nu++] = b2;
5037
+ let g = cumT[x] + cumT[D] - cumT[y + 1] + (tie ? cumT[x + 1] - cumT[x] : 0);
5038
+ for (let q = 0; q < nu; q++) {
5039
+ const o = U[q] * D1;
5040
+ g -= cumC[o + x] + cumC[o + D] - cumC[o + y + 1] + (tie ? cumC[o + x + 1] - cumC[o + x] : 0);
5041
+ for (let r = q + 1; r < nu; r++) {
5042
+ const k = at[U[q] * 52 + U[r]];
5043
+ if (k >= 0) {
5044
+ const d = vr[k];
5045
+ if (d < x || d > y || tie && d === x) g += vw[k];
5046
+ }
5047
+ }
5048
+ }
5049
+ Gv[oi * m + orb[j]] += g;
5050
+ if (j !== i) Gv[orb[j] * m + oi] += g;
5051
+ }
5052
+ }
5053
+ const w0 = new Float64Array(m);
5054
+ W.ob.list.forEach((mem, o) => {
5055
+ let t = 0;
5056
+ for (const i of mem) t += hero[i].w;
5057
+ w0[o] = t / mem.length;
5058
+ });
5059
+ const quad = (M) => {
5060
+ let t = 0;
5061
+ for (let x = 0; x < m; x++) {
5062
+ let r = 0;
5063
+ const o = x * m;
5064
+ for (let y = 0; y < m; y++) r += M[o + y] * w0[y];
5065
+ t += w0[x] * r;
5066
+ }
5067
+ return t;
5068
+ };
5069
+ const cv = quad(Gv), ch = quad(Go);
5070
+ if (!(cv > 0) || !(ch > 0)) return;
5071
+ for (let q = 0; q < m * m; q++) Go[q] = Go[q] / ch + Gv[q] / cv;
5072
+ }
5073
+ function invertSPD(A, m) {
5074
+ const L = new Float64Array(m * m);
5075
+ for (let i = 0; i < m; i++) {
5076
+ const ri = i * m;
5077
+ for (let j = 0; j <= i; j++) {
5078
+ const rj = j * m;
5079
+ let s0 = A[ri + j], s1 = 0, s2 = 0, s3 = 0, k = 0;
5080
+ for (const e = j - 3; k < e; k += 4) {
5081
+ s0 -= L[ri + k] * L[rj + k];
5082
+ s1 -= L[ri + k + 1] * L[rj + k + 1];
5083
+ s2 -= L[ri + k + 2] * L[rj + k + 2];
5084
+ s3 -= L[ri + k + 3] * L[rj + k + 3];
5085
+ }
5086
+ for (; k < j; k++) s0 -= L[ri + k] * L[rj + k];
5087
+ const s = s0 + s1 + s2 + s3;
5088
+ L[ri + j] = i === j ? Math.sqrt(s > 0 ? s : 1e-300) : s / L[rj + j];
5089
+ }
5090
+ }
5091
+ const X = new Float64Array(m * m);
5092
+ for (let i = 0; i < m; i++) {
5093
+ const ri = i * m, d = 1 / L[ri + i];
5094
+ for (let k = 0; k < i; k++) {
5095
+ const f = L[ri + k];
5096
+ if (!f) continue;
5097
+ const rk = k * m;
5098
+ let j = 0;
5099
+ for (const e = k - 2; j < e; j += 4) {
5100
+ X[ri + j] -= f * X[rk + j];
5101
+ X[ri + j + 1] -= f * X[rk + j + 1];
5102
+ X[ri + j + 2] -= f * X[rk + j + 2];
5103
+ X[ri + j + 3] -= f * X[rk + j + 3];
5104
+ }
5105
+ for (; j <= k; j++) X[ri + j] -= f * X[rk + j];
5106
+ }
5107
+ for (let j = 0; j < i; j++) X[ri + j] *= d;
5108
+ X[ri + i] = d;
5109
+ }
5110
+ const Pm = L.fill(0);
5111
+ for (let k = 0; k < m; k++) {
5112
+ const rk = k * m;
5113
+ for (let a = 0; a <= k; a++) {
5114
+ const xa = X[rk + a];
5115
+ if (!xa) continue;
5116
+ const ra = a * m;
5117
+ let b = 0;
5118
+ for (const e = a - 2; b < e; b += 4) {
5119
+ Pm[ra + b] += xa * X[rk + b];
5120
+ Pm[ra + b + 1] += xa * X[rk + b + 1];
5121
+ Pm[ra + b + 2] += xa * X[rk + b + 2];
5122
+ Pm[ra + b + 3] += xa * X[rk + b + 3];
5123
+ }
5124
+ for (; b <= a; b++) Pm[ra + b] += xa * X[rk + b];
5125
+ }
5126
+ }
5127
+ return Pm;
5128
+ }
5129
+ function obsState(M, dim, idx, eps, w0, bvec) {
5130
+ const k = idx.length, A = mk(Float64Array, k * k);
5131
+ for (let q = 0; q < k; q++) {
5132
+ const o = idx[q] * dim, r = q * k;
5133
+ for (let p = 0; p <= q; p++) A[r + p] = M[o + idx[p]];
5134
+ A[r + q] += eps;
5135
+ }
5136
+ let Pm;
5137
+ if (arena) {
5138
+ Pm = mk(Float64Array, k * k);
5139
+ const X = mk(Float64Array, k * k);
5140
+ WK.ex.invertSPD(A.byteOffset, Pm.byteOffset, X.byteOffset, k);
5141
+ } else Pm = invertSPD(A, k);
5142
+ const wp = mk(Float64Array, k);
5143
+ if (w0) for (let q = 0; q < k; q++) wp[q] = w0[idx[q]];
5144
+ else for (let q = 0; q < k; q++) {
5145
+ let s = 0;
5146
+ const r = q * k;
5147
+ for (let p = 0; p <= q; p++) s += Pm[r + p] * bvec[idx[p]];
5148
+ for (let p = q + 1; p < k; p++) s += Pm[p * k + q] * bvec[idx[p]];
5149
+ wp[q] = s;
5150
+ }
5151
+ const act = mk(Int32Array, k);
5152
+ act.set(idx);
5153
+ return { Pm, k, na: k, act, wp, col: mk(Float64Array, k), sal: 0, w: arena, salp: arena ? mk(Float64Array, 1) : null };
5154
+ }
5155
+ function obsPick(st, skip) {
5156
+ const { Pm, k, na, wp, act } = st;
5157
+ if (st.w && !skip) {
5158
+ const q = WK.ex.obsPick(Pm.byteOffset, k, na, wp.byteOffset, st.salp.byteOffset);
5159
+ st.sal = st.salp[0];
5160
+ return q;
5161
+ }
5162
+ let bq = -1, bs = Infinity, sal = 0;
5163
+ for (let q = 0; q < na; q++) {
5164
+ if (skip && skip(act[q])) continue;
5165
+ const wj = wp[q], cost = wj * wj / Pm[q * k + q], s = wj < 0 ? -1e30 + wj : cost;
5166
+ if (s < bs) {
5167
+ bs = s;
5168
+ bq = q;
5169
+ sal = cost;
5170
+ }
5171
+ }
5172
+ st.sal = sal;
5173
+ return bq;
5174
+ }
5175
+ function obsRemove(st, bq) {
5176
+ const { Pm, k, wp, act, col } = st;
5177
+ let na = st.na;
5178
+ if (st.w) {
5179
+ const id = WK.ex.obsRemove(Pm.byteOffset, k, na, wp.byteOffset, act.byteOffset, col.byteOffset, bq);
5180
+ st.na = na - 1;
5181
+ return id;
5182
+ }
5183
+ const bj = act[bq];
5184
+ const rb = bq * k;
5185
+ for (let q = 0; q <= bq; q++) col[q] = Pm[rb + q];
5186
+ for (let q = bq + 1; q < na; q++) col[q] = Pm[q * k + bq];
5187
+ const pj = col[bq], f = wp[bq] / pj, inv = 1 / pj, last = na - 1;
5188
+ if (bq !== last) {
5189
+ const rl = last * k;
5190
+ for (let q = 0; q < bq; q++) Pm[rb + q] = Pm[rl + q];
5191
+ for (let q = bq + 1; q < last; q++) Pm[q * k + bq] = Pm[rl + q];
5192
+ Pm[rb + bq] = Pm[rl + last];
5193
+ col[bq] = col[last];
5194
+ wp[bq] = wp[last];
5195
+ act[bq] = act[last];
5196
+ }
5197
+ na = last;
5198
+ for (let q = 0; q < na; q++) {
5199
+ const ci = col[q];
5200
+ wp[q] -= f * ci;
5201
+ const s = ci * inv;
5202
+ if (!s) continue;
5203
+ const row = q * k;
5204
+ let p = 0;
5205
+ for (const e = q - 2; p < e; p += 4) {
5206
+ Pm[row + p] -= s * col[p];
5207
+ Pm[row + p + 1] -= s * col[p + 1];
5208
+ Pm[row + p + 2] -= s * col[p + 2];
5209
+ Pm[row + p + 3] -= s * col[p + 3];
5210
+ }
5211
+ for (; p <= q; p++) Pm[row + p] -= s * col[p];
5212
+ }
5213
+ st.na = na;
5214
+ return bj;
5215
+ }
5216
+ function eliminate(P, opts = {}) {
5217
+ const T = opts.timing, now = T ? () => Number(process.hrtime.bigint()) / 1e6 : null;
5218
+ let t0 = T ? now() : 0;
5219
+ const lap = (k) => {
5220
+ if (T) {
5221
+ const t = now();
5222
+ T[k] = (T[k] || 0) + t - t0;
5223
+ t0 = t;
5224
+ }
5225
+ };
5226
+ const { hero } = P;
5227
+ const W = walker(P, opts), ob = W.ob, m = W.m;
5228
+ const osize = new Int32Array(m);
5229
+ ob.list.forEach((mem, o) => {
5230
+ osize[o] = mem.length;
5231
+ });
5232
+ const w0 = new Float64Array(m);
5233
+ ob.list.forEach((mem, o) => {
5234
+ let s = 0;
5235
+ for (const i of mem) s += hero[i].w;
5236
+ w0[o] = s / mem.length;
5237
+ });
5238
+ const targets = (opts.sizes || []).slice().sort((a, b) => b - a);
5239
+ const tol = opts.tolerance;
5240
+ let hands = hero.length, cum = 0;
5241
+ const path = [], curve = [];
5242
+ let Go = gram(P, opts).Go;
5243
+ const ocls = ob.list.map((mem) => cls(hero[mem[0]]));
5244
+ if (opts.classMu) {
5245
+ Go = Float64Array.from(Go);
5246
+ for (let i = 0; i < m; i++) for (let j = 0; j < m; j++) if (ocls[i] === ocls[j]) Go[i * m + j] += opts.classMu * osize[i] * osize[j];
5247
+ }
5248
+ let clsCount = null, skip = null;
5249
+ if (opts.keepClasses) {
5250
+ clsCount = /* @__PURE__ */ new Map();
5251
+ ocls.forEach((c) => clsCount.set(c, (clsCount.get(c) || 0) + 1));
5252
+ skip = (o) => clsCount.get(ocls[o]) <= 1;
5253
+ }
5254
+ let tr = 0;
5255
+ for (let i = 0; i < m; i++) tr += Go[i * m + i];
5256
+ const eps = (opts.ridge || 1e-6) * tr / m;
5257
+ const bl = new Float64Array(m);
5258
+ for (let i = 0; i < m; i++) {
5259
+ let s = 0;
5260
+ const o = i * m;
5261
+ for (let j = 0; j < m; j++) s += Go[o + j] * w0[j];
5262
+ bl[i] = s;
5263
+ }
5264
+ let c0 = 0;
5265
+ for (let i = 0; i < m; i++) c0 += w0[i] * bl[i];
5266
+ const M = Go, dim = m;
5267
+ let st = null;
5268
+ lap("gram");
5269
+ const blockwise = !opts.exact && !opts.classMu && !opts.keepClasses && !opts.fullCurve && m >= (opts.blockMin || 180) && (targets.length === 1 || tol !== void 0 && !targets.length);
5270
+ if (blockwise) {
5271
+ const feq = new Float64Array(m);
5272
+ ob.list.forEach((mem, o) => {
5273
+ let s = 0;
5274
+ for (const i of mem) s += P.ef[i];
5275
+ feq[o] = s / mem.length;
5276
+ });
5277
+ const order = Array.from({ length: m }, (_, o) => o).sort((x, y) => feq[x] - feq[y]);
5278
+ const G = Math.max(2, Math.round(m / (opts.blockSize || 110)));
5279
+ const seqs = [];
5280
+ for (let q = 0; q < G; q++) {
5281
+ const mark = arena ? WK.top : 0;
5282
+ const b = obsState(Go, m, order.slice(Math.floor(q * m / G), Math.floor((q + 1) * m / G)), eps, w0, null), seq = [];
5283
+ while (b.na > 1) {
5284
+ const bq = obsPick(b);
5285
+ if (bq < 0) break;
5286
+ const sal = b.sal;
5287
+ seq.push([obsRemove(b, bq), sal]);
5288
+ }
5289
+ seqs.push(seq);
5290
+ if (arena) WK.top = mark;
5291
+ }
5292
+ lap("blockElim");
5293
+ const head = new Int32Array(G), gone = new Uint8Array(m);
5294
+ let h1 = hands, c1 = 0;
5295
+ const stopHands = targets.length ? Math.ceil(targets[0] * (opts.blockKeep || 1.25)) : 0, stopCost = tol !== void 0 ? (tol * (opts.blockTol || 0.6)) ** 2 * c0 : Infinity;
5296
+ for (; ; ) {
5297
+ let bg = -1, bs = Infinity;
5298
+ for (let q = 0; q < G; q++) if (head[q] < seqs[q].length && seqs[q][head[q]][1] < bs) {
5299
+ bs = seqs[q][head[q]][1];
5300
+ bg = q;
5301
+ }
5302
+ if (bg < 0) break;
5303
+ const o = seqs[bg][head[bg]][0];
5304
+ if (targets.length ? h1 - osize[o] < stopHands : c1 + bs > stopCost) break;
5305
+ gone[o] = 1;
5306
+ h1 -= osize[o];
5307
+ c1 += bs;
5308
+ head[bg]++;
5309
+ }
5310
+ const keep = [];
5311
+ for (let o = 0; o < m; o++) if (!gone[o]) keep.push(o);
5312
+ if (keep.length < m) {
5313
+ st = obsState(Go, m, keep, eps, null, bl);
5314
+ let e1 = c0;
5315
+ for (let q = 0; q < st.k; q++) e1 -= st.wp[q] * bl[keep[q]];
5316
+ if (tol !== void 0 && Math.sqrt(Math.max(0, e1) / c0) > tol) st = null;
5317
+ else {
5318
+ cum = Math.max(0, e1);
5319
+ hands = h1;
5320
+ }
5321
+ }
5322
+ lap("stage2init");
5323
+ }
5324
+ if (!st) {
5325
+ const all = new Int32Array(m);
5326
+ for (let i = 0; i < m; i++) all[i] = i;
5327
+ st = obsState(Go, m, all, eps, w0, null);
5328
+ hands = hero.length;
5329
+ cum = 0;
5330
+ }
5331
+ const snapshot = () => {
5332
+ const na = st.na, sup = st.act, ww = new Float64Array(m);
5333
+ const gs = mk(Float64Array, na * na), bs = mk(Float64Array, na), x = mk(Float64Array, na);
5334
+ for (let q = 0; q < na; q++) {
5335
+ const o = sup[q] * dim, r = q * na;
5336
+ bs[q] = bl[sup[q]];
5337
+ x[q] = st.wp[q] > 0 ? st.wp[q] : 0;
5338
+ for (let p = 0; p < na; p++) gs[r + p] = M[o + sup[p]];
5339
+ }
5340
+ if (arena) WK.ex.nnls(gs.byteOffset, bs.byteOffset, x.byteOffset, na, opts.sweeps || 60);
5341
+ else for (let s = 0, S = opts.sweeps || 60; s < S; s++) {
5342
+ let moved = 0;
5343
+ for (let q = 0; q < na; q++) {
5344
+ const r = q * na, gq = gs[r + q];
5345
+ let v = bs[q] + gq * x[q];
5346
+ for (let p = 0; p < na; p++) v -= gs[r + p] * x[p];
5347
+ v = v > 0 ? v / gq : 0;
5348
+ const d = v - x[q];
5349
+ if (d > moved) moved = d;
5350
+ else if (-d > moved) moved = -d;
5351
+ x[q] = v;
5352
+ }
5353
+ if (moved < 1e-12) break;
5354
+ }
5355
+ let e = 0, hc = 0;
5356
+ for (let q = 0; q < na; q++) {
5357
+ const o = sup[q];
5358
+ ww[o] = x[q];
5359
+ if (!x[q]) continue;
5360
+ hc += osize[o];
5361
+ const r = q * na;
5362
+ let v = 0;
5363
+ for (let p = 0; p < na; p++) v += gs[r + p] * x[p];
5364
+ e += x[q] * (v - 2 * bs[q]);
5365
+ }
5366
+ return { hands: hc, err: Math.sqrt(Math.max(0, e + c0) / c0), w: ww };
5367
+ };
5368
+ lap("fullInit");
5369
+ let ti = 0;
5370
+ while (st.na > 1) {
5371
+ while (ti < targets.length && hands <= targets[ti]) {
5372
+ path.push(Object.assign({ target: targets[ti] }, snapshot()));
5373
+ ti++;
5374
+ }
5375
+ if (ti >= targets.length && tol === void 0 && !opts.fullCurve) break;
5376
+ const bq = obsPick(st, skip);
5377
+ if (bq < 0) break;
5378
+ const sal = st.sal;
5379
+ if (tol !== void 0 && Math.sqrt((cum + sal) / c0) > tol) break;
5380
+ const o = obsRemove(st, bq);
5381
+ if (clsCount) clsCount.set(ocls[o], clsCount.get(ocls[o]) - 1);
5382
+ hands -= osize[o];
5383
+ cum += sal;
5384
+ if (opts.fullCurve) curve.push([hands, Math.sqrt(cum / c0)]);
5385
+ }
5386
+ lap("stage2elim");
5387
+ while (ti < targets.length) {
5388
+ path.push(Object.assign({ target: targets[ti] }, snapshot()));
5389
+ ti++;
5390
+ }
5391
+ if (tol !== void 0) path.push(Object.assign({ target: tol }, snapshot()));
5392
+ lap("refit");
5393
+ return { path, ob, curve };
5394
+ }
5395
+ function materialize(P, snap, ob, opts = {}) {
5396
+ const { hero, n } = P;
5397
+ const hands = [], reps = [];
5398
+ hero.forEach((h, i) => {
5399
+ const x = snap.w[ob.orb[i]];
5400
+ if (x > 0) {
5401
+ hands.push({ a: h.a, b: h.b, w: x });
5402
+ reps.push(i);
5403
+ }
5404
+ });
5405
+ let mx = 0;
5406
+ for (const h of hands) if (h.w > mx) mx = h.w;
5407
+ for (const h of hands) h.w /= mx;
5408
+ if (!opts.top) return { hands, prefs: null, err: snap.err, scale: 1 / mx };
5409
+ const D = distances(P);
5410
+ const key = (i, r) => D[i * n + r] + (opts.sameClass && cls(hero[i]) !== cls(hero[r]) ? 10 : 0);
5411
+ const prefs = hero.map((h, i) => {
5412
+ const top = reps.slice().sort((x, y) => key(i, x) - key(i, y)).slice(0, opts.top);
5413
+ return [hid(h), top.map((r) => hid(hero[r])), top.map((r) => +key(i, r).toFixed(5))];
5414
+ });
5415
+ if (opts.transport) {
5416
+ const m = reps.length, eps = opts.transport;
5417
+ const a = hero.map((h) => h.w), b = hands.map((h) => h.w);
5418
+ const sa = a.reduce((x, y) => x + y, 0), sb = b.reduce((x, y) => x + y, 0);
5419
+ const K = new Float64Array(n * m);
5420
+ for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) K[i * m + j] = Math.exp(-D[i * n + reps[j]] / eps);
5421
+ const u = new Float64Array(n).fill(1), v = new Float64Array(m).fill(1);
5422
+ for (let it = 0; it < (opts.transportIters || 300); it++) {
5423
+ for (let i = 0; i < n; i++) {
5424
+ let t = 0;
5425
+ const o = i * m;
5426
+ for (let j = 0; j < m; j++) t += K[o + j] * v[j];
5427
+ u[i] = a[i] / sa / (t || 1e-300);
5428
+ }
5429
+ for (let j = 0; j < m; j++) {
5430
+ let t = 0;
5431
+ for (let i = 0; i < n; i++) t += K[i * m + j] * u[i];
5432
+ v[j] = b[j] / sb / (t || 1e-300);
5433
+ }
5434
+ }
5435
+ hero.forEach((h, i) => {
5436
+ const row = [];
5437
+ let tot = 0;
5438
+ for (let j = 0; j < m; j++) {
5439
+ const x = u[i] * K[i * m + j] * v[j];
5440
+ if (x > 0) row.push([j, x]);
5441
+ tot += x;
5442
+ }
5443
+ row.sort((x, y) => y[1] - x[1]);
5444
+ const top = row.slice(0, opts.top);
5445
+ prefs[i] = [hid(h), top.map((x) => hid(hero[reps[x[0]]])), top.map((x) => +D[i * n + reps[x[0]]].toFixed(5)), top.map((x) => +(x[1] / tot).toFixed(5))];
5446
+ });
5447
+ }
5448
+ return { hands, prefs, err: snap.err, scale: 1 / mx };
5449
+ }
5450
+ const asHands = (r) => typeof r === "string" ? parseRange2(r) : r.map((h) => {
5451
+ if (!h.hand) return h;
5452
+ let a = cardFromStr(h.hand.slice(0, 2)), b = cardFromStr(h.hand.slice(2, 4));
5453
+ if (a > b) {
5454
+ const t = a;
5455
+ a = b;
5456
+ b = t;
5457
+ }
5458
+ return { a, b, w: h.weight };
5459
+ });
5460
+ const asFlop = (f) => {
5461
+ const txt = typeof f === "string" ? f.replace(/[\s,]/g, "") : null;
5462
+ const b = txt !== null ? /^([2-9TJQKA][cdhs])*$/.test(txt) ? (txt.match(/../g) || []).map(cardFromStr) : [] : Array.isArray(f) ? f.slice() : [];
5463
+ if (b.length < 3 || b.length > 5 || b.some((c) => !(c >= 0 && c < 52) || c !== Math.floor(c)) || new Set(b).size !== b.length) throw new Error('The board must be three, four or five different cards, like "Td9d6h" or "Td9d6h2c"; got ' + JSON.stringify(f));
5464
+ return b;
5465
+ };
5466
+ const boardOf = (o) => asFlop(o.board !== void 0 ? o.board : o.flop);
5467
+ const asMask = (b) => !b ? 0 : typeof b === "number" ? b : b.reduce((m, s) => m | 1 << (typeof s === "string" ? SUITS2.indexOf(s) : s), 0);
5468
+ const liveHands = (hands, flop) => hands.filter((h) => h.w > 0 && !flop.includes(h.a) && !flop.includes(h.b));
5469
+ function blankSuitsFor(flop) {
5470
+ flop = asFlop(flop);
5471
+ const fc = [0, 0, 0, 0];
5472
+ flop.forEach((c) => fc[c & 3]++);
5473
+ return [0, 1, 2, 3].filter((s) => fc[s] < 2).map((s) => SUITS2[s]);
5474
+ }
5475
+ const expectedFrequencyError = (mismatch) => 0.6 + 60 * mismatch;
5476
+ const binsFor = (o, st) => o.bins || (st.fixed.length === 2 ? 64 : 16);
5477
+ const arenaBytes = (nA, nB, st, bins) => {
5478
+ const n = Math.max(nA, nB);
5479
+ return (4 * (st.rivers.length + st.turns.length + 2) + 16 * st.turns.length + 96) * (nA + nB) + 56 * n * n + 16 * (bins || 16) * n + 12 * st.rivers.length * 8 + (4 << 20);
5480
+ };
5481
+ const elimOpts = (o, n, sym) => {
5482
+ const opts = { symmetric: o.symmetric !== false && sym, bins: o.bins, streetWeights: o.streetWeights, exact: o.exact, riverSample: o.riverSample || "auto" };
5483
+ if (o.size) opts.sizes = [Math.min(o.size, n)];
5484
+ else opts.tolerance = o.tolerance === void 0 ? 0.01 : o.tolerance;
5485
+ if (o.curve) opts.fullCurve = true;
5486
+ return opts;
5487
+ };
5488
+ function solveOne(P, o) {
5489
+ const eo = elimOpts(o, P.n, P.boardSym || P.perms.length === 1);
5490
+ eo.bins = binsFor(o, P.states);
5491
+ const el = eliminate(P, eo);
5492
+ const m = materialize(P, el.path[0], el.ob, { top: o.standIns || 0 });
5493
+ return { hands: m.hands, prefs: m.prefs, err: m.err, scale: m.scale, n: P.n, curve: o.curve ? el.curve : void 0 };
5494
+ }
5495
+ function present(r, states) {
5496
+ let standIns = null;
5497
+ if (r.prefs) {
5498
+ standIns = {};
5499
+ r.prefs.forEach(([id, list]) => {
5500
+ standIns[handToStr(id / 52 | 0, id % 52)] = list.map((x) => handToStr(x / 52 | 0, x % 52));
5501
+ });
5502
+ }
5503
+ const hands = r.hands;
5504
+ return {
5505
+ range: rangeToString(hands),
5506
+ get pio() {
5507
+ return hands.map((h) => handToStr(h.a, h.b) + ":" + h.w.toFixed(4)).join(",");
5508
+ },
5509
+ hands: hands.map((h) => ({ hand: handToStr(h.a, h.b), weight: h.w })),
5510
+ size: hands.length,
5511
+ originalSize: r.n,
5512
+ mismatch: r.err,
5513
+ expectedFrequencyError: expectedFrequencyError(r.err),
5514
+ standIns,
5515
+ curve: r.curve,
5516
+ weightScale: r.scale,
5517
+ deck: states.blankMask ? { blankSuits: [0, 1, 2, 3].filter((s) => states.blankMask >> s & 1).map((s) => SUITS2[s]), turnCards: states.turns.length, riverBoards: states.rivers.length } : null
5518
+ };
5519
+ }
5520
+ function compress(o) {
5521
+ const flop = boardOf(o);
5522
+ const hero = liveHands(asHands(o.range), flop), villain = liveHands(asHands(o.opponent), flop);
5523
+ const states = deckStates(flop, asMask(o.blankSuits));
5524
+ return present(withArena(arenaBytes(hero.length, 0, states, binsFor(o, states)), () => solveOne(prepareBoth(hero, villain, flop, states, true, false)[0], o)), states);
5525
+ }
5526
+ function compressBoth(o) {
5527
+ const flop = boardOf(o);
5528
+ const a = liveHands(asHands(o.oop), flop), b = liveHands(asHands(o.ip), flop);
5529
+ const states = deckStates(flop, asMask(o.blankSuits));
5530
+ const r = withArena(arenaBytes(a.length, b.length, states, binsFor(o, states)), () => {
5531
+ const P = prepareBoth(a, b, flop, states);
5532
+ const mark = arena ? WK.top : 0;
5533
+ const x = solveOne(P[0], Object.assign({}, o, { size: o.sizeOop || o.size }));
5534
+ if (arena) WK.top = mark;
5535
+ return [x, solveOne(P[1], Object.assign({}, o, { size: o.sizeIp || o.size }))];
5536
+ });
5537
+ return { oop: present(r[0], states), ip: present(r[1], states) };
5538
+ }
5539
+ return {
5540
+ compress,
5541
+ compressBoth,
5542
+ blankSuitsFor,
5543
+ expectedFrequencyError,
5544
+ parseRange: parseRange2,
5545
+ rangeToString,
5546
+ cardFromStr,
5547
+ cardToStr,
5548
+ handToStr,
5549
+ /** true if the WebAssembly kernels loaded; setWasm(false) forces the JavaScript path */
5550
+ get wasm() {
5551
+ return !!wasm3();
5552
+ },
5553
+ setWasm(on) {
5554
+ wasmOn = !!on;
5555
+ },
5556
+ ready,
5557
+ releaseMemory
5558
+ };
5559
+ }
5560
+ var range_compress_default = factory();
5561
+
5562
+ // src/compress.ts
5563
+ function compressRanges(config, options = {}) {
5564
+ const board = parseCards(config.board);
5565
+ if (board.length < 3 || board.length > 5) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);
5566
+ const tolerance = options.tolerance ?? (board.length === 3 ? 0.01 : 5e-3);
5567
+ if (!(tolerance > 0 && tolerance < 1)) throw new Error(`tolerance must be above 0 and under 1; got ${tolerance}`);
5568
+ const sizes = options.size === void 0 ? void 0 : typeof options.size === "number" ? [options.size, options.size] : options.size;
5569
+ if (sizes && !sizes.every((n) => Number.isInteger(n) && n >= 2)) throw new Error(`size must be whole numbers of at least 2; got ${String(options.size)}`);
5570
+ const onBoard = new Set(board);
5571
+ const floor = config.minWeight ?? 0;
5572
+ const live = (range, who) => {
5573
+ const weights = typeof range === "string" ? parseRange(range) : range;
5574
+ if (weights.length !== COMBOS) throw new Error(`The ${who} range has ${weights.length} weights; one per combination is ${COMBOS}`);
5575
+ const kept = [];
5576
+ let largest = 0;
5577
+ for (let combo = 0; combo < COMBOS; combo++) {
5578
+ const weight = weights[combo];
5579
+ if (!(weight > 0) || weight < floor) continue;
5580
+ if (onBoard.has(COMBO_CARDS[combo * 2]) || onBoard.has(COMBO_CARDS[combo * 2 + 1])) continue;
5581
+ kept.push(combo);
5582
+ if (weight > largest) largest = weight;
5583
+ }
5584
+ if (kept.length === 0) throw new Error(`The ${who} range is empty once the board's cards${floor > 0 ? " and the combinations under minWeight" : ""} are removed`);
5585
+ return kept.map((combo) => ({ hand: formatCombo(combo), weight: weights[combo] / largest }));
5586
+ };
5587
+ const oop = live(config.oop, "out-of-position");
5588
+ const ip = live(config.ip, "in-position");
5589
+ let result;
5590
+ try {
5591
+ result = range_compress_default.compressBoth({
5592
+ oop,
5593
+ ip,
5594
+ board: board.map(formatCard).join(""),
5595
+ ...sizes ? { sizeOop: Math.min(sizes[0], oop.length), sizeIp: Math.min(sizes[1], ip.length) } : { tolerance }
5596
+ });
5597
+ } finally {
5598
+ range_compress_default.releaseMemory();
5599
+ }
5600
+ const weightsOf = (hands) => {
5601
+ const weights = new Float64Array(COMBOS);
5602
+ for (const { hand, weight } of hands) weights[comboIndex(parseCard(hand.slice(0, 2)), parseCard(hand.slice(2, 4)))] = weight;
5603
+ return weights;
5604
+ };
5605
+ return {
5606
+ oop: weightsOf(result.oop.hands),
5607
+ ip: weightsOf(result.ip.hands),
5608
+ report: [
5609
+ { from: oop.length, to: result.oop.size, mismatch: result.oop.mismatch },
5610
+ { from: ip.length, to: result.ip.size, mismatch: result.ip.mismatch }
5611
+ ]
5612
+ };
5613
+ }
5614
+
3925
5615
  // src/presets.ts
3926
5616
  function sizesCut(caller, preset) {
3927
5617
  const from = bettingTree(caller);
@@ -4044,8 +5734,10 @@ function liteConfig(config, options = {}) {
4044
5734
  );
4045
5735
  const buckets = options.runoutBuckets ?? 3;
4046
5736
  const given = typeof config.runoutBuckets === "number" ? config.runoutBuckets : config.runoutBuckets ? 1 : 0;
5737
+ const compressed = options.compressRanges ? compressRanges(config, options.compressRanges === true ? {} : options.compressRanges) : void 0;
4047
5738
  return {
4048
5739
  ...config,
5740
+ ...compressed ? { oop: compressed.oop, ip: compressed.ip, minWeight: void 0 } : {},
4049
5741
  betSizes,
4050
5742
  ...raiseSizes === void 0 ? {} : { raiseSizes },
4051
5743
  maxRaises,
@@ -4075,10 +5767,11 @@ function nearest(row, target) {
4075
5767
  }
4076
5768
  function solveLite(config, options = {}) {
4077
5769
  const preset = litePreset(config, options);
4078
- const blueprint = preset.config;
5770
+ return liteSolution(solve(defineSpot(preset.config), preset.options), config, preset.config, preset.changes, options);
5771
+ }
5772
+ function liteSolution(solution, config, blueprint, changes, options) {
4079
5773
  const share = blueprint.shareHistories;
4080
5774
  const kept = typeof share === "object" ? [...share.keepLines ?? []] : [];
4081
- const solution = solve(defineSpot(blueprint), preset.options);
4082
5775
  const subgameSolve = pick(options, ["workers", "precision", "wasmStorage"]);
4083
5776
  const { tree } = solution.spot;
4084
5777
  const scale = solution.spot.chipScale;
@@ -4087,7 +5780,7 @@ function solveLite(config, options = {}) {
4087
5780
  blueprint,
4088
5781
  kept,
4089
5782
  source: config,
4090
- changes: preset.changes,
5783
+ changes,
4091
5784
  resolve(node, board, resolveOptions) {
4092
5785
  const round = tree.round[node];
4093
5786
  const prefix = `${solution.path(node)} `;
@@ -4103,10 +5796,96 @@ function solveLite(config, options = {}) {
4103
5796
  }
4104
5797
  };
4105
5798
  }
5799
+ var LITE_RESUME = 30;
5800
+ function openLite(config, options = {}) {
5801
+ const preset = litePreset(config, options);
5802
+ const { settle, ...rest } = preset.options;
5803
+ const moved = settle || options.resettle ? { ...settle, ...options.resettle } : null;
5804
+ const resettle = moved && options.algorithm === "cfr+" && options.resettle?.tolerance === void 0 ? { ...moved, tolerance: settlePlan(moved).tolerance / 2 } : moved;
5805
+ if (resettle) settlePlan(resettle);
5806
+ const compress = options.compressRanges ? options.compressRanges === true ? {} : options.compressRanges : null;
5807
+ let run = createRun(defineSpot(preset.config), preset.options);
5808
+ let source = config;
5809
+ let earlier = 0;
5810
+ const reading = (solution) => liteSolution(solution, source, run.spot.source, preset.changes, options);
5811
+ const settleRun = (plan) => reading(runToStop(run, plan ? { ...rest, settle: plan } : rest));
5812
+ const resumed = () => options.algorithm === "cfr+" ? run.totalIterations : Math.min(run.totalIterations, LITE_RESUME);
5813
+ let current;
5814
+ try {
5815
+ current = settleRun(settle);
5816
+ } catch (error) {
5817
+ run.close();
5818
+ throw error;
5819
+ }
5820
+ return {
5821
+ get current() {
5822
+ return current;
5823
+ },
5824
+ get iterations() {
5825
+ return earlier + run.completed;
5826
+ },
5827
+ setRange(player, range) {
5828
+ const next = { ...source, [player === 0 ? "oop" : "ip"]: typeof range === "string" ? range : range.slice() };
5829
+ let inPlace = false;
5830
+ if (!compress) {
5831
+ try {
5832
+ run.setRange(player, range, { resume: LITE_RESUME });
5833
+ inPlace = true;
5834
+ } catch (error) {
5835
+ if (!(error instanceof RangeNotInPlaceError)) throw error;
5836
+ }
5837
+ }
5838
+ if (!inPlace) {
5839
+ const ranges = compress ? compressRanges(next, compress) : next;
5840
+ const stored = (index) => Float64Array.from(index.slot, (slot) => slot >= 0 ? 1 : 0);
5841
+ const blueprint = {
5842
+ ...preset.config,
5843
+ oop: ranges.oop,
5844
+ ip: ranges.ip,
5845
+ ...compress ? {} : { oopReserve: stored(run.spot.players[0]), ipReserve: stored(run.spot.players[1]) }
5846
+ };
5847
+ const spot = defineSpot(blueprint);
5848
+ const count = resumed();
5849
+ run.close();
5850
+ let replacement;
5851
+ try {
5852
+ replacement = createRun(spot, { ...preset.options, warmStart: run, warmIteration: count });
5853
+ } catch (error) {
5854
+ run = createRun(run.spot, { ...preset.options, warmStart: run });
5855
+ throw error;
5856
+ }
5857
+ earlier += run.completed;
5858
+ run = replacement;
5859
+ }
5860
+ source = next;
5861
+ try {
5862
+ current = settleRun(resettle);
5863
+ } catch (error) {
5864
+ current = reading(run.snapshot([], "iterations"));
5865
+ throw error;
5866
+ }
5867
+ return current;
5868
+ },
5869
+ refine(count) {
5870
+ if (!(Number.isInteger(count) && count > 0)) throw new Error(`refine: iterations must be a positive whole number; got ${count}`);
5871
+ run.step(count);
5872
+ current = reading(run.snapshot([], "iterations"));
5873
+ return current;
5874
+ },
5875
+ close() {
5876
+ run.close();
5877
+ }
5878
+ };
5879
+ }
5880
+ var KEEP_TOLERANCE = 5e-3;
4106
5881
  function litePreset(config, options = {}) {
4107
5882
  const blueprint = keepWithin(liteConfig(config, options), options);
4108
5883
  const sampling = options.sampling === void 0 ? {} : options.sampling;
4109
- const settle = options.settle === void 0 ? {} : options.settle;
5884
+ const asked = options.settle === void 0 ? {} : options.settle;
5885
+ const share = blueprint.shareHistories;
5886
+ const keeps = options.keepBudget !== void 0 && typeof share === "object" && (share.keepLines?.length ?? 0) > 0;
5887
+ const settle = asked && keeps && asked.tolerance === void 0 ? { ...asked, tolerance: KEEP_TOLERANCE } : asked;
5888
+ const tolerance = settle ? settlePlan(settle).tolerance : 0;
4110
5889
  const solveOptions = {
4111
5890
  iterations: options.iterations ?? 2e3,
4112
5891
  ...settle ? { settle } : {},
@@ -4141,8 +5920,14 @@ function litePreset(config, options = {}) {
4141
5920
  if (dropped > 0) {
4142
5921
  change("removeActions", config.removeActions, blueprint.removeActions, `${dropped} line${dropped > 1 ? "s" : ""} below a deal or past the flop cap left out of the blueprint; resolve puts those below a deal back`);
4143
5922
  }
5923
+ if (options.compressRanges) {
5924
+ const count = (range) => activeCombos(typeof range === "string" ? parseRange(range) : range).length;
5925
+ change("compressRanges", void 0, options.compressRanges, `compressed to ${count(blueprint.oop)} and ${count(blueprint.ip)} re-weighted combinations (out of position, in position) that keep each range's equity distribution on this board and those that can follow it; approximate: the blueprint has no strategy for a combination left out, and what one combination does is not preserved`);
5926
+ }
4144
5927
  if (sampling) change("approximations.chanceSampling", void 0, sampling, samplingNote(sampling));
4145
- if (settle) change("settle", void 0, settle, "stops once the root play stops moving, not at an exploitability target");
5928
+ if (settle) {
5929
+ change("settle", void 0, settle, `stops once the root play moves under ${+(100 * tolerance).toFixed(2)}% of the range between checks, not at an exploitability target${settle === asked ? "" : " (later than its default, for the kept lines' turn ranges)"}`);
5930
+ }
4146
5931
  return { config: blueprint, options: solveOptions, changes: presetChanges(config, blueprint, settings, notes) };
4147
5932
  }
4148
5933
  function keepWithin(blueprint, options = {}) {
@@ -4211,6 +5996,11 @@ function bettingFrom(config, round) {
4211
5996
  };
4212
5997
  return out;
4213
5998
  }
5999
+ function exploitabilityInExact(lite, exact) {
6000
+ if (exact.solver.ctx.layout.shared) throw new Error("The Exact run shares histories; measure in one that keeps them apart");
6001
+ warmStart(exact.solver.ctx, lite.solver.ctx, true);
6002
+ return exact.exploitabilityPercent();
6003
+ }
4214
6004
 
4215
6005
  // src/index.ts
4216
6006
  var OPS_PER_SECOND = 2e8;
@@ -4248,6 +6038,9 @@ function defineSpot(config) {
4248
6038
  const rounds = 6 - board.length;
4249
6039
  if (config.pot <= 0) throw new Error("pot must be positive");
4250
6040
  if (config.stack <= 0) throw new Error("stack must be positive");
6041
+ if (config.evPot !== void 0 && !(Number.isFinite(config.evPot) && config.evPot > 0)) {
6042
+ throw new Error(`evPot must be a positive number of chips; got ${config.evPot}`);
6043
+ }
4251
6044
  const rows = betRows(config, rounds);
4252
6045
  const onBoard = new Set(board);
4253
6046
  const trim = (range, who) => {
@@ -4273,13 +6066,39 @@ function defineSpot(config) {
4273
6066
  }
4274
6067
  return weights;
4275
6068
  };
6069
+ const reserved = (range, who) => {
6070
+ if (range === void 0) return null;
6071
+ const hands = typeof range === "string" ? parseRange(range) : range;
6072
+ if (hands.length !== COMBOS) {
6073
+ throw new Error(`The ${who} reserve has ${hands.length} weights; one per combination is ${COMBOS}`);
6074
+ }
6075
+ const mask = new Float64Array(COMBOS);
6076
+ for (let combo = 0; combo < COMBOS; combo++) {
6077
+ if (hands[combo] > 0 && !onBoard.has(COMBO_CARDS[combo * 2]) && !onBoard.has(COMBO_CARDS[combo * 2 + 1])) mask[combo] = 1;
6078
+ }
6079
+ return mask;
6080
+ };
6081
+ const reserves = [reserved(config.oopReserve, "out-of-position"), reserved(config.ipReserve, "in-position")];
4276
6082
  const players = [
4277
- buildPlayerIndex(trim(config.oop, "out-of-position")),
4278
- buildPlayerIndex(trim(config.ip, "in-position"))
6083
+ buildPlayerIndex(trim(config.oop, "out-of-position"), reserves[0] ?? void 0),
6084
+ buildPlayerIndex(trim(config.ip, "in-position"), reserves[1] ?? void 0)
4279
6085
  ];
4280
- const symmetries = config.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights]);
6086
+ if (!holdable(players[0].weights, players[1].weights)) {
6087
+ throw new Error("No hand of one range can be held against a hand of the other: every pair shares a card");
6088
+ }
6089
+ for (const player of players) {
6090
+ if (config.maxCombos !== void 0 && player.count > config.maxCombos) {
6091
+ throw new Error(`A range and its reserve hold ${player.count} combinations, over the ${config.maxCombos} limit`);
6092
+ }
6093
+ }
6094
+ const symmetries = config.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights, ...reserves.filter((mask) => mask !== null)]);
4281
6095
  const merge = config.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config.runoutBuckets) : void 0;
4282
- const runouts = enumerateRunouts(board, symmetries, merge);
6096
+ const runouts = runoutsFor(board, symmetries, merge);
6097
+ const symmetryCombos = (symmetries ?? []).map((map) => {
6098
+ const image = new Uint16Array(COMBOS);
6099
+ for (let combo = 0; combo < COMBOS; combo++) image[combo] = comboIndex(map[COMBO_CARDS[combo * 2]], map[COMBO_CARDS[combo * 2 + 1]]);
6100
+ return image;
6101
+ }).filter((image) => image.some((combo, at) => combo !== at));
4283
6102
  const tree = buildTree(treeConfig(config, rows), runouts);
4284
6103
  const historyAlias = config.shareHistories ? shareHistories(tree, runouts, config, chipScale) : void 0;
4285
6104
  const layout = buildLayout(tree, runouts, players, 4, historyAlias);
@@ -4314,7 +6133,7 @@ function defineSpot(config) {
4314
6133
  suggestions
4315
6134
  };
4316
6135
  if (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);
4317
- return {
6136
+ const spot = {
4318
6137
  board,
4319
6138
  tree,
4320
6139
  runouts,
@@ -4329,7 +6148,52 @@ function defineSpot(config) {
4329
6148
  return resolveBoard(runouts, typeof cards === "string" ? parseCards(cards) : cards);
4330
6149
  }
4331
6150
  };
6151
+ spotSymmetries.set(spot, symmetryCombos);
6152
+ return spot;
6153
+ }
6154
+ var RANGE_RESUME = 10;
6155
+ var builtFrom = /* @__PURE__ */ new WeakMap();
6156
+ var keptRunouts = null;
6157
+ function runoutsFor(board, symmetries, merge) {
6158
+ let key = `${board.join(",")}|${(symmetries ?? []).map((map) => map.join(",")).join(";")}|`;
6159
+ if (merge) {
6160
+ key += `${merge.maxGap}:`;
6161
+ for (let a = 0; a < 13; a++) for (let b = 0; b < 13; b++) key += merge.ranks(a, b) ? "1" : "0";
6162
+ }
6163
+ if (keptRunouts?.key !== key) keptRunouts = { key, runouts: enumerateRunouts(board, symmetries, merge) };
6164
+ return keptRunouts.runouts;
6165
+ }
6166
+ var keptTables = null;
6167
+ function setupTables(spot, relevant) {
6168
+ const [first, second] = [spot.players[0].combos, spot.players[1].combos];
6169
+ const same = (a, b) => a.length === b.length && a.every((combo, i) => combo === b[i]);
6170
+ if (keptTables && keptTables.runouts === spot.runouts && same(keptTables.combos[0], first) && same(keptTables.combos[1], second)) {
6171
+ return keptTables.tables;
6172
+ }
6173
+ keptTables = null;
6174
+ const showdown = buildShowdownTable(spot.runouts, relevant);
6175
+ const active = buildActiveLists(spot.runouts, spot.players, showdown);
6176
+ const hands = buildHandSpace(spot.runouts, spot.players, active);
6177
+ keptTables = { runouts: spot.runouts, combos: [first, second], tables: { showdown, active, hands } };
6178
+ return keptTables.tables;
4332
6179
  }
6180
+ function releaseSetupCache() {
6181
+ keptRunouts = null;
6182
+ keptTables = null;
6183
+ }
6184
+ function holdable(a, b) {
6185
+ for (let i = 0; i < COMBOS; i++) {
6186
+ if (!(a[i] > 0)) continue;
6187
+ const [c, d] = [COMBO_CARDS[i * 2], COMBO_CARDS[i * 2 + 1]];
6188
+ for (let j = 0; j < COMBOS; j++) {
6189
+ if (!(b[j] > 0)) continue;
6190
+ const [e, f] = [COMBO_CARDS[j * 2], COMBO_CARDS[j * 2 + 1]];
6191
+ if (c !== e && c !== f && d !== e && d !== f) return true;
6192
+ }
6193
+ }
6194
+ return false;
6195
+ }
6196
+ var spotSymmetries = /* @__PURE__ */ new WeakMap();
4333
6197
  function shareHistories(tree, runouts, config, chipScale) {
4334
6198
  const asked = config.shareHistories === true ? {} : config.shareHistories || {};
4335
6199
  const keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : void 0;
@@ -4376,6 +6240,8 @@ var TREE_SETTINGS = [
4376
6240
  "mergeSizes",
4377
6241
  "thinSizes"
4378
6242
  ];
6243
+ var RangeNotInPlaceError = class extends Error {
6244
+ };
4379
6245
  function createRun(spot, options = {}) {
4380
6246
  if (options.analysisOnly && options.approximations?.currentProfileEv) {
4381
6247
  throw new Error("approximations.currentProfileEv needs regrets, and an analysisOnly run has none");
@@ -4391,39 +6257,60 @@ function createRun(spot, options = {}) {
4391
6257
  const clash = clashes.find(([set]) => set)?.[1];
4392
6258
  if (clash) throw new Error(`compactStorage does not combine with ${clash}`);
4393
6259
  }
4394
- const precision = compact ? options.precision ?? "f32" : options.analysisOnly ? "f32" : options.precision ?? (bytes <= maxBytes ? "f32" : "i16");
4395
- const coarsePlan = planCoarseStart(spot, options, precision, maxBytes);
6260
+ const defaulted = !compact && !options.analysisOnly && options.precision === void 0;
6261
+ let precision = compact ? options.precision ?? "f32" : options.analysisOnly ? "f32" : options.precision ?? (bytes <= maxBytes ? "f32" : "i16");
4396
6262
  const relevant = new Uint8Array(COMBOS);
4397
6263
  for (const combo of spot.players[0].combos) relevant[combo] = 1;
4398
6264
  for (const combo of spot.players[1].combos) relevant[combo] = 1;
4399
- const showdown = buildShowdownTable(spot.runouts, relevant);
4400
- const layout = buildLayout(
6265
+ if (!options.analysisOnly && options.engine !== "js" && options.simd !== false && (options.workers ?? 1) !== 1) {
6266
+ const engineLikely = precision === "f32" && !compact || options.wasmStorage !== void 0 && precision !== "f64" && (precision === "i16" || compact !== null);
6267
+ const asked = engineLikely ? resolveWorkers(options, true) : 1;
6268
+ if (asked > 1 && planShards(spot.tree, spot.runouts, asked)) warmEngineThreads(asked - 1);
6269
+ }
6270
+ const { showdown, active, hands } = setupTables(spot, relevant);
6271
+ const layoutAt = (at) => buildLayout(
4401
6272
  spot.tree,
4402
6273
  spot.runouts,
4403
6274
  spot.players,
4404
- PRECISION_BYTES[precision],
6275
+ PRECISION_BYTES[at],
4405
6276
  spot.historyAlias,
4406
6277
  compact ?? void 0
4407
6278
  );
6279
+ let layout = layoutAt(precision);
4408
6280
  const weights = runoutWeights(spot.runouts);
6281
+ const samplingOptions = options.approximations?.chanceSampling;
6282
+ const samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : void 0;
6283
+ const storageAt = (at, of) => compact ? of.bytes : Math.max(at === "i16" ? spot.estimate.compressedBytes : bytes, of.bytes);
6284
+ const baselineBytes = samplingPlan ? samplingBytes(samplingPlan) : 0;
6285
+ if (defaulted && precision === "f32" && samplingPlan && storageAt("f32", layout) + baselineBytes > maxBytes) {
6286
+ precision = "i16";
6287
+ layout = layoutAt(precision);
6288
+ }
6289
+ let storageBytes = storageAt(precision, layout);
6290
+ if (samplingPlan && storageBytes + baselineBytes > maxBytes) {
6291
+ throw new Error(
6292
+ `chanceSampling needs ${Math.ceil(baselineBytes / 2 ** 20)} MiB of baselines beside ${Math.ceil(storageBytes / 2 ** 20)} MiB of storage, over maxBytes; sample fewer rounds or raise maxBytes`
6293
+ );
6294
+ }
6295
+ const held = (at, of) => Math.max(storageAt(at, of), storageCost(spot, at)) + baselineBytes;
6296
+ let coarsePlan;
6297
+ try {
6298
+ coarsePlan = planCoarseStart(spot, options, maxBytes, held(precision, layout));
6299
+ } catch (error) {
6300
+ if (!(error instanceof CoarseRefusal && defaulted && precision === "f32")) throw error;
6301
+ precision = "i16";
6302
+ layout = layoutAt(precision);
6303
+ storageBytes = storageAt(precision, layout);
6304
+ coarsePlan = planCoarseStart(spot, { ...options, precision }, maxBytes, held(precision, layout));
6305
+ }
4409
6306
  const storageEngine = options.wasmStorage !== void 0 && precision !== "f64" && (precision === "i16" || compact !== null);
4410
6307
  const wantsEngine = options.engine !== "js" && !options.analysisOnly && options.simd !== false && (precision === "f32" && !compact || storageEngine);
4411
- const samplingOptions = options.approximations?.chanceSampling;
4412
6308
  const requested = resolveWorkers(options, wantsEngine);
4413
6309
  const shards = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;
4414
6310
  const plan = shards && samplingOptions && sampledRounds(samplingOptions, spot.runouts.rounds).some((r) => r < shards.round) ? null : shards;
4415
6311
  const allocate = (bytes2) => plan ? new SharedArrayBuffer(bytes2) : new ArrayBuffer(bytes2);
4416
6312
  const width = PRECISION_BYTES[precision];
4417
6313
  const quantised = precision === "i16";
4418
- const active = buildActiveLists(spot.runouts, spot.players, showdown);
4419
- const hands = buildHandSpace(spot.runouts, spot.players, active);
4420
- const samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : void 0;
4421
- const storageBytes = compact ? layout.bytes : Math.max(quantised ? spot.estimate.compressedBytes : bytes, layout.bytes);
4422
- if (samplingPlan && storageBytes + samplingBytes(samplingPlan) > maxBytes) {
4423
- throw new Error(
4424
- `chanceSampling needs ${Math.ceil(samplingBytes(samplingPlan) / 2 ** 20)} MiB of baselines beside ${Math.ceil(storageBytes / 2 ** 20)} MiB of storage, over maxBytes; sample fewer rounds or raise maxBytes`
4425
- );
4426
- }
4427
6314
  const engine = wantsEngine ? createEngine(
4428
6315
  {
4429
6316
  tree: spot.tree,
@@ -4504,8 +6391,9 @@ function createRun(spot, options = {}) {
4504
6391
  }
4505
6392
  if (warm) ctx.sampling?.lastUpdate.fill(offset);
4506
6393
  solver = makeSolver(ctx);
6394
+ if (engine?.profile) threadProfiles.set(solver, engine.profile);
4507
6395
  if (warm && coarsePlan) coarseMs.set(solver, coarsePlan.elapsed);
4508
- pool = plan && !engine ? startPool(ctx, solver, plan, { config: spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd, compact }, requested) : null;
6396
+ pool = plan && !engine ? startPool(ctx, solver, plan, { config: builtFrom.get(spot) ?? spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd, compact }, requested) : null;
4509
6397
  } catch (error) {
4510
6398
  engine?.close();
4511
6399
  throw error;
@@ -4514,6 +6402,7 @@ function createRun(spot, options = {}) {
4514
6402
  if (engine) solver.useRoot(engine.root(ctx.dcfr));
4515
6403
  const threadCount = pool ? pool.workers : engine ? engine.threads : 1;
4516
6404
  let completed = 0;
6405
+ const nextRange = new Float64Array(COMBOS);
4517
6406
  return {
4518
6407
  spot,
4519
6408
  solver,
@@ -4531,6 +6420,69 @@ function createRun(spot, options = {}) {
4531
6420
  solver.iterate(count, offset + completed);
4532
6421
  completed += count;
4533
6422
  },
6423
+ setRange(player, range, options2 = {}) {
6424
+ if (options2.resume !== void 0 && !(Number.isInteger(options2.resume) && options2.resume >= 0)) {
6425
+ throw new Error(`setRange: resume must be a whole number of iterations; got ${options2.resume}`);
6426
+ }
6427
+ const given = typeof range === "string" ? parseRange(range) : range;
6428
+ if (given.length !== COMBOS) {
6429
+ throw new Error(`setRange: the range has ${given.length} weights; one per combination is ${COMBOS}`);
6430
+ }
6431
+ const index = spot.players[player];
6432
+ const floor = spot.source.minWeight ?? 0;
6433
+ const [first, second, third] = spot.board;
6434
+ const fourth = spot.board[3] ?? -1;
6435
+ const fifth = spot.board[4] ?? -1;
6436
+ const blocked = (card) => card === first || card === second || card === third || card === fourth || card === fifth;
6437
+ let live = 0;
6438
+ let unstored = -1;
6439
+ for (let combo = 0; combo < COMBOS; combo++) {
6440
+ let weight = given[combo];
6441
+ if (!(weight >= 0)) throw new Error(`setRange: a weight is ${weight}; weights are zero or more`);
6442
+ if (weight < floor) weight = 0;
6443
+ if (weight > 0 && index.slot[combo] < 0) {
6444
+ if (blocked(COMBO_CARDS[combo * 2]) || blocked(COMBO_CARDS[combo * 2 + 1])) weight = 0;
6445
+ else if (unstored < 0) unstored = combo;
6446
+ }
6447
+ if (weight > 0) live++;
6448
+ nextRange[combo] = weight;
6449
+ }
6450
+ if (live === 0) throw new Error("setRange: the range is empty once the board is removed");
6451
+ if (!holdable(nextRange, spot.players[1 - player].weights)) {
6452
+ throw new Error("setRange: no hand of this range can be held against the other range");
6453
+ }
6454
+ if (unstored >= 0) {
6455
+ throw new RangeNotInPlaceError(
6456
+ `setRange: ${formatCards([COMBO_CARDS[unstored * 2], COMBO_CARDS[unstored * 2 + 1]])} has no storage; a hand can be added only if the range or \`${player === 0 ? "oopReserve" : "ipReserve"}\` held it when the spot was defined`
6457
+ );
6458
+ }
6459
+ for (const image of spotSymmetries.get(spot) ?? []) {
6460
+ for (let combo = 0; combo < COMBOS; combo++) {
6461
+ if (nextRange[combo] !== nextRange[image[combo]]) {
6462
+ throw new RangeNotInPlaceError(
6463
+ "setRange: the range breaks a suit symmetry the spot folds runouts by; keep mirrored hands at one weight, or define the spot with `isomorphism: false`"
6464
+ );
6465
+ }
6466
+ }
6467
+ }
6468
+ index.weights.set(nextRange);
6469
+ if (!builtFrom.has(spot)) builtFrom.set(spot, spot.source);
6470
+ const stored = Float64Array.from(index.slot, (slot) => slot >= 0 ? 1 : 0);
6471
+ spot.source = player === 0 ? { ...spot.source, oop: nextRange.slice(), oopReserve: stored } : { ...spot.source, ip: nextRange.slice(), ipReserve: stored };
6472
+ let resumed = offset + completed;
6473
+ if (ctx.dcfr) {
6474
+ resumed = Math.min(resumed, options2.resume ?? RANGE_RESUME);
6475
+ offset = resumed - completed;
6476
+ } else if (ctx.regret.length > 0 || ctx.compactRegret) {
6477
+ ctx.strategySum.fill(0);
6478
+ ctx.sumScale?.fill(0);
6479
+ ctx.compactSum?.forEach((sums) => sums.fill(0));
6480
+ ctx.sumShift?.forEach((shifts) => shifts.fill(0));
6481
+ }
6482
+ ctx.discounted?.fill(0);
6483
+ ctx.sampling?.lastWalk.fill(0);
6484
+ ctx.sampling?.lastUpdate.fill(resumed);
6485
+ },
4534
6486
  close() {
4535
6487
  solver.useRoot(null);
4536
6488
  pool?.close();
@@ -4594,8 +6546,10 @@ function compactPlan(settings, rounds) {
4594
6546
  };
4595
6547
  }
4596
6548
  var DEFAULT_COARSE_GAP = 3;
6549
+ var CoarseRefusal = class extends Error {
6550
+ };
4597
6551
  var coarseMs = /* @__PURE__ */ new WeakMap();
4598
- function planCoarseStart(spot, options, precision, maxBytes) {
6552
+ function planCoarseStart(spot, options, maxBytes, used) {
4599
6553
  const settings = options.approximations?.coarseStart;
4600
6554
  if (!settings) return null;
4601
6555
  const { iterations, runoutBuckets = DEFAULT_COARSE_GAP } = settings;
@@ -4612,15 +6566,17 @@ function planCoarseStart(spot, options, precision, maxBytes) {
4612
6566
  if (iterations === 0 || spot.board.length === 5 || runoutBuckets <= ownGap) return null;
4613
6567
  const coarseSpot = defineSpot({ ...spot.source, runoutBuckets });
4614
6568
  if (coarseSpot.runouts.counts.at(-1) >= spot.runouts.counts.at(-1)) return null;
4615
- const used = storageCost(spot, precision);
4616
6569
  const left = maxBytes - used;
4617
- const coarsePrecision = options.precision ?? (storageCost(coarseSpot, "f32") <= left ? "f32" : "i16");
4618
- const needs = storageCost(coarseSpot, coarsePrecision);
4619
- if (needs > left) {
4620
- throw new Error(
4621
- `coarseStart needs ~${formatBytes(needs)} beside this spot's ~${formatBytes(used)}, over the ${formatBytes(maxBytes)} limit; raise maxBytes or leave coarseStart off`
4622
- );
4623
- }
6570
+ const sampling = options.approximations?.chanceSampling;
6571
+ const refuse = (needs2) => new CoarseRefusal(
6572
+ `coarseStart needs ~${formatBytes(needs2)} beside this spot's ~${formatBytes(used)}${sampling ? " (storage and chanceSampling baselines, for each)" : ""}, over the ${formatBytes(maxBytes)} limit; raise maxBytes or leave coarseStart off`
6573
+ );
6574
+ const narrowest = storageCost(coarseSpot, options.precision ?? "i16");
6575
+ if (narrowest > left) throw refuse(narrowest);
6576
+ const coarseBaselines = sampling ? baselineCost(coarseSpot, sampling) : 0;
6577
+ const coarsePrecision = options.precision ?? (storageCost(coarseSpot, "f32") + coarseBaselines <= left ? "f32" : "i16");
6578
+ const needs = storageCost(coarseSpot, coarsePrecision) + coarseBaselines;
6579
+ if (needs > left) throw refuse(needs);
4624
6580
  return { spot: coarseSpot, iterations, precision: coarsePrecision, elapsed: 0 };
4625
6581
  }
4626
6582
  function solveCoarse(plan, options) {
@@ -4644,6 +6600,15 @@ function solveCoarse(plan, options) {
4644
6600
  plan.elapsed = Date.now() - started;
4645
6601
  return run;
4646
6602
  }
6603
+ function baselineCost(of, sampling) {
6604
+ const relevant = new Uint8Array(COMBOS);
6605
+ for (const combo of of.players[0].combos) relevant[combo] = 1;
6606
+ for (const combo of of.players[1].combos) relevant[combo] = 1;
6607
+ const active = buildActiveLists(of.runouts, of.players, buildShowdownTable(of.runouts, relevant));
6608
+ const compact = of.source.compactStorage ? compactPlan(of.source.compactStorage, of.runouts.rounds) : void 0;
6609
+ const layout = buildLayout(of.tree, of.runouts, of.players, 4, of.historyAlias, compact);
6610
+ return samplingBytes(planSampling(of.tree, of.runouts, active, layout, sampling));
6611
+ }
4647
6612
  function storageCost(of, at) {
4648
6613
  if (of.estimate.compactBytes === null) {
4649
6614
  return at === "i16" ? of.estimate.compressedBytes : of.estimate.bytes * (at === "f64" ? 2 : 1);
@@ -4653,7 +6618,7 @@ function storageCost(of, at) {
4653
6618
  return of.estimate.compactBytes + bytesAt(PRECISION_BYTES[at]) - bytesAt(4);
4654
6619
  }
4655
6620
  function sameSpot(a, b) {
4656
- const plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, ...game }) => JSON.stringify(game, (_, value) => value instanceof Float64Array ? Array.from(value) : value);
6621
+ const plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, evPot: _evPot, ...game }) => JSON.stringify(game, (_, value) => value instanceof Float64Array ? Array.from(value) : value);
4657
6622
  const kept = (config) => typeof config.shareHistories === "object" ? config.shareHistories.keepLines : void 0;
4658
6623
  if (kept(a) === void 0 && kept(b) === void 0) return plain(a) === plain(b);
4659
6624
  const mine = new Set(kept(a) ?? []);
@@ -4710,19 +6675,25 @@ function makeSumStore(precision, buffer) {
4710
6675
  return precision === "f32" ? new Float32Array(buffer) : new Uint16Array(buffer);
4711
6676
  }
4712
6677
  function solve(spot, options = {}) {
4713
- const iterations = options.iterations ?? 500;
4714
- const target = options.targetPercent ?? 0;
4715
- const fixed = options.exploitEvery ?? 0;
4716
- const settle = options.settle ? settlePlan(options.settle) : null;
6678
+ if (options.settle) settlePlan(options.settle);
4717
6679
  const run = createRun(spot, options);
4718
- const history = [];
4719
- const started = Date.now() - (coarseMs.get(run.solver) ?? 0);
4720
- const before = coarseMs.has(run.solver) ? run.totalIterations : 0;
4721
6680
  try {
4722
- return runAll();
6681
+ return runToStop(run, options);
4723
6682
  } finally {
4724
6683
  run.close();
4725
6684
  }
6685
+ }
6686
+ function runToStop(run, options = {}) {
6687
+ const { spot } = run;
6688
+ const iterations = options.iterations ?? 500;
6689
+ const target = options.targetPercent ?? 0;
6690
+ const fixed = options.exploitEvery ?? 0;
6691
+ const settle = options.settle ? settlePlan(options.settle) : null;
6692
+ const history = [];
6693
+ const coarse = run.completed === 0 ? coarseMs.get(run.solver) : void 0;
6694
+ const started = Date.now() - (coarse ?? 0);
6695
+ const before = coarse !== void 0 ? run.totalIterations : 0;
6696
+ return runAll();
4726
6697
  function runAll() {
4727
6698
  if (settle) return runSettled(settle);
4728
6699
  if (fixed <= 0 && target <= 0) {
@@ -4771,6 +6742,7 @@ function solve(spot, options = {}) {
4771
6742
  }
4772
6743
  function runSettled(plan) {
4773
6744
  const tracker = trackSettle(plan);
6745
+ if (run.completed > 0) tracker.check(run.snapshot(), 0);
4774
6746
  let stoppedAt = "iterations";
4775
6747
  let done = 0;
4776
6748
  while (done < iterations) {
@@ -4850,7 +6822,10 @@ function makeSolution(spot, solver, iterations, totalIterations, history, stoppe
4850
6822
  let cachedEv = null;
4851
6823
  const rootValues = () => cachedEv ??= solver.rootValues(currentProfileEv ? Mode.Current : Mode.Average);
4852
6824
  const cachedHands = [null, null];
6825
+ const cachedChips = [null, null];
4853
6826
  let cachedExploit = null;
6827
+ const evPot = spot.source.evPot ?? spot.potUnits / spot.chipScale;
6828
+ const share = (chips) => 100 * (chips + evPot / 2) / evPot;
4854
6829
  return {
4855
6830
  spot,
4856
6831
  iterations,
@@ -4859,13 +6834,21 @@ function makeSolution(spot, solver, iterations, totalIterations, history, stoppe
4859
6834
  workers,
4860
6835
  solver,
4861
6836
  history,
6837
+ evPot,
4862
6838
  ev(player) {
6839
+ return share(rootValues().totals[player]);
6840
+ },
6841
+ evChips(player) {
4863
6842
  return rootValues().totals[player];
4864
6843
  },
4865
6844
  handEvs(player) {
4866
- cachedHands[player] ??= solver.handEvs(player, rootValues().values[player]);
6845
+ cachedHands[player] ??= solver.handEvs(player, rootValues().values[player], share);
4867
6846
  return cachedHands[player].slice();
4868
6847
  },
6848
+ handEvsChips(player) {
6849
+ cachedChips[player] ??= solver.handEvs(player, rootValues().values[player]);
6850
+ return cachedChips[player].slice();
6851
+ },
4869
6852
  exploitability() {
4870
6853
  cachedExploit ??= solver.exploitability();
4871
6854
  return cachedExploit;
@@ -4917,6 +6900,8 @@ function makeSolution(spot, solver, iterations, totalIterations, history, stoppe
4917
6900
  return {
4918
6901
  board: formatCards(cards),
4919
6902
  pot: tree.pot[node] / spot.chipScale,
6903
+ // EV stays a share of the original spot's pot down a hand.
6904
+ evPot,
4920
6905
  stack: (spot.stackUnits - invested) / spot.chipScale,
4921
6906
  oop: reachAt(node, board, 0),
4922
6907
  ip: reachAt(node, board, 1),
@@ -4952,7 +6937,9 @@ export {
4952
6937
  NodeKind,
4953
6938
  PLATFORM,
4954
6939
  PRECISION_BYTES,
6940
+ RANGE_RESUME,
4955
6941
  RANKS,
6942
+ RangeNotInPlaceError,
4956
6943
  SUITS,
4957
6944
  SpotTooLargeError,
4958
6945
  activeCombos,
@@ -4961,10 +6948,12 @@ export {
4961
6948
  categoryOf,
4962
6949
  checkedDown,
4963
6950
  comboIndex,
6951
+ compressRanges,
4964
6952
  createRun,
4965
6953
  defineSpot,
4966
6954
  evaluate,
4967
6955
  evaluateCards,
6956
+ exploitabilityInExact,
4968
6957
  formatCard,
4969
6958
  formatCards,
4970
6959
  formatCombo,
@@ -4974,6 +6963,7 @@ export {
4974
6963
  litePreset,
4975
6964
  makeRegretStore,
4976
6965
  makeSumStore,
6966
+ openLite,
4977
6967
  parseCard,
4978
6968
  parseCards,
4979
6969
  parseRange,
@@ -4981,10 +6971,12 @@ export {
4981
6971
  rangeWeight,
4982
6972
  rankOf,
4983
6973
  rankSwap,
6974
+ releaseSetupCache,
4984
6975
  resolveSubgame,
4985
6976
  rootPlay,
4986
6977
  rootPlayMovement,
4987
6978
  rootPlayNodes,
6979
+ runToStop,
4988
6980
  simdAvailable,
4989
6981
  solve,
4990
6982
  solveLite,
@@ -4994,4 +6986,25 @@ export {
4994
6986
  trackSettle,
4995
6987
  turnLineReach
4996
6988
  };
6989
+ /*!
6990
+ * Vendored from https://github.com/DarraghGeo/poker-rangecompress (dist/range-compress.js) by
6991
+ * scripts/vendor-range-compress.ts: an ES module, single-threaded. Do not edit here.
6992
+ *
6993
+ * range-compress.js — shrink a poker range for a postflop solver while keeping how the range plays.
6994
+ *
6995
+ * What it does: given a player's range, the opponent's range and a flop, it keeps a subset of the combos
6996
+ * and re-weights them so that, on every turn and river the solver will deal, the range still has the same
6997
+ * distribution of hand strength. The result is an ordinary range (combos with weights 0..1).
6998
+ *
6999
+ * What it preserves: how often the range as a whole takes each action, and how its strong / medium / weak
7000
+ * parts act. What it does not preserve: what an individual combo does (see README).
7001
+ *
7002
+ * No dependencies. Works in browsers (global `RangeCompress`), web workers and Node (CommonJS).
7003
+ * Cards are 4*rank+suit with rank 0..12 = 2..A and suit 0..3 = c,d,h,s.
7004
+ *
7005
+ * Speed notes (v2): hands are never evaluated one by one. On each board the 91 rank classes are valued once
7006
+ * from rank-count bit masks (the suit-lane idea of poker-bitvaljs), flushes are patched in from a 13-bit
7007
+ * lane table, equities with exact card removal come from per-card prefix tables instead of sorting, and
7008
+ * the linear algebra works on suit orbits with a Cholesky inverse and triangular updates.
7009
+ */
4997
7010
  //# sourceMappingURL=index.js.map