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/browser.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
+ }
1848
+ }
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;
1811
1866
  }
1812
- for (let m = memberStart[memberStart.length - 1]; m < members.length; m++) seen[members[m]] = 0;
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;
@@ -2746,6 +2778,8 @@ function threadAdvice(engine) {
2746
2778
  function spawnWorker(_setup, _onError) {
2747
2779
  throw new Error("The browser build threads only the WebAssembly engine; use workers: 1 with this solve");
2748
2780
  }
2781
+ function warmEngineThreads(_count) {
2782
+ }
2749
2783
  function spawnEngineWorker(setup, onError) {
2750
2784
  const threads = provider();
2751
2785
  if (!threads) throw new Error("No engine threads; call enableThreads() from poker-flopsolve/threads first");
@@ -2989,8 +3023,46 @@ function compiledStorage(source, kind) {
2989
3023
  if (!cache) storageModules.set(source, cache = { plain: void 0, shared: void 0 });
2990
3024
  return compileInto(cache, kind, source[kind]);
2991
3025
  }
3026
+ var PROFILE = { traversals: 0, collect: 1, override: 2, wait: 3, reduce: 4, run: 5, busy: 6 };
3027
+ var threadProfiles = /* @__PURE__ */ new WeakMap();
3028
+ function scheduleBytes(boards) {
3029
+ return Math.ceil(boards / 2) * 8 + 2 * boards * 8;
3030
+ }
3031
+ function scheduleViews(buffer, boards) {
3032
+ return {
3033
+ order: new Int32Array(buffer, 0, boards),
3034
+ cost: new Float64Array(buffer, Math.ceil(boards / 2) * 8, 2 * boards)
3035
+ };
3036
+ }
3037
+ var TOUCH_STEP = 4096;
3038
+ function touchShares(ranges, shares) {
3039
+ const total = ranges.reduce((sum, [from, to]) => sum + (to - from), 0);
3040
+ const each = Math.ceil(total / shares / TOUCH_STEP) * TOUCH_STEP;
3041
+ const out = Array.from({ length: shares }, () => []);
3042
+ let share = 0;
3043
+ let room = each;
3044
+ for (const [start, to] of ranges) {
3045
+ let from = start;
3046
+ while (from < to) {
3047
+ const take = Math.min(room, to - from);
3048
+ out[share].push(from, from + take);
3049
+ from += take;
3050
+ room -= take;
3051
+ if (room === 0 && share < shares - 1) {
3052
+ share++;
3053
+ room = each;
3054
+ }
3055
+ }
3056
+ }
3057
+ return out;
3058
+ }
3059
+ function touchStorage(bytes, share) {
3060
+ for (let r = 0; r < share.length; r += 2) {
3061
+ for (let at = share[r]; at < share[r + 1]; at += TOUCH_STEP) bytes[at] = 0;
3062
+ }
3063
+ }
2992
3064
  var MAX_MEMORY = 4294901760;
2993
- var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 };
3065
+ var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, next: 7, size: 8 };
2994
3066
  function createEngine(input, pool) {
2995
3067
  const shared = pool !== void 0;
2996
3068
  const storage = input.storage ?? null;
@@ -3013,15 +3085,16 @@ function createEngine(input, pool) {
3013
3085
  const [upRound, upStart] = flatten(hands.upStart);
3014
3086
  const [childRound, childStart] = flatten(runouts.childStart);
3015
3087
  const [orbitRound, orbitStart] = flatten(runouts.orbitStart);
3016
- const maxCount = Math.max(4, ...active.count);
3088
+ let maxCount = 4;
3089
+ for (let i = 0; i < active.count.length; i++) if (active.count[i] > maxCount) maxCount = active.count[i];
3017
3090
  const stride = Math.ceil(maxCount / 4) * 4;
3018
3091
  const maxActions = Math.max(1, layout.maxActions);
3019
3092
  const depths = treeDepth2(tree) + 2;
3020
3093
  const rowBytes = stride * 4;
3021
3094
  const depthBytes = rowBytes * (3 + 2 * maxActions);
3022
3095
  const pieces = [];
3023
- const add = (data, bytes2 = data ? data.byteLength : 0) => {
3024
- pieces.push({ data, bytes: Math.ceil(Math.max(bytes2, 4) / 16) * 16 });
3096
+ const add = (data, bytes2 = data ? data.byteLength : 0, empty = data === null) => {
3097
+ pieces.push({ data, bytes: Math.ceil(Math.max(bytes2, 4) / 16) * 16, empty });
3025
3098
  return pieces.length - 1;
3026
3099
  };
3027
3100
  const common = [
@@ -3036,12 +3109,12 @@ function createEngine(input, pool) {
3036
3109
  add(layout.rowStart),
3037
3110
  add(active.roundBase),
3038
3111
  add(active.start),
3039
- add(Int32Array.from(active.count)),
3112
+ add(new Int32Array(active.count)),
3040
3113
  add(active.cardA),
3041
3114
  add(active.cardB),
3042
3115
  add(active.strength),
3043
3116
  add(active.packed),
3044
- add(Float32Array.from(active.multiplicity)),
3117
+ add(new Float32Array(active.multiplicity)),
3045
3118
  add(active.memberStart),
3046
3119
  add(active.memberA),
3047
3120
  add(active.memberB),
@@ -3067,13 +3140,13 @@ function createEngine(input, pool) {
3067
3140
  cardSums: add(null, 52 * 8 + stride * 8),
3068
3141
  rootMe: add(null, rowBytes),
3069
3142
  rootOpp: add(null, rowBytes),
3070
- header: add(null, 40 * 4)
3143
+ header: add(null, 40 * 4, false)
3071
3144
  }));
3072
3145
  const entries = pool ? pool.plan.entryNodes.length : 0;
3073
3146
  const entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;
3074
3147
  const reach = pool ? add(null, entries * 2 * rowBytes) : -1;
3075
3148
  const values = pool ? add(null, entries * rowBytes) : -1;
3076
- const partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;
3149
+ const boardValues = pool ? add(null, pool.plan.boards * entries * rowBytes) : -1;
3077
3150
  const plan = input.sampling;
3078
3151
  const sample = plan ? {
3079
3152
  baseOffset: add(plan.baseOffset),
@@ -3091,13 +3164,13 @@ function createEngine(input, pool) {
3091
3164
  } : null;
3092
3165
  const chunks = compact ? layout.chunkSlots.length : 0;
3093
3166
  const stored = storage ? {
3094
- block: add(null, 128),
3167
+ block: add(null, 128, false),
3095
3168
  blockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),
3096
3169
  regretScale: quantised ? add(null, layout.blocks * 8) : -1,
3097
3170
  sumScale: quantised ? add(null, layout.blocks * 8) : -1,
3098
3171
  compactChunk: compact ? add(layout.compactChunk) : -1,
3099
- handOffset: compact ? add(Int32Array.from(layout.handOffset)) : -1,
3100
- tables: compact ? add(null, chunks * 4 * 5) : -1,
3172
+ handOffset: compact ? add(new Int32Array(layout.handOffset)) : -1,
3173
+ tables: compact ? add(null, chunks * 4 * 5, false) : -1,
3101
3174
  regrets: layout.chunkSlots.map((slots) => add(null, slots * (compact.float ? 4 : 1))),
3102
3175
  shifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],
3103
3176
  sums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],
@@ -3117,6 +3190,10 @@ function createEngine(input, pool) {
3117
3190
  pieces.forEach((piece, i) => {
3118
3191
  if (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);
3119
3192
  });
3193
+ const touch = touchShares(
3194
+ pieces.flatMap((piece, i) => piece.empty && piece.bytes >= 16 * TOUCH_STEP ? [[offsets[i], offsets[i] + piece.bytes]] : []),
3195
+ threads
3196
+ );
3120
3197
  for (const mine of own) {
3121
3198
  const head = new Uint32Array(memory.buffer, offsets[mine.header], 40);
3122
3199
  common.forEach((slot, i) => head[i] = offsets[slot]);
@@ -3221,14 +3298,22 @@ function createEngine(input, pool) {
3221
3298
  };
3222
3299
  let control = null;
3223
3300
  let settings = null;
3301
+ let profile = null;
3302
+ let schedule = null;
3224
3303
  const workers = [];
3225
3304
  let failure = null;
3305
+ if (!pool) touchStorage(bytes, touch[0]);
3226
3306
  if (pool) {
3227
3307
  const plan2 = pool.plan;
3228
3308
  const controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);
3229
3309
  const settingsBuffer = new SharedArrayBuffer(8 * 8);
3230
3310
  control = new Int32Array(controlBuffer);
3231
3311
  settings = new Float64Array(settingsBuffer);
3312
+ const profileBuffer = new SharedArrayBuffer(8 * (PROFILE.busy + threads));
3313
+ profile = new Float64Array(profileBuffer);
3314
+ const scheduleBuffer = new SharedArrayBuffer(scheduleBytes(plan2.boards));
3315
+ schedule = scheduleViews(scheduleBuffer, plan2.boards);
3316
+ for (let i = 0; i < plan2.boards; i++) schedule.order[i] = i;
3232
3317
  exports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);
3233
3318
  for (let w = 1; w < threads; w++) {
3234
3319
  const setup = {
@@ -3237,17 +3322,20 @@ function createEngine(input, pool) {
3237
3322
  header: offsets[own[w].header],
3238
3323
  maxActions,
3239
3324
  exchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],
3240
- shard: [plan2.round, plan2.bounds[w], plan2.bounds[w + 1]],
3325
+ shard: [plan2.round, plan2.boards],
3241
3326
  entryNodes: plan2.entryNodes,
3242
3327
  rootMe: offsets[own[w].rootMe],
3243
3328
  rootOpp: offsets[own[w].rootOpp],
3244
- partial: offsets[partials] + (w - 1) * entries * rowBytes,
3329
+ boardValues: offsets[boardValues],
3330
+ schedule: scheduleBuffer,
3245
3331
  stride,
3246
3332
  control: controlBuffer,
3247
3333
  settings: settingsBuffer,
3248
3334
  ...share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] } : {},
3249
3335
  ...stored ? { storage: true } : {},
3250
- ...samplingArgs ? { sampling: samplingArgs } : {}
3336
+ ...samplingArgs ? { sampling: samplingArgs } : {},
3337
+ profile: [profileBuffer, PROFILE.busy + w],
3338
+ touch: touch[w]
3251
3339
  };
3252
3340
  workers.push(pool.spawn(setup, (error) => {
3253
3341
  failure ??= error;
@@ -3257,6 +3345,7 @@ function createEngine(input, pool) {
3257
3345
  Atomics.notify(control, ENGINE_CONTROL.ready);
3258
3346
  }));
3259
3347
  }
3348
+ touchStorage(bytes, touch[0]);
3260
3349
  const deadline = Date.now() + WORKER_START_MS;
3261
3350
  for (; ; ) {
3262
3351
  const ready = Atomics.load(control, ENGINE_CONTROL.ready);
@@ -3311,25 +3400,41 @@ function createEngine(input, pool) {
3311
3400
  };
3312
3401
  const runThreaded = (mode, traverser, apply, positive, negative, sum, weight, clamp) => {
3313
3402
  const plan2 = pool.plan;
3403
+ const { order, cost } = schedule;
3404
+ const clock = performance.now();
3314
3405
  exports.setShard(plan2.round, 0, 0);
3315
3406
  exports.setPhase(1, 0);
3316
3407
  exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);
3408
+ const collected = performance.now();
3409
+ const costs = cost.subarray(traverser * plan2.boards, (traverser + 1) * plan2.boards);
3410
+ const timed = mode === Mode.Train && apply === 1;
3411
+ order.sort((a, b) => costs[b] - costs[a] || a - b);
3317
3412
  settings.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);
3318
3413
  Atomics.store(control, ENGINE_CONTROL.done, 0);
3414
+ Atomics.store(control, ENGINE_CONTROL.next, 0);
3319
3415
  Atomics.store(control, ENGINE_CONTROL.mode, mode);
3320
3416
  Atomics.store(control, ENGINE_CONTROL.traverser, traverser);
3321
3417
  Atomics.store(control, ENGINE_CONTROL.command, 0);
3322
3418
  Atomics.add(control, ENGINE_CONTROL.generation, 1);
3323
3419
  Atomics.notify(control, ENGINE_CONTROL.generation);
3324
3420
  const dispatched = performance.now();
3325
- exports.setShard(plan2.round, plan2.bounds[0], plan2.bounds[1]);
3326
3421
  exports.setPhase(0, apply);
3327
- const valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);
3328
- for (let entry = 0; entry < entries; entry++) {
3329
- const slot = offsets[reach] + entry * 2 * rowBytes;
3330
- const out = exports.runChance(mode, traverser, plan2.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 0;
3331
- valueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);
3422
+ const heap = new Float32Array(memory.buffer);
3423
+ const into = offsets[boardValues] >>> 2;
3424
+ for (; ; ) {
3425
+ const taken = Atomics.add(control, ENGINE_CONTROL.next, 1);
3426
+ if (taken >= plan2.boards) break;
3427
+ const board = order[taken];
3428
+ exports.setShard(plan2.round, board, board + 1);
3429
+ const started = performance.now();
3430
+ for (let entry = 0; entry < entries; entry++) {
3431
+ const slot = offsets[reach] + entry * 2 * rowBytes;
3432
+ const out = exports.runChance(mode, traverser, plan2.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 2;
3433
+ heap.copyWithin(into + (board * entries + entry) * stride, out, out + stride);
3434
+ }
3435
+ if (timed) costs[board] = performance.now() - started;
3332
3436
  }
3437
+ const walked = performance.now();
3333
3438
  failure ??= awaitThreads(
3334
3439
  control,
3335
3440
  ENGINE_CONTROL.done,
@@ -3340,15 +3445,28 @@ function createEngine(input, pool) {
3340
3445
  );
3341
3446
  const dead = failed();
3342
3447
  if (dead) throw dead;
3343
- const partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);
3344
- for (let w = 0; w < threads - 1; w++) {
3345
- for (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];
3448
+ const waited = performance.now();
3449
+ const valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);
3450
+ valueView.fill(0);
3451
+ for (let board = 0; board < plan2.boards; board++) {
3452
+ const rows = into + board * entries * stride;
3453
+ for (let i = 0; i < entries * stride; i++) valueView[i] += heap[rows + i];
3346
3454
  }
3455
+ const reduced = performance.now();
3347
3456
  exports.setShard(plan2.round, 0, 0);
3348
3457
  exports.setPhase(2, apply);
3349
3458
  const at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;
3350
3459
  exports.setPhase(0, 1);
3351
3460
  exports.setShard(-1, 0, 0);
3461
+ const p = profile;
3462
+ const finished = performance.now();
3463
+ p[PROFILE.traversals]++;
3464
+ p[PROFILE.collect] += collected - clock;
3465
+ p[PROFILE.busy] += walked - dispatched;
3466
+ p[PROFILE.wait] += waited - walked;
3467
+ p[PROFILE.reduce] += reduced - waited;
3468
+ p[PROFILE.override] += finished - reduced;
3469
+ p[PROFILE.run] += finished - clock;
3352
3470
  return at;
3353
3471
  };
3354
3472
  return {
@@ -3360,6 +3478,7 @@ function createEngine(input, pool) {
3360
3478
  sampling: samplingViews,
3361
3479
  discounted,
3362
3480
  threads,
3481
+ profile,
3363
3482
  root(dcfr) {
3364
3483
  return (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);
3365
3484
  },
@@ -3519,70 +3638,119 @@ function warmStart(to, from, averages, cards, tolerance = SIZE_TOLERANCE) {
3519
3638
  const newSum = new Float64Array(width);
3520
3639
  const keepsRegrets = (ctx) => ctx.regret.length > 0 || (ctx.compactRegret ?? null) !== null;
3521
3640
  const hasRegret = keepsRegrets(to) && keepsRegrets(from);
3522
- const position = new Int32Array(COMBOS).fill(-1);
3641
+ const rounds = to.runouts.rounds;
3642
+ const nodesOf = Array.from({ length: rounds * 2 }, () => []);
3643
+ const actionsOf = /* @__PURE__ */ new Map();
3523
3644
  let matched = 0;
3524
3645
  for (const node of tree.decisionNodes) {
3525
3646
  const old = match[node];
3526
3647
  if (old < 0) continue;
3527
3648
  matched++;
3528
- const round = tree.round[node];
3529
- const owner = tree.player[node];
3530
3649
  const actions = tree.numEdges[node];
3531
- const oldActions = from.tree.numEdges[old];
3532
3650
  const actionOf = new Int32Array(actions).fill(-1);
3533
3651
  for (let e = 0; e < actions; e++) {
3534
3652
  const other = matchEdge(tree, tree.firstEdge[node] + e, node, from.tree, old, tolerance);
3535
3653
  if (other >= 0) actionOf[e] = other - from.tree.firstEdge[old];
3536
3654
  }
3655
+ actionsOf.set(node, actionOf);
3656
+ nodesOf[tree.round[node] * 2 + tree.player[node]].push(node);
3657
+ }
3658
+ const position = new Int32Array(COMBOS).fill(-1);
3659
+ const sourceOf = new Int32Array(COMBOS);
3660
+ const sourceEnd = new Int32Array(COMBOS);
3661
+ for (let round = 0; round < rounds; round++) {
3662
+ if (nodesOf[round * 2].length + nodesOf[round * 2 + 1].length === 0) continue;
3537
3663
  for (let board = 0; board < to.runouts.counts[round]; board++) {
3538
3664
  const resolved = resolveBoard(from.runouts, asSource(realCards(to.runouts, round, board)));
3539
- const oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;
3540
- const oldFrom = from.active.start[oldSlot];
3541
- const oldCount = from.active.count[oldSlot];
3542
- const oldBlock = from.layout.blockOffset[old] + resolved.board;
3543
- const oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];
3544
- const oldLength = oldActions * oldCount;
3545
- if (round >= from.layout.compactFrom) {
3546
- readCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);
3547
- } else {
3548
- if (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);
3549
- readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);
3550
- }
3551
- markMembers(from.active, oldFrom, oldCount, position, false);
3552
- const newSlot = (to.active.roundBase[round] + board) * 2 + owner;
3553
- const newFrom = to.active.start[newSlot];
3554
- const count = to.active.count[newSlot];
3555
- const length = actions * count;
3556
- newRegret.fill(0, 0, length);
3557
- newSum.fill(0, 0, length);
3558
- for (let i = 0; i < count; i++) {
3559
- const firstMember = to.active.memberStart[newFrom + i];
3560
- const membersEnd = to.active.memberStart[newFrom + i + 1];
3561
- const share = 1 / (membersEnd - firstMember);
3562
- for (let m = firstMember; m < membersEnd; m++) {
3563
- const j = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];
3564
- if (j < 0) continue;
3665
+ for (let owner = 0; owner < 2; owner++) {
3666
+ const nodes = nodesOf[round * 2 + owner];
3667
+ if (nodes.length === 0) continue;
3668
+ const oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;
3669
+ const oldFrom = from.active.start[oldSlot];
3670
+ const oldCount = from.active.count[oldSlot];
3671
+ const newSlot = (to.active.roundBase[round] + board) * 2 + owner;
3672
+ const newFrom = to.active.start[newSlot];
3673
+ const count = to.active.count[newSlot];
3674
+ markMembers(from.active, oldFrom, oldCount, position, false);
3675
+ let sources = 0;
3676
+ for (let i = 0; i < count; i++) {
3677
+ for (let m = to.active.memberStart[newFrom + i]; m < to.active.memberStart[newFrom + i + 1]; m++) {
3678
+ sourceOf[sources++] = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];
3679
+ }
3680
+ sourceEnd[i] = sources;
3681
+ }
3682
+ markMembers(from.active, oldFrom, oldCount, position, true);
3683
+ const direct = sources === count && round < from.layout.compactFrom && round < to.layout.compactFrom && from.regretScale === null && to.regretScale === null;
3684
+ for (const node of nodes) {
3685
+ const old = match[node];
3686
+ const actions = tree.numEdges[node];
3687
+ const oldActions = from.tree.numEdges[old];
3688
+ const actionOf = actionsOf.get(node);
3689
+ const oldBlock = from.layout.blockOffset[old] + resolved.board;
3690
+ const oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];
3691
+ const oldLength = oldActions * oldCount;
3692
+ if (direct) {
3693
+ const base2 = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3694
+ if (hasRegret) copyRows(to.regret, base2, from.regret, oldBase, actionOf, count, oldCount, sourceOf);
3695
+ if (averages) copyRows(to.strategySum, base2, from.strategySum, oldBase, actionOf, count, oldCount, sourceOf);
3696
+ continue;
3697
+ }
3698
+ if (round >= from.layout.compactFrom) {
3699
+ readCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);
3700
+ } else {
3701
+ if (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);
3702
+ if (averages) readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);
3703
+ }
3704
+ const length = actions * count;
3705
+ newRegret.fill(0, 0, length);
3706
+ if (averages) newSum.fill(0, 0, length);
3565
3707
  for (let e = 0; e < actions; e++) {
3566
3708
  const action = actionOf[e];
3567
3709
  if (action < 0) continue;
3568
- newRegret[e * count + i] += share * oldRegret[action * oldCount + j];
3569
- newSum[e * count + i] += share * oldSum[action * oldCount + j];
3710
+ const row = e * count;
3711
+ const oldRow = action * oldCount;
3712
+ let first = 0;
3713
+ for (let i = 0; i < count; i++) {
3714
+ const end = sourceEnd[i];
3715
+ const share = 1 / (end - first);
3716
+ for (let k = first; k < end; k++) {
3717
+ const j = sourceOf[k];
3718
+ if (j < 0) continue;
3719
+ if (hasRegret) newRegret[row + i] += share * oldRegret[oldRow + j];
3720
+ if (averages) newSum[row + i] += share * oldSum[oldRow + j];
3721
+ }
3722
+ first = end;
3723
+ }
3724
+ }
3725
+ const block = to.layout.blockOffset[node] + board;
3726
+ const base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3727
+ if (round >= to.layout.compactFrom) {
3728
+ writeCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);
3729
+ } else {
3730
+ if (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS2, block, base, length, newRegret);
3731
+ if (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS2, block, base, length, newSum);
3570
3732
  }
3571
3733
  }
3572
3734
  }
3573
- markMembers(from.active, oldFrom, oldCount, position, true);
3574
- const block = to.layout.blockOffset[node] + board;
3575
- const base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3576
- if (round >= to.layout.compactFrom) {
3577
- writeCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);
3578
- } else {
3579
- if (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS2, block, base, length, newRegret);
3580
- if (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS2, block, base, length, newSum);
3581
- }
3582
3735
  }
3583
3736
  }
3584
3737
  return { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };
3585
3738
  }
3739
+ function copyRows(to, base, from, oldBase, actionOf, count, oldCount, sourceOf) {
3740
+ for (let e = 0; e < actionOf.length; e++) {
3741
+ const action = actionOf[e];
3742
+ const row = base + e * count;
3743
+ if (action < 0) {
3744
+ to.fill(0, row, row + count);
3745
+ continue;
3746
+ }
3747
+ const oldRow = oldBase + action * oldCount;
3748
+ for (let i = 0; i < count; i++) {
3749
+ const j = sourceOf[i];
3750
+ to[row + i] = j < 0 ? 0 : from[oldRow + j];
3751
+ }
3752
+ }
3753
+ }
3586
3754
  function checkRelabelling(cards, a, b) {
3587
3755
  const seen = new Uint8Array(DECK);
3588
3756
  if (cards.length !== DECK) throw new Error(`A card relabelling maps all ${DECK} cards; got ${cards.length}`);
@@ -3912,6 +4080,1473 @@ function linesWithin(solution, maxBytes, options = {}) {
3912
4080
  return lines(low);
3913
4081
  }
3914
4082
 
4083
+ // src/vendor/range-compress.js
4084
+ function factory() {
4085
+ const RANKS2 = "23456789TJQKA", SUITS2 = "cdhs";
4086
+ const cardFromStr = (s) => RANKS2.indexOf(s[0]) * 4 + SUITS2.indexOf(s[1]);
4087
+ const cardToStr = (c) => RANKS2[c >> 2] + SUITS2[c & 3];
4088
+ const handToStr = (a, b) => a > b ? cardToStr(a) + cardToStr(b) : cardToStr(b) + cardToStr(a);
4089
+ const hid = (h) => h.a * 52 + h.b;
4090
+ const cls = (h) => {
4091
+ const r1 = h.a >> 2, r2 = h.b >> 2, hi = Math.max(r1, r2), lo = Math.min(r1, r2);
4092
+ return (h.a & 3) === (h.b & 3) ? hi * 13 + lo : lo * 13 + hi;
4093
+ };
4094
+ function parseRange2(text) {
4095
+ const out = /* @__PURE__ */ new Map();
4096
+ const re = /\[(\d+(?:\.\d+)?)\]([^\[]*)\[\/\1\]|([^\[\],\s]+)/g;
4097
+ let m;
4098
+ const add = (tok, w) => {
4099
+ tok = tok.trim();
4100
+ if (!tok) return;
4101
+ if (tok.length !== 4) throw new Error("unsupported token " + tok);
4102
+ let a = cardFromStr(tok.slice(0, 2)), b = cardFromStr(tok.slice(2, 4));
4103
+ if (a > b) {
4104
+ const t = a;
4105
+ a = b;
4106
+ b = t;
4107
+ }
4108
+ out.set(a * 52 + b, { a, b, w });
4109
+ };
4110
+ while (m = re.exec(text)) {
4111
+ if (m[2] !== void 0) {
4112
+ const w = parseFloat(m[1]) / 100;
4113
+ const parts = m[2].split(",");
4114
+ for (let i = 0; i < parts.length; i++) add(parts[i], w);
4115
+ } else add(m[3], 1);
4116
+ }
4117
+ return [...out.values()].filter((h) => h.w > 0).sort((x, y) => x.a - y.a || x.b - y.b);
4118
+ }
4119
+ function rangeToString(hands) {
4120
+ const groups = /* @__PURE__ */ new Map();
4121
+ for (const h of hands) {
4122
+ const k = (Math.round(h.w * 1e4) / 100).toFixed(2);
4123
+ if (!groups.has(k)) groups.set(k, []);
4124
+ groups.get(k).push(handToStr(h.a, h.b));
4125
+ }
4126
+ const parts = [];
4127
+ for (const [k, v] of [...groups.entries()].sort((x, y) => x[0] - y[0])) {
4128
+ if (k === "100.00") parts.push(v.join(", "));
4129
+ else parts.unshift("[" + k + "]" + v.join(", ") + "[/" + k + "]");
4130
+ }
4131
+ return parts.join(", ");
4132
+ }
4133
+ const KERNELS_B64 = "AGFzbQEAAAABQAdgBH9/f38Bf2AHf39/f39/fwF/YAV/f39/fwF/YAV/f39/fwBgBH9/f38AYAF/AGANf39/f39/f39/f39/fAACDwEDZW52Bm1lbW9yeQIAAAMIBwABAgMEBQYGEAN/AUEAC38BQQALfwFBAAsHSwcJaW52ZXJ0U1BEAAQHb2JzUGljawACCW9ic1JlbW92ZQABCGFkZFN0YXRlAAYEbm5scwADCmVxdWl0eVBhc3MABQZtZW1vcnkCAArJNgelAwEBfyADBEBBHyADZ2siAUEQdEGAgMADckEfIABBfiABd3Fna0EMdHIPCyABIAJBf3NxIQEgAgRAIAJBfkEfIAJnayICd3EiAwRAIAJBEHRBgICAA3JBHyADZ2tBDHRyDwsgAQRAIAJBEHRBgICAA3JBHyABZ2tBDHRyDwsjASAAaiwAACIBQQBOBEAgAUEQdEGAgIACcg8LIAJBEHRBgIDAAXJBHyAAQX4gAndxIgBnayIBQQx0ckEf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gCCAOQQJ0aiATQQFqNgIACwsLIA9BAWohDwwBCwsDQCAEIBBKBEAgBSAQbCIAIAggEEECdGooAgBqIQIDQCAAIAJIBEAgCiAGIABBAnRqKAIAIgFBA3RqIgMgAysDACAHIABBA3RqKwMAIhQgDKIiFSAUoqA5AwAgCSABIAtsQQN0aiEDIABBAWohAQNAIAEgAkgEQCADIAYgAUECdGooAgBBA3RqIg0gDSsDACAVIAcgAUEDdGorAwCioDkDACABQQFqIQEMAQsLIABBAWohAAwBCwsgEEEBaiEQDAELCws=";
4134
+ let WK = null, arena = false, wasmOn = true, wasmP = null;
4135
+ const FULL = { full: true };
4136
+ function wasm3() {
4137
+ if (WK !== null) return WK;
4138
+ WK = false;
4139
+ if (!KERNELS_B64 || typeof WebAssembly === "undefined") return WK;
4140
+ let bin, mem, imports;
4141
+ const setup = (inst) => {
4142
+ new Uint8Array(mem.buffer, 16384, 8192).set(POPC);
4143
+ new Int8Array(mem.buffer, 16384 + 8192, 8192).set(STRT);
4144
+ new Int32Array(mem.buffer, 16384 + 16384, 8192).set(FLUSHV);
4145
+ return { mem, ex: inst.exports, top: 65536, limit: 0, buf: null, tab: 16384 };
4146
+ };
4147
+ try {
4148
+ bin = typeof atob === "function" ? Uint8Array.from(atob(KERNELS_B64), (c) => c.charCodeAt(0)) : new Uint8Array(Buffer.from(KERNELS_B64, "base64"));
4149
+ mem = new WebAssembly.Memory({ initial: 64 });
4150
+ imports = { env: { memory: mem, abort() {
4151
+ } } };
4152
+ WK = setup(new WebAssembly.Instance(new WebAssembly.Module(bin), imports));
4153
+ } catch (e) {
4154
+ WK = false;
4155
+ try {
4156
+ if (bin && mem) wasmP = WebAssembly.instantiate(bin, imports).then((r) => {
4157
+ WK = setup(r.instance);
4158
+ return true;
4159
+ }, () => false);
4160
+ } catch (e2) {
4161
+ wasmP = null;
4162
+ }
4163
+ }
4164
+ return WK;
4165
+ }
4166
+ function releaseMemory() {
4167
+ if (!arena) {
4168
+ WK = null;
4169
+ wasmP = null;
4170
+ }
4171
+ }
4172
+ function ready() {
4173
+ const w = wasm3();
4174
+ return w ? Promise.resolve(true) : wasmP || Promise.resolve(false);
4175
+ }
4176
+ function withArena(bytes, fn) {
4177
+ const w = wasmOn && !arena ? wasm3() : false;
4178
+ if (!w) return fn();
4179
+ try {
4180
+ const need = 65536 + bytes, have = w.mem.buffer.byteLength;
4181
+ if (need > have) w.mem.grow(Math.ceil((need - have) / 65536));
4182
+ w.top = 65536;
4183
+ w.buf = w.mem.buffer;
4184
+ w.limit = w.buf.byteLength;
4185
+ arena = true;
4186
+ return fn();
4187
+ } catch (e) {
4188
+ if (e !== FULL) throw e;
4189
+ arena = false;
4190
+ return fn();
4191
+ } finally {
4192
+ arena = false;
4193
+ }
4194
+ }
4195
+ function mk(Type, n, zero) {
4196
+ if (!arena) return new Type(n);
4197
+ const p = WK.top + 15 & ~15, bytes = n * Type.BYTES_PER_ELEMENT;
4198
+ if (p + bytes > WK.limit) throw FULL;
4199
+ WK.top = p + bytes;
4200
+ const a = new Type(WK.buf, p, n);
4201
+ if (zero) a.fill(0);
4202
+ return a;
4203
+ }
4204
+ const inW = (a) => arena && a.buffer === WK.buf;
4205
+ const POPC = new Uint8Array(8192), STRT = new Int8Array(8192).fill(-1), FLUSHV = new Int32Array(8192);
4206
+ const top5 = (m) => {
4207
+ let v = 0;
4208
+ for (let sh = 16; sh >= 0; sh -= 4) {
4209
+ const r = 31 - Math.clz32(m);
4210
+ v |= r << sh;
4211
+ m &= ~(1 << r);
4212
+ }
4213
+ return v;
4214
+ };
4215
+ for (let m = 1; m < 8192; m++) {
4216
+ POPC[m] = POPC[m >> 1] + (m & 1);
4217
+ for (let hi = 12; hi >= 4; hi--) if ((m >> hi - 4 & 31) === 31) {
4218
+ STRT[m] = hi;
4219
+ break;
4220
+ }
4221
+ if (STRT[m] < 0 && (m & 4111) === 4111) STRT[m] = 3;
4222
+ }
4223
+ 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);
4224
+ function rankEval(m1, m2, m3, m4) {
4225
+ if (m4) {
4226
+ const q = 31 - Math.clz32(m4);
4227
+ return 7 << 20 | q << 16 | 31 - Math.clz32(m1 & ~(1 << q)) << 12;
4228
+ }
4229
+ const pairs = m2 & ~m3;
4230
+ if (m3) {
4231
+ const t = 31 - Math.clz32(m3);
4232
+ const rest = m3 & ~(1 << t);
4233
+ if (rest) return 6 << 20 | t << 16 | 31 - Math.clz32(rest) << 12;
4234
+ if (pairs) return 6 << 20 | t << 16 | 31 - Math.clz32(pairs) << 12;
4235
+ const st2 = STRT[m1];
4236
+ if (st2 >= 0) return 4 << 20 | st2 << 16;
4237
+ let r = m1 & ~(1 << t);
4238
+ const k1 = 31 - Math.clz32(r);
4239
+ r &= ~(1 << k1);
4240
+ return 3 << 20 | t << 16 | k1 << 12 | 31 - Math.clz32(r) << 8;
4241
+ }
4242
+ const st = STRT[m1];
4243
+ if (st >= 0) return 4 << 20 | st << 16;
4244
+ if (pairs) {
4245
+ const p1 = 31 - Math.clz32(pairs);
4246
+ const rest = pairs & ~(1 << p1);
4247
+ if (rest) {
4248
+ const p2 = 31 - Math.clz32(rest);
4249
+ return 2 << 20 | p1 << 16 | p2 << 12 | 31 - Math.clz32(m1 & ~(1 << p1) & ~(1 << p2)) << 8;
4250
+ }
4251
+ let r = m1 & ~(1 << p1);
4252
+ const k1 = 31 - Math.clz32(r);
4253
+ r &= ~(1 << k1);
4254
+ const k2 = 31 - Math.clz32(r);
4255
+ r &= ~(1 << k2);
4256
+ return 1 << 20 | p1 << 16 | k1 << 12 | k2 << 8 | 31 - Math.clz32(r) << 4;
4257
+ }
4258
+ return top5(m1);
4259
+ }
4260
+ function eval7(c0, c1, c2, c3, c4, c5, c6) {
4261
+ const cs = [c0, c1, c2, c3, c4, c5, c6];
4262
+ const lane = [0, 0, 0, 0];
4263
+ let m1 = 0, m2 = 0, m3 = 0, m4 = 0;
4264
+ for (const c of cs) {
4265
+ const bit = 1 << (c >> 2);
4266
+ lane[c & 3] |= bit;
4267
+ if (m3 & bit) m4 |= bit;
4268
+ else if (m2 & bit) m3 |= bit;
4269
+ else if (m1 & bit) m2 |= bit;
4270
+ else m1 |= bit;
4271
+ }
4272
+ let v = rankEval(m1, m2, m3, m4);
4273
+ for (let s = 0; s < 4; s++) if (POPC[lane[s]] >= 5 && FLUSHV[lane[s]] > v) v = FLUSHV[lane[s]];
4274
+ return v;
4275
+ }
4276
+ function deckStates(flop, blankMask = 0) {
4277
+ if (flop.length > 3) {
4278
+ if (blankMask) throw new Error("blankSuits is only for a three-card flop");
4279
+ const base = flop.slice(0, 3), fixed = flop.slice(3), rivers2 = [];
4280
+ if (fixed.length === 2) rivers2.push([Math.min(fixed[0], fixed[1]), Math.max(fixed[0], fixed[1]), 1]);
4281
+ 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]);
4282
+ return { rivers: rivers2, turns: [], blankMask: 0, base, fixed };
4283
+ }
4284
+ const fm = new Set(flop);
4285
+ const blank = (s) => blankMask >> s & 1;
4286
+ const fc = [0, 0, 0, 0];
4287
+ flop.forEach((c) => fc[c & 3]++);
4288
+ const pri = [0, 1, 2, 3].filter(blank).sort((x, y) => fc[x] - fc[y] || x - y);
4289
+ const proxy = (card, dead) => {
4290
+ if (!blank(card & 3)) return card;
4291
+ for (const s of pri) {
4292
+ const c = card & ~3 | s;
4293
+ if (!dead.has(c)) return c;
4294
+ }
4295
+ throw new Error("no proxy");
4296
+ };
4297
+ const tw = /* @__PURE__ */ new Map();
4298
+ for (let x = 0; x < 52; x++) if (!fm.has(x)) {
4299
+ const t = proxy(x, fm);
4300
+ tw.set(t, (tw.get(t) || 0) + 1);
4301
+ }
4302
+ const rivers = [], rIdx = /* @__PURE__ */ new Map(), turns = [];
4303
+ for (const [t, wt] of tw) {
4304
+ const dead = new Set(flop);
4305
+ dead.add(t);
4306
+ const rw = /* @__PURE__ */ new Map();
4307
+ for (let y = 0; y < 52; y++) if (!dead.has(y)) {
4308
+ const u = proxy(y, dead);
4309
+ rw.set(u, (rw.get(u) || 0) + 1);
4310
+ }
4311
+ const rivs = [];
4312
+ for (const [u, wu] of rw) {
4313
+ const key = Math.min(t, u) * 52 + Math.max(t, u);
4314
+ if (!rIdx.has(key)) {
4315
+ rIdx.set(key, rivers.length);
4316
+ rivers.push([Math.min(t, u), Math.max(t, u), 0]);
4317
+ }
4318
+ const i = rIdx.get(key);
4319
+ rivers[i][2] += wt * wu;
4320
+ rivs.push([i, wu]);
4321
+ }
4322
+ turns.push({ card: t, w: wt, rivs });
4323
+ }
4324
+ return { rivers, turns, blankMask, base: flop, fixed: [] };
4325
+ }
4326
+ function dealtKey(st, k, p) {
4327
+ const r = st.rivers[k], fx = st.fixed;
4328
+ let a = -1, b = -1;
4329
+ for (let q = 0; q < 2; q++) {
4330
+ let c = r[q];
4331
+ if (fx.length && fx.includes(c)) continue;
4332
+ if (p) c = c & ~3 | p[c & 3];
4333
+ if (a < 0) a = c;
4334
+ else b = c;
4335
+ }
4336
+ return b < 0 ? a : a < b ? a * 52 + b + 52 : b * 52 + a + 52;
4337
+ }
4338
+ const DCAP = 91 + 64;
4339
+ function side(h, other, R, T, want) {
4340
+ const n = h.length;
4341
+ const o = /* @__PURE__ */ new Map();
4342
+ for (const x of other) o.set(hid(x), x.w);
4343
+ const s = {
4344
+ hands: h,
4345
+ n,
4346
+ want,
4347
+ ca: mk(Uint8Array, n),
4348
+ cb: mk(Uint8Array, n),
4349
+ cl: mk(Uint8Array, n),
4350
+ w: mk(Float64Array, n),
4351
+ same: mk(Float64Array, n),
4352
+ id: mk(Uint8Array, n),
4353
+ dd: mk(Uint8Array, n),
4354
+ start: mk(Int32Array, DCAP + 3),
4355
+ ord: mk(Int32Array, n),
4356
+ totC: mk(Float64Array, 52),
4357
+ tot: 0,
4358
+ E: want ? mk(Float32Array, R * n).fill(NaN) : null,
4359
+ fS: mk(Float64Array, n, true),
4360
+ fW: mk(Float64Array, n, true),
4361
+ tS: want ? mk(Float64Array, T * n, true) : null,
4362
+ tW: want ? mk(Float64Array, T * n, true) : null
4363
+ };
4364
+ for (let i = 0; i < n; i++) {
4365
+ const a = h[i].a, b = h[i].b;
4366
+ s.ca[i] = a;
4367
+ s.cb[i] = b;
4368
+ s.w[i] = h[i].w;
4369
+ s.same[i] = o.get(hid(h[i])) || 0;
4370
+ const r1 = a >> 2, r2 = b >> 2, hi = r1 > r2 ? r1 : r2, lo = r1 > r2 ? r2 : r1;
4371
+ s.cl[i] = hi * (hi + 1) / 2 + lo;
4372
+ }
4373
+ return s;
4374
+ }
4375
+ function equitiesBoth(hA, hB, flop, states, wantA = true, wantB = true, perms = null, only = null) {
4376
+ const R = states.rivers.length, T = states.turns.length;
4377
+ const S = [side(hA, hB, R, T, wantA), side(hB, hA, R, T, wantB)];
4378
+ const mir = [];
4379
+ if (perms && perms.length > 1) {
4380
+ const ridx = new Map(states.rivers.map((r, k) => [dealtKey(states, k), k]));
4381
+ for (const p of perms) {
4382
+ if (p[0] === 0 && p[1] === 1 && p[2] === 2 && p[3] === 3) continue;
4383
+ const bmap = mk(Int32Array, R);
4384
+ for (let k = 0; k < R; k++) bmap[k] = ridx.get(dealtKey(states, k, p));
4385
+ const hmap = S.map((s) => {
4386
+ const idx = new Map(s.hands.map((h, i) => [hid(h), i]));
4387
+ const out = mk(Int32Array, s.n);
4388
+ s.hands.forEach((h, i) => {
4389
+ let a = h.a & ~3 | p[h.a & 3], b = h.b & ~3 | p[h.b & 3];
4390
+ if (a > b) {
4391
+ const t = a;
4392
+ a = b;
4393
+ b = t;
4394
+ }
4395
+ out[i] = idx.get(a * 52 + b);
4396
+ });
4397
+ return out;
4398
+ });
4399
+ mir.push({ bmap, hmap });
4400
+ }
4401
+ }
4402
+ const done = mk(Uint8Array, R, true);
4403
+ if (only) for (let k = 0; k < R; k++) done[k] = only[k] ? 0 : 1;
4404
+ const present2 = mk(Uint8Array, 91, true);
4405
+ for (const s of S) for (let i = 0; i < s.n; i++) present2[s.cl[i]] = 1;
4406
+ const t1 = mk(Int32Array, R).fill(-1), t2 = mk(Int32Array, R).fill(-1), u1 = mk(Float64Array, R, true), u2 = mk(Float64Array, R, true);
4407
+ states.turns.forEach((t, ti) => {
4408
+ for (const [k, wu] of t.rivs) {
4409
+ if (t1[k] < 0) {
4410
+ t1[k] = ti;
4411
+ u1[k] = wu;
4412
+ } else {
4413
+ t2[k] = ti;
4414
+ u2[k] = wu;
4415
+ }
4416
+ }
4417
+ });
4418
+ const fl = [0, 0, 0, 0];
4419
+ let f1 = 0, f2 = 0, f3 = 0, f4 = 0;
4420
+ for (const c of states.base || flop) {
4421
+ const bit = 1 << (c >> 2);
4422
+ fl[c & 3] |= bit;
4423
+ if (f3 & bit) f4 |= bit;
4424
+ else if (f2 & bit) f3 |= bit;
4425
+ else if (f1 & bit) f2 |= bit;
4426
+ else f1 |= bit;
4427
+ }
4428
+ const cv = mk(Int32Array, 91), keys = mk(Float64Array, DCAP), denseOf = mk(Uint8Array, DCAP);
4429
+ 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);
4430
+ if (arena && WK.ex.equityPass) {
4431
+ const rT = mk(Uint8Array, R), rR = mk(Uint8Array, R), rW = mk(Float64Array, R);
4432
+ for (let k = 0; k < R; k++) {
4433
+ rT[k] = states.rivers[k][0];
4434
+ rR[k] = states.rivers[k][1];
4435
+ rW[k] = states.rivers[k][2];
4436
+ }
4437
+ const sb = S.map((s) => {
4438
+ const tot = mk(Float64Array, 1), b = mk(Int32Array, 18);
4439
+ const o = (a) => a ? a.byteOffset : 0;
4440
+ 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)]);
4441
+ return b;
4442
+ });
4443
+ const mb = mk(Int32Array, Math.max(1, mir.length * 3));
4444
+ mir.forEach((x, q) => {
4445
+ mb[q * 3] = x.bmap.byteOffset;
4446
+ mb[q * 3 + 1] = x.hmap[0].byteOffset;
4447
+ mb[q * 3 + 2] = x.hmap[1].byteOffset;
4448
+ });
4449
+ const pb = mk(Int32Array, 32);
4450
+ pb.set([
4451
+ R,
4452
+ mir.length,
4453
+ rT.byteOffset,
4454
+ rR.byteOffset,
4455
+ rW.byteOffset,
4456
+ t1.byteOffset,
4457
+ t2.byteOffset,
4458
+ u1.byteOffset,
4459
+ u2.byteOffset,
4460
+ done.byteOffset,
4461
+ present2.byteOffset,
4462
+ cv.byteOffset,
4463
+ keys.byteOffset,
4464
+ denseOf.byteOffset,
4465
+ fStamp.byteOffset,
4466
+ fSlot.byteOffset,
4467
+ ltC.byteOffset,
4468
+ eqC.byteOffset,
4469
+ fl[0],
4470
+ fl[1],
4471
+ fl[2],
4472
+ fl[3],
4473
+ f1,
4474
+ f2,
4475
+ f3,
4476
+ f4,
4477
+ sb[0].byteOffset,
4478
+ sb[1].byteOffset,
4479
+ mb.byteOffset,
4480
+ WK.tab,
4481
+ WK.tab + 8192,
4482
+ WK.tab + 16384
4483
+ ]);
4484
+ WK.ex.equityPass(pb.byteOffset);
4485
+ } else for (let k = 0; k < R; k++) {
4486
+ if (done[k]) continue;
4487
+ const t = states.rivers[k][0], r = states.rivers[k][1], wgt = states.rivers[k][2];
4488
+ let m1 = f1, m2 = f2, m3 = f3, m4 = f4;
4489
+ lane[0] = fl[0];
4490
+ lane[1] = fl[1];
4491
+ lane[2] = fl[2];
4492
+ lane[3] = fl[3];
4493
+ let bit = 1 << (t >> 2);
4494
+ lane[t & 3] |= bit;
4495
+ if (m3 & bit) m4 |= bit;
4496
+ else if (m2 & bit) m3 |= bit;
4497
+ else if (m1 & bit) m2 |= bit;
4498
+ else m1 |= bit;
4499
+ bit = 1 << (r >> 2);
4500
+ lane[r & 3] |= bit;
4501
+ if (m3 & bit) m4 |= bit;
4502
+ else if (m2 & bit) m3 |= bit;
4503
+ else if (m1 & bit) m2 |= bit;
4504
+ else m1 |= bit;
4505
+ let c = 0, nk = 0;
4506
+ for (let hi = 0; hi < 13; hi++) {
4507
+ const bh = 1 << hi;
4508
+ let a1 = m1, a2 = m2, a3 = m3, a4 = m4;
4509
+ if (a3 & bh) a4 |= bh;
4510
+ else if (a2 & bh) a3 |= bh;
4511
+ else if (a1 & bh) a2 |= bh;
4512
+ else a1 |= bh;
4513
+ for (let lo = 0; lo <= hi; lo++) {
4514
+ const bl = 1 << lo;
4515
+ let b1 = a1, b2 = a2, b3 = a3, b4 = a4;
4516
+ if (b3 & bl) b4 |= bl;
4517
+ else if (b2 & bl) b3 |= bl;
4518
+ else if (b1 & bl) b2 |= bl;
4519
+ else b1 |= bl;
4520
+ if (!present2[c]) {
4521
+ c++;
4522
+ continue;
4523
+ }
4524
+ const v = rankEval(b1, b2, b3, b4);
4525
+ cv[c] = v;
4526
+ keys[nk++] = v * 256 + c;
4527
+ c++;
4528
+ }
4529
+ }
4530
+ let F = -1, need = 9, fLane = 0;
4531
+ for (let s = 0; s < 4; s++) if (POPC[lane[s]] >= 3) {
4532
+ F = s;
4533
+ fLane = lane[s];
4534
+ need = 5 - POPC[lane[s]];
4535
+ }
4536
+ let slot = 91;
4537
+ for (let p = 0; p < 2; p++) {
4538
+ const s = S[p], n = s.n, ca = s.ca, cb = s.cb, cl = s.cl, id = s.id;
4539
+ if (F < 0) {
4540
+ for (let i = 0; i < n; i++) {
4541
+ const a = ca[i], b = cb[i];
4542
+ id[i] = a === t || a === r || b === t || b === r ? 255 : cl[i];
4543
+ }
4544
+ } else {
4545
+ for (let i = 0; i < n; i++) {
4546
+ const a = ca[i], b = cb[i];
4547
+ if (a === t || a === r || b === t || b === r) {
4548
+ id[i] = 255;
4549
+ continue;
4550
+ }
4551
+ let cnt = 0, mk2 = fLane;
4552
+ if ((a & 3) === F) {
4553
+ cnt++;
4554
+ mk2 |= 1 << (a >> 2);
4555
+ }
4556
+ if ((b & 3) === F) {
4557
+ cnt++;
4558
+ mk2 |= 1 << (b >> 2);
4559
+ }
4560
+ if (cnt >= need) {
4561
+ const fv = FLUSHV[mk2];
4562
+ if (fv > cv[cl[i]]) {
4563
+ if (fStamp[mk2] !== k) {
4564
+ fStamp[mk2] = k;
4565
+ fSlot[mk2] = slot;
4566
+ keys[nk++] = fv * 256 + slot;
4567
+ slot++;
4568
+ }
4569
+ id[i] = fSlot[mk2];
4570
+ continue;
4571
+ }
4572
+ }
4573
+ id[i] = cl[i];
4574
+ }
4575
+ }
4576
+ }
4577
+ const ks = nk === DCAP ? keys : keys.subarray(0, nk);
4578
+ ks.sort();
4579
+ let D = -1, prev = -1;
4580
+ for (let q = 0; q < nk; q++) {
4581
+ const key = ks[q];
4582
+ const v = key / 256 >>> 0;
4583
+ if (v !== prev) {
4584
+ D++;
4585
+ prev = v;
4586
+ }
4587
+ denseOf[key - v * 256] = D;
4588
+ }
4589
+ D++;
4590
+ for (let p = 0; p < 2; p++) {
4591
+ 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;
4592
+ start.fill(0, 0, D + 2);
4593
+ totC.fill(0);
4594
+ let tot = 0;
4595
+ for (let i = 0; i < n; i++) {
4596
+ const x = id[i];
4597
+ if (x === 255) continue;
4598
+ const d = denseOf[x];
4599
+ dd[i] = d;
4600
+ start[d + 2]++;
4601
+ const wi = w[i];
4602
+ totC[ca[i]] += wi;
4603
+ totC[cb[i]] += wi;
4604
+ tot += wi;
4605
+ }
4606
+ for (let d = 2; d <= D + 1; d++) start[d] += start[d - 1];
4607
+ for (let i = 0; i < n; i++) {
4608
+ if (id[i] === 255) continue;
4609
+ ord[start[dd[i] + 1]++] = i;
4610
+ }
4611
+ s.tot = tot;
4612
+ }
4613
+ const ta = t1[k], tb = t2[k], wa = u1[k], wb = u2[k];
4614
+ for (let p = 0; p < 2; p++) {
4615
+ const s = S[p];
4616
+ if (!s.want) continue;
4617
+ const v = S[1 - p];
4618
+ 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;
4619
+ const va = v.ca, vb = v.cb, vw = v.w, vs = v.start, vo = v.ord, totC = v.totC, tot = v.tot;
4620
+ const base = k * n, oa = ta * n, ob = tb * n;
4621
+ ltC.fill(0);
4622
+ let ltT = 0;
4623
+ for (let d = 0; d < D; d++) {
4624
+ const v0 = vs[d], v1 = vs[d + 1], h0 = hs[d], h1 = hs[d + 1];
4625
+ let eqT = 0;
4626
+ if (h0 < h1) {
4627
+ for (let q = v0; q < v1; q++) {
4628
+ const j = vo[q], wj = vw[j];
4629
+ eqC[va[j]] += wj;
4630
+ eqC[vb[j]] += wj;
4631
+ eqT += wj;
4632
+ }
4633
+ for (let q = h0; q < h1; q++) {
4634
+ const i = ho[q], a = ca[i], b = cb[i], sw = same[i];
4635
+ const all = tot - totC[a] - totC[b] + sw;
4636
+ const e = all > 1e-12 ? (ltT - ltC[a] - ltC[b] + 0.5 * (eqT - eqC[a] - eqC[b] + sw)) / all : 0.5;
4637
+ E[base + i] = e;
4638
+ fS[i] += wgt * e;
4639
+ fW[i] += wgt;
4640
+ if (ta >= 0) {
4641
+ tS[oa + i] += wa * e;
4642
+ tW[oa + i] += wa;
4643
+ }
4644
+ if (tb >= 0) {
4645
+ tS[ob + i] += wb * e;
4646
+ tW[ob + i] += wb;
4647
+ }
4648
+ }
4649
+ for (let q = v0; q < v1; q++) {
4650
+ const j = vo[q], wj = vw[j];
4651
+ const a = va[j], b = vb[j];
4652
+ ltC[a] += wj;
4653
+ ltC[b] += wj;
4654
+ eqC[a] = 0;
4655
+ eqC[b] = 0;
4656
+ }
4657
+ ltT += eqT;
4658
+ } else {
4659
+ for (let q = v0; q < v1; q++) {
4660
+ const j = vo[q], wj = vw[j];
4661
+ ltC[va[j]] += wj;
4662
+ ltC[vb[j]] += wj;
4663
+ ltT += wj;
4664
+ }
4665
+ }
4666
+ }
4667
+ }
4668
+ for (let q = 0; q < mir.length; q++) {
4669
+ const k2 = mir[q].bmap[k];
4670
+ if (k2 === k || done[k2]) continue;
4671
+ done[k2] = 1;
4672
+ const w2 = states.rivers[k2][2], ta2 = t1[k2], tb2 = t2[k2], wa2 = u1[k2], wb2 = u2[k2];
4673
+ for (let p = 0; p < 2; p++) {
4674
+ const s = S[p];
4675
+ if (!s.want) continue;
4676
+ 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;
4677
+ const b1 = k * n, b2 = k2 * n, oa = ta2 * n, ob = tb2 * n;
4678
+ for (let i = 0; i < n; i++) {
4679
+ if (id[i] === 255) continue;
4680
+ const e = E[b1 + i], j = hm[i];
4681
+ E[b2 + j] = e;
4682
+ fS[j] += w2 * e;
4683
+ fW[j] += w2;
4684
+ if (ta2 >= 0) {
4685
+ tS[oa + j] += wa2 * e;
4686
+ tW[oa + j] += wa2;
4687
+ }
4688
+ if (tb2 >= 0) {
4689
+ tS[ob + j] += wb2 * e;
4690
+ tW[ob + j] += wb2;
4691
+ }
4692
+ }
4693
+ }
4694
+ }
4695
+ }
4696
+ return S.map((s) => {
4697
+ if (!s.want) return null;
4698
+ const n = s.n;
4699
+ const ef = mk(Float32Array, n), et = mk(Float32Array, T * n);
4700
+ for (let i = 0; i < n; i++) ef[i] = s.fW[i] ? s.fS[i] / s.fW[i] : 0.5;
4701
+ for (let q = 0; q < T * n; q++) et[q] = s.tW[q] ? s.tS[q] / s.tW[q] : NaN;
4702
+ return { E: s.E, ef, et, fS: s.fS, fW: s.fW, tS: s.tS, tW: s.tW };
4703
+ });
4704
+ }
4705
+ const ALL_PERMS = (() => {
4706
+ const out = [];
4707
+ const rec = (a, rest) => {
4708
+ if (!rest.length) return out.push(a);
4709
+ rest.forEach((x, i) => rec(a.concat(x), rest.filter((_, j) => j !== i)));
4710
+ };
4711
+ rec([], [0, 1, 2, 3]);
4712
+ return out;
4713
+ })();
4714
+ function flopPerms(flop) {
4715
+ const key = (cs) => cs.slice().sort((x, y) => x - y).join(",");
4716
+ const k0 = key(flop);
4717
+ return ALL_PERMS.filter((p) => key(flop.map((c) => c & ~3 | p[c & 3])) === k0);
4718
+ }
4719
+ function orbits(hero, flop, symmetric) {
4720
+ const perms = symmetric ? flopPerms(flop) : [[0, 1, 2, 3]];
4721
+ const idx = new Map(hero.map((h, i) => [hid(h), i]));
4722
+ const orb = new Int32Array(hero.length).fill(-1);
4723
+ const list = [];
4724
+ hero.forEach((h, i) => {
4725
+ if (orb[i] >= 0) return;
4726
+ const o = list.length, mem = [];
4727
+ for (const p of perms) {
4728
+ let a = h.a & ~3 | p[h.a & 3], b = h.b & ~3 | p[h.b & 3];
4729
+ if (a > b) {
4730
+ const t = a;
4731
+ a = b;
4732
+ b = t;
4733
+ }
4734
+ const j = idx.get(a * 52 + b);
4735
+ if (j !== void 0 && orb[j] < 0) {
4736
+ orb[j] = o;
4737
+ mem.push(j);
4738
+ }
4739
+ }
4740
+ list.push(mem);
4741
+ });
4742
+ return { orb, list, perms };
4743
+ }
4744
+ function isSymmetric(hands, perms) {
4745
+ const idx = new Map(hands.map((h) => [hid(h), h.w]));
4746
+ for (const p of perms) for (const h of hands) {
4747
+ let a = h.a & ~3 | p[h.a & 3], b = h.b & ~3 | p[h.b & 3];
4748
+ if (a > b) {
4749
+ const t = a;
4750
+ a = b;
4751
+ b = t;
4752
+ }
4753
+ const w = idx.get(a * 52 + b);
4754
+ if (w === void 0 || Math.abs(w - h.w) > 1e-9) return false;
4755
+ }
4756
+ return true;
4757
+ }
4758
+ function prepareBoth(hA, hB, flop, states, wantA = true, wantB = true, only = null) {
4759
+ states = states || deckStates(flop, 0);
4760
+ const perms = states.blankMask ? [[0, 1, 2, 3]] : flopPerms(flop);
4761
+ const sym = perms.length > 1 && isSymmetric(hA, perms) && isSymmetric(hB, perms);
4762
+ const eq = equitiesBoth(hA, hB, flop, states, wantA, wantB, sym ? perms : null, only);
4763
+ 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 };
4764
+ return [one(hA, eq[0], hB), one(hB, eq[1], hA)];
4765
+ }
4766
+ let lastPair = null;
4767
+ function prepare(hero, villain, flop, states) {
4768
+ states = states || deckStates(flop, 0);
4769
+ if (lastPair && lastPair.states === states && lastPair.a === villain && lastPair.b === hero) return lastPair.res[1];
4770
+ const res = prepareBoth(hero, villain, flop, states);
4771
+ lastPair = { a: hero, b: villain, states, res };
4772
+ return res[0];
4773
+ }
4774
+ function distances(P) {
4775
+ if (P.D) return P.D;
4776
+ const { n, R, E, states } = P;
4777
+ const D = new Float32Array(n * n), S2 = new Float64Array(n * n), C2 = new Float64Array(n * n);
4778
+ const live = new Int32Array(n), ev = new Float64Array(n);
4779
+ for (let k = 0; k < R; k++) {
4780
+ const w = states.rivers[k][2], base = k * n;
4781
+ let c = 0;
4782
+ for (let i = 0; i < n; i++) {
4783
+ const e = E[base + i];
4784
+ if (e === e) {
4785
+ live[c] = i;
4786
+ ev[c] = e;
4787
+ c++;
4788
+ }
4789
+ }
4790
+ for (let p = 0; p < c; p++) {
4791
+ const row = live[p] * n, ep = ev[p];
4792
+ for (let q = p + 1; q < c; q++) {
4793
+ const d = ep - ev[q];
4794
+ S2[row + live[q]] += w * d * d;
4795
+ C2[row + live[q]] += w;
4796
+ }
4797
+ }
4798
+ }
4799
+ for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
4800
+ const c = C2[i * n + j];
4801
+ D[i * n + j] = D[j * n + i] = c ? Math.sqrt(S2[i * n + j] / c) : 1;
4802
+ }
4803
+ return P.D = D;
4804
+ }
4805
+ function walker(P, opts = {}) {
4806
+ const B = opts.bins || 16, sw = opts.streetWeights || [1, 1, 1];
4807
+ const symmetric = opts.symmetric !== false && !P.states.blankMask;
4808
+ const rsOpt = opts.riverSample || 1;
4809
+ const key = B + "|" + sw.join(",") + "|" + symmetric + "|" + rsOpt;
4810
+ if (P.walkKey === key) return P.walk;
4811
+ const { hero, flop, n, R, states } = P;
4812
+ const ob = orbits(hero, flop, symmetric);
4813
+ const list = [["ef", 0, sw[0]]];
4814
+ const tw = states.turns.reduce((s, t) => s + t.w, 0);
4815
+ states.turns.forEach((t, ti) => list.push(["et", ti * n, sw[1] * t.w / tw]));
4816
+ const rws = [], rks = [];
4817
+ const mirrored = symmetric && P.boardSym && ob.perms.length > 1;
4818
+ const done = new Uint8Array(R), ridx = mirrored ? new Map(states.rivers.map((r, k) => [dealtKey(states, k), k])) : null, repQ = new Int32Array(R);
4819
+ for (let k = 0; k < R; k++) {
4820
+ if (done[k]) continue;
4821
+ let wsum = states.rivers[k][2];
4822
+ repQ[k] = rks.length;
4823
+ if (mirrored) {
4824
+ wsum = 0;
4825
+ for (const p of ob.perms) {
4826
+ const j = ridx.get(dealtKey(states, k, p));
4827
+ if (!done[j]) {
4828
+ done[j] = 1;
4829
+ repQ[j] = rks.length;
4830
+ wsum += states.rivers[j][2];
4831
+ }
4832
+ }
4833
+ }
4834
+ rks.push(k);
4835
+ rws.push(wsum);
4836
+ }
4837
+ const rs = rsOpt === "auto" ? Math.max(1, Math.min(3, Math.floor(rks.length / 300))) : rsOpt;
4838
+ let rw = 0;
4839
+ const use = [];
4840
+ for (let q = 0; q < rks.length; q++) if (q % rs === 0) {
4841
+ use.push(q);
4842
+ rw += rws[q];
4843
+ }
4844
+ const rivers = use.map((q) => ["E", rks[q] * n, sw[2] * rws[q] / rw, q]);
4845
+ P.walkKey = key;
4846
+ P.gramKey = null;
4847
+ P.walk = { key, B, ob, m: ob.list.length, fixed: list, rivers, sets: rks.length, repQ };
4848
+ return P.walk;
4849
+ }
4850
+ function fillBins(arr, off, order, cnt, keyOf, B, n, binK, binV, binN) {
4851
+ const Bm1 = B - 1, Bm2 = B - 2;
4852
+ binN.fill(0);
4853
+ for (let q = 0; q < cnt; q++) {
4854
+ const i = order[q];
4855
+ const e = arr[off + i];
4856
+ if (e !== e) continue;
4857
+ const o = keyOf[i];
4858
+ const x = (e < 0 ? 0 : e > 1 ? 1 : e) * Bm1;
4859
+ let b0 = x | 0;
4860
+ if (b0 > Bm2) b0 = Bm2;
4861
+ const f = x - b0;
4862
+ if (f < 1) {
4863
+ const base = b0 * n, c = binN[b0];
4864
+ if (c && binK[base + c - 1] === o) binV[base + c - 1] += 1 - f;
4865
+ else {
4866
+ binK[base + c] = o;
4867
+ binV[base + c] = 1 - f;
4868
+ binN[b0] = c + 1;
4869
+ }
4870
+ }
4871
+ if (f > 0) {
4872
+ const b1 = b0 + 1, base = b1 * n, c = binN[b1];
4873
+ if (c && binK[base + c - 1] === o) binV[base + c - 1] += f;
4874
+ else {
4875
+ binK[base + c] = o;
4876
+ binV[base + c] = f;
4877
+ binN[b1] = c + 1;
4878
+ }
4879
+ }
4880
+ }
4881
+ }
4882
+ function addPairs(U, diag, stride, binK, binV, from, to, lam) {
4883
+ for (let p = from; p < to; p++) {
4884
+ const op = binK[p], v = binV[p], vp = v * lam, row = op * stride;
4885
+ diag[op] += vp * v;
4886
+ let q = p + 1;
4887
+ for (const e = to - 3; q < e; q += 4) {
4888
+ U[row + binK[q]] += vp * binV[q];
4889
+ U[row + binK[q + 1]] += vp * binV[q + 1];
4890
+ U[row + binK[q + 2]] += vp * binV[q + 2];
4891
+ U[row + binK[q + 3]] += vp * binV[q + 3];
4892
+ }
4893
+ for (; q < to; q++) U[row + binK[q]] += vp * binV[q];
4894
+ }
4895
+ }
4896
+ const symmetrize = (U, diag, m) => {
4897
+ for (let a = 0; a < m; a++) {
4898
+ U[a * m + a] = diag[a] + 2 * U[a * m + a];
4899
+ for (let b = a + 1; b < m; b++) {
4900
+ const v = U[a * m + b] + U[b * m + a];
4901
+ U[a * m + b] = v;
4902
+ U[b * m + a] = v;
4903
+ }
4904
+ }
4905
+ return U;
4906
+ };
4907
+ function accumulate(P, W, entries, U, diag) {
4908
+ const { n } = P, { B, ob, m } = W, orb = ob.orb;
4909
+ const order = mk(Int32Array, n);
4910
+ {
4911
+ let c = 0;
4912
+ for (const mem of ob.list) for (const i of mem) order[c++] = i;
4913
+ }
4914
+ U = U || mk(Float64Array, m * m, true);
4915
+ diag = diag || mk(Float64Array, m, true);
4916
+ const binK = mk(Int32Array, B * n), binV = mk(Float64Array, B * n), binN = mk(Int32Array, B);
4917
+ const src = (e) => P[e[0]];
4918
+ if (entries.length && inW(U) && entries.every((e) => inW(src(e)))) {
4919
+ const key = mk(Int32Array, n);
4920
+ key.set(orb);
4921
+ const ex = WK.ex;
4922
+ 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]);
4923
+ } else for (const e of entries) {
4924
+ fillBins(src(e), e[1], order, n, orb, B, n, binK, binV, binN);
4925
+ for (let b = 0; b < B; b++) addPairs(U, diag, m, binK, binV, b * n, b * n + binN[b], e[2]);
4926
+ }
4927
+ return { U, diag };
4928
+ }
4929
+ function gram(P, opts = {}) {
4930
+ const W = walker(P, opts);
4931
+ if (P.gramKey === W.key) return P.gramRes;
4932
+ const a = accumulate(P, W, W.fixed.concat(W.rivers));
4933
+ const Go = symmetrize(a.U, a.diag, W.m);
4934
+ if (P.states.fixed && P.states.fixed.length === 2 && P.villain) addOpponentSide(P, W, Go);
4935
+ P.gramKey = W.key;
4936
+ P.gramRes = { Go, ob: W.ob, m: W.m };
4937
+ return P.gramRes;
4938
+ }
4939
+ function addOpponentSide(P, W, Go) {
4940
+ const { hero, villain, n } = P, bd = P.states.base.concat(P.states.fixed), m = W.m, orb = W.ob.orb, nv = villain.length;
4941
+ 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]));
4942
+ 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;
4943
+ 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);
4944
+ let vt = 0;
4945
+ for (const v of villain) vt += v.w;
4946
+ if (!(vt > 0)) return;
4947
+ villain.forEach((v, j) => {
4948
+ const d = rank.get(vv[j]), w = v.w / vt;
4949
+ vr[j] = d;
4950
+ vw[j] = w;
4951
+ cumT[d + 1] += w;
4952
+ cumC[v.a * D1 + d + 1] += w;
4953
+ cumC[v.b * D1 + d + 1] += w;
4954
+ at[v.a * 52 + v.b] = j;
4955
+ at[v.b * 52 + v.a] = j;
4956
+ });
4957
+ for (let d = 1; d <= D; d++) cumT[d] += cumT[d - 1];
4958
+ for (let c = 0; c < 52; c++) {
4959
+ const o = c * D1;
4960
+ for (let d = 1; d <= D; d++) cumC[o + d] += cumC[o + d - 1];
4961
+ }
4962
+ const hr = Int32Array.from(hv, (v) => rank.get(v)), Gv = new Float64Array(m * m), U = [0, 0, 0, 0];
4963
+ for (let i = 0; i < n; i++) {
4964
+ const a = hero[i].a, b = hero[i].b, ri = hr[i], oi = orb[i];
4965
+ for (let j = i; j < n; j++) {
4966
+ 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;
4967
+ let nu = 2;
4968
+ U[0] = a;
4969
+ U[1] = b;
4970
+ if (a2 !== a && a2 !== b) U[nu++] = a2;
4971
+ if (b2 !== a && b2 !== b) U[nu++] = b2;
4972
+ let g = cumT[x] + cumT[D] - cumT[y + 1] + (tie ? cumT[x + 1] - cumT[x] : 0);
4973
+ for (let q = 0; q < nu; q++) {
4974
+ const o = U[q] * D1;
4975
+ g -= cumC[o + x] + cumC[o + D] - cumC[o + y + 1] + (tie ? cumC[o + x + 1] - cumC[o + x] : 0);
4976
+ for (let r = q + 1; r < nu; r++) {
4977
+ const k = at[U[q] * 52 + U[r]];
4978
+ if (k >= 0) {
4979
+ const d = vr[k];
4980
+ if (d < x || d > y || tie && d === x) g += vw[k];
4981
+ }
4982
+ }
4983
+ }
4984
+ Gv[oi * m + orb[j]] += g;
4985
+ if (j !== i) Gv[orb[j] * m + oi] += g;
4986
+ }
4987
+ }
4988
+ const w0 = new Float64Array(m);
4989
+ W.ob.list.forEach((mem, o) => {
4990
+ let t = 0;
4991
+ for (const i of mem) t += hero[i].w;
4992
+ w0[o] = t / mem.length;
4993
+ });
4994
+ const quad = (M) => {
4995
+ let t = 0;
4996
+ for (let x = 0; x < m; x++) {
4997
+ let r = 0;
4998
+ const o = x * m;
4999
+ for (let y = 0; y < m; y++) r += M[o + y] * w0[y];
5000
+ t += w0[x] * r;
5001
+ }
5002
+ return t;
5003
+ };
5004
+ const cv = quad(Gv), ch = quad(Go);
5005
+ if (!(cv > 0) || !(ch > 0)) return;
5006
+ for (let q = 0; q < m * m; q++) Go[q] = Go[q] / ch + Gv[q] / cv;
5007
+ }
5008
+ function invertSPD(A, m) {
5009
+ const L = new Float64Array(m * m);
5010
+ for (let i = 0; i < m; i++) {
5011
+ const ri = i * m;
5012
+ for (let j = 0; j <= i; j++) {
5013
+ const rj = j * m;
5014
+ let s0 = A[ri + j], s1 = 0, s2 = 0, s3 = 0, k = 0;
5015
+ for (const e = j - 3; k < e; k += 4) {
5016
+ s0 -= L[ri + k] * L[rj + k];
5017
+ s1 -= L[ri + k + 1] * L[rj + k + 1];
5018
+ s2 -= L[ri + k + 2] * L[rj + k + 2];
5019
+ s3 -= L[ri + k + 3] * L[rj + k + 3];
5020
+ }
5021
+ for (; k < j; k++) s0 -= L[ri + k] * L[rj + k];
5022
+ const s = s0 + s1 + s2 + s3;
5023
+ L[ri + j] = i === j ? Math.sqrt(s > 0 ? s : 1e-300) : s / L[rj + j];
5024
+ }
5025
+ }
5026
+ const X = new Float64Array(m * m);
5027
+ for (let i = 0; i < m; i++) {
5028
+ const ri = i * m, d = 1 / L[ri + i];
5029
+ for (let k = 0; k < i; k++) {
5030
+ const f = L[ri + k];
5031
+ if (!f) continue;
5032
+ const rk = k * m;
5033
+ let j = 0;
5034
+ for (const e = k - 2; j < e; j += 4) {
5035
+ X[ri + j] -= f * X[rk + j];
5036
+ X[ri + j + 1] -= f * X[rk + j + 1];
5037
+ X[ri + j + 2] -= f * X[rk + j + 2];
5038
+ X[ri + j + 3] -= f * X[rk + j + 3];
5039
+ }
5040
+ for (; j <= k; j++) X[ri + j] -= f * X[rk + j];
5041
+ }
5042
+ for (let j = 0; j < i; j++) X[ri + j] *= d;
5043
+ X[ri + i] = d;
5044
+ }
5045
+ const Pm = L.fill(0);
5046
+ for (let k = 0; k < m; k++) {
5047
+ const rk = k * m;
5048
+ for (let a = 0; a <= k; a++) {
5049
+ const xa = X[rk + a];
5050
+ if (!xa) continue;
5051
+ const ra = a * m;
5052
+ let b = 0;
5053
+ for (const e = a - 2; b < e; b += 4) {
5054
+ Pm[ra + b] += xa * X[rk + b];
5055
+ Pm[ra + b + 1] += xa * X[rk + b + 1];
5056
+ Pm[ra + b + 2] += xa * X[rk + b + 2];
5057
+ Pm[ra + b + 3] += xa * X[rk + b + 3];
5058
+ }
5059
+ for (; b <= a; b++) Pm[ra + b] += xa * X[rk + b];
5060
+ }
5061
+ }
5062
+ return Pm;
5063
+ }
5064
+ function obsState(M, dim, idx, eps, w0, bvec) {
5065
+ const k = idx.length, A = mk(Float64Array, k * k);
5066
+ for (let q = 0; q < k; q++) {
5067
+ const o = idx[q] * dim, r = q * k;
5068
+ for (let p = 0; p <= q; p++) A[r + p] = M[o + idx[p]];
5069
+ A[r + q] += eps;
5070
+ }
5071
+ let Pm;
5072
+ if (arena) {
5073
+ Pm = mk(Float64Array, k * k);
5074
+ const X = mk(Float64Array, k * k);
5075
+ WK.ex.invertSPD(A.byteOffset, Pm.byteOffset, X.byteOffset, k);
5076
+ } else Pm = invertSPD(A, k);
5077
+ const wp = mk(Float64Array, k);
5078
+ if (w0) for (let q = 0; q < k; q++) wp[q] = w0[idx[q]];
5079
+ else for (let q = 0; q < k; q++) {
5080
+ let s = 0;
5081
+ const r = q * k;
5082
+ for (let p = 0; p <= q; p++) s += Pm[r + p] * bvec[idx[p]];
5083
+ for (let p = q + 1; p < k; p++) s += Pm[p * k + q] * bvec[idx[p]];
5084
+ wp[q] = s;
5085
+ }
5086
+ const act = mk(Int32Array, k);
5087
+ act.set(idx);
5088
+ return { Pm, k, na: k, act, wp, col: mk(Float64Array, k), sal: 0, w: arena, salp: arena ? mk(Float64Array, 1) : null };
5089
+ }
5090
+ function obsPick(st, skip) {
5091
+ const { Pm, k, na, wp, act } = st;
5092
+ if (st.w && !skip) {
5093
+ const q = WK.ex.obsPick(Pm.byteOffset, k, na, wp.byteOffset, st.salp.byteOffset);
5094
+ st.sal = st.salp[0];
5095
+ return q;
5096
+ }
5097
+ let bq = -1, bs = Infinity, sal = 0;
5098
+ for (let q = 0; q < na; q++) {
5099
+ if (skip && skip(act[q])) continue;
5100
+ const wj = wp[q], cost = wj * wj / Pm[q * k + q], s = wj < 0 ? -1e30 + wj : cost;
5101
+ if (s < bs) {
5102
+ bs = s;
5103
+ bq = q;
5104
+ sal = cost;
5105
+ }
5106
+ }
5107
+ st.sal = sal;
5108
+ return bq;
5109
+ }
5110
+ function obsRemove(st, bq) {
5111
+ const { Pm, k, wp, act, col } = st;
5112
+ let na = st.na;
5113
+ if (st.w) {
5114
+ const id = WK.ex.obsRemove(Pm.byteOffset, k, na, wp.byteOffset, act.byteOffset, col.byteOffset, bq);
5115
+ st.na = na - 1;
5116
+ return id;
5117
+ }
5118
+ const bj = act[bq];
5119
+ const rb = bq * k;
5120
+ for (let q = 0; q <= bq; q++) col[q] = Pm[rb + q];
5121
+ for (let q = bq + 1; q < na; q++) col[q] = Pm[q * k + bq];
5122
+ const pj = col[bq], f = wp[bq] / pj, inv = 1 / pj, last = na - 1;
5123
+ if (bq !== last) {
5124
+ const rl = last * k;
5125
+ for (let q = 0; q < bq; q++) Pm[rb + q] = Pm[rl + q];
5126
+ for (let q = bq + 1; q < last; q++) Pm[q * k + bq] = Pm[rl + q];
5127
+ Pm[rb + bq] = Pm[rl + last];
5128
+ col[bq] = col[last];
5129
+ wp[bq] = wp[last];
5130
+ act[bq] = act[last];
5131
+ }
5132
+ na = last;
5133
+ for (let q = 0; q < na; q++) {
5134
+ const ci = col[q];
5135
+ wp[q] -= f * ci;
5136
+ const s = ci * inv;
5137
+ if (!s) continue;
5138
+ const row = q * k;
5139
+ let p = 0;
5140
+ for (const e = q - 2; p < e; p += 4) {
5141
+ Pm[row + p] -= s * col[p];
5142
+ Pm[row + p + 1] -= s * col[p + 1];
5143
+ Pm[row + p + 2] -= s * col[p + 2];
5144
+ Pm[row + p + 3] -= s * col[p + 3];
5145
+ }
5146
+ for (; p <= q; p++) Pm[row + p] -= s * col[p];
5147
+ }
5148
+ st.na = na;
5149
+ return bj;
5150
+ }
5151
+ function eliminate(P, opts = {}) {
5152
+ const T = opts.timing, now = T ? () => Number(process.hrtime.bigint()) / 1e6 : null;
5153
+ let t0 = T ? now() : 0;
5154
+ const lap = (k) => {
5155
+ if (T) {
5156
+ const t = now();
5157
+ T[k] = (T[k] || 0) + t - t0;
5158
+ t0 = t;
5159
+ }
5160
+ };
5161
+ const { hero } = P;
5162
+ const W = walker(P, opts), ob = W.ob, m = W.m;
5163
+ const osize = new Int32Array(m);
5164
+ ob.list.forEach((mem, o) => {
5165
+ osize[o] = mem.length;
5166
+ });
5167
+ const w0 = new Float64Array(m);
5168
+ ob.list.forEach((mem, o) => {
5169
+ let s = 0;
5170
+ for (const i of mem) s += hero[i].w;
5171
+ w0[o] = s / mem.length;
5172
+ });
5173
+ const targets = (opts.sizes || []).slice().sort((a, b) => b - a);
5174
+ const tol = opts.tolerance;
5175
+ let hands = hero.length, cum = 0;
5176
+ const path = [], curve = [];
5177
+ let Go = gram(P, opts).Go;
5178
+ const ocls = ob.list.map((mem) => cls(hero[mem[0]]));
5179
+ if (opts.classMu) {
5180
+ Go = Float64Array.from(Go);
5181
+ 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];
5182
+ }
5183
+ let clsCount = null, skip = null;
5184
+ if (opts.keepClasses) {
5185
+ clsCount = /* @__PURE__ */ new Map();
5186
+ ocls.forEach((c) => clsCount.set(c, (clsCount.get(c) || 0) + 1));
5187
+ skip = (o) => clsCount.get(ocls[o]) <= 1;
5188
+ }
5189
+ let tr = 0;
5190
+ for (let i = 0; i < m; i++) tr += Go[i * m + i];
5191
+ const eps = (opts.ridge || 1e-6) * tr / m;
5192
+ const bl = new Float64Array(m);
5193
+ for (let i = 0; i < m; i++) {
5194
+ let s = 0;
5195
+ const o = i * m;
5196
+ for (let j = 0; j < m; j++) s += Go[o + j] * w0[j];
5197
+ bl[i] = s;
5198
+ }
5199
+ let c0 = 0;
5200
+ for (let i = 0; i < m; i++) c0 += w0[i] * bl[i];
5201
+ const M = Go, dim = m;
5202
+ let st = null;
5203
+ lap("gram");
5204
+ const blockwise = !opts.exact && !opts.classMu && !opts.keepClasses && !opts.fullCurve && m >= (opts.blockMin || 180) && (targets.length === 1 || tol !== void 0 && !targets.length);
5205
+ if (blockwise) {
5206
+ const feq = new Float64Array(m);
5207
+ ob.list.forEach((mem, o) => {
5208
+ let s = 0;
5209
+ for (const i of mem) s += P.ef[i];
5210
+ feq[o] = s / mem.length;
5211
+ });
5212
+ const order = Array.from({ length: m }, (_, o) => o).sort((x, y) => feq[x] - feq[y]);
5213
+ const G = Math.max(2, Math.round(m / (opts.blockSize || 110)));
5214
+ const seqs = [];
5215
+ for (let q = 0; q < G; q++) {
5216
+ const mark = arena ? WK.top : 0;
5217
+ const b = obsState(Go, m, order.slice(Math.floor(q * m / G), Math.floor((q + 1) * m / G)), eps, w0, null), seq = [];
5218
+ while (b.na > 1) {
5219
+ const bq = obsPick(b);
5220
+ if (bq < 0) break;
5221
+ const sal = b.sal;
5222
+ seq.push([obsRemove(b, bq), sal]);
5223
+ }
5224
+ seqs.push(seq);
5225
+ if (arena) WK.top = mark;
5226
+ }
5227
+ lap("blockElim");
5228
+ const head = new Int32Array(G), gone = new Uint8Array(m);
5229
+ let h1 = hands, c1 = 0;
5230
+ 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;
5231
+ for (; ; ) {
5232
+ let bg = -1, bs = Infinity;
5233
+ for (let q = 0; q < G; q++) if (head[q] < seqs[q].length && seqs[q][head[q]][1] < bs) {
5234
+ bs = seqs[q][head[q]][1];
5235
+ bg = q;
5236
+ }
5237
+ if (bg < 0) break;
5238
+ const o = seqs[bg][head[bg]][0];
5239
+ if (targets.length ? h1 - osize[o] < stopHands : c1 + bs > stopCost) break;
5240
+ gone[o] = 1;
5241
+ h1 -= osize[o];
5242
+ c1 += bs;
5243
+ head[bg]++;
5244
+ }
5245
+ const keep = [];
5246
+ for (let o = 0; o < m; o++) if (!gone[o]) keep.push(o);
5247
+ if (keep.length < m) {
5248
+ st = obsState(Go, m, keep, eps, null, bl);
5249
+ let e1 = c0;
5250
+ for (let q = 0; q < st.k; q++) e1 -= st.wp[q] * bl[keep[q]];
5251
+ if (tol !== void 0 && Math.sqrt(Math.max(0, e1) / c0) > tol) st = null;
5252
+ else {
5253
+ cum = Math.max(0, e1);
5254
+ hands = h1;
5255
+ }
5256
+ }
5257
+ lap("stage2init");
5258
+ }
5259
+ if (!st) {
5260
+ const all = new Int32Array(m);
5261
+ for (let i = 0; i < m; i++) all[i] = i;
5262
+ st = obsState(Go, m, all, eps, w0, null);
5263
+ hands = hero.length;
5264
+ cum = 0;
5265
+ }
5266
+ const snapshot = () => {
5267
+ const na = st.na, sup = st.act, ww = new Float64Array(m);
5268
+ const gs = mk(Float64Array, na * na), bs = mk(Float64Array, na), x = mk(Float64Array, na);
5269
+ for (let q = 0; q < na; q++) {
5270
+ const o = sup[q] * dim, r = q * na;
5271
+ bs[q] = bl[sup[q]];
5272
+ x[q] = st.wp[q] > 0 ? st.wp[q] : 0;
5273
+ for (let p = 0; p < na; p++) gs[r + p] = M[o + sup[p]];
5274
+ }
5275
+ if (arena) WK.ex.nnls(gs.byteOffset, bs.byteOffset, x.byteOffset, na, opts.sweeps || 60);
5276
+ else for (let s = 0, S = opts.sweeps || 60; s < S; s++) {
5277
+ let moved = 0;
5278
+ for (let q = 0; q < na; q++) {
5279
+ const r = q * na, gq = gs[r + q];
5280
+ let v = bs[q] + gq * x[q];
5281
+ for (let p = 0; p < na; p++) v -= gs[r + p] * x[p];
5282
+ v = v > 0 ? v / gq : 0;
5283
+ const d = v - x[q];
5284
+ if (d > moved) moved = d;
5285
+ else if (-d > moved) moved = -d;
5286
+ x[q] = v;
5287
+ }
5288
+ if (moved < 1e-12) break;
5289
+ }
5290
+ let e = 0, hc = 0;
5291
+ for (let q = 0; q < na; q++) {
5292
+ const o = sup[q];
5293
+ ww[o] = x[q];
5294
+ if (!x[q]) continue;
5295
+ hc += osize[o];
5296
+ const r = q * na;
5297
+ let v = 0;
5298
+ for (let p = 0; p < na; p++) v += gs[r + p] * x[p];
5299
+ e += x[q] * (v - 2 * bs[q]);
5300
+ }
5301
+ return { hands: hc, err: Math.sqrt(Math.max(0, e + c0) / c0), w: ww };
5302
+ };
5303
+ lap("fullInit");
5304
+ let ti = 0;
5305
+ while (st.na > 1) {
5306
+ while (ti < targets.length && hands <= targets[ti]) {
5307
+ path.push(Object.assign({ target: targets[ti] }, snapshot()));
5308
+ ti++;
5309
+ }
5310
+ if (ti >= targets.length && tol === void 0 && !opts.fullCurve) break;
5311
+ const bq = obsPick(st, skip);
5312
+ if (bq < 0) break;
5313
+ const sal = st.sal;
5314
+ if (tol !== void 0 && Math.sqrt((cum + sal) / c0) > tol) break;
5315
+ const o = obsRemove(st, bq);
5316
+ if (clsCount) clsCount.set(ocls[o], clsCount.get(ocls[o]) - 1);
5317
+ hands -= osize[o];
5318
+ cum += sal;
5319
+ if (opts.fullCurve) curve.push([hands, Math.sqrt(cum / c0)]);
5320
+ }
5321
+ lap("stage2elim");
5322
+ while (ti < targets.length) {
5323
+ path.push(Object.assign({ target: targets[ti] }, snapshot()));
5324
+ ti++;
5325
+ }
5326
+ if (tol !== void 0) path.push(Object.assign({ target: tol }, snapshot()));
5327
+ lap("refit");
5328
+ return { path, ob, curve };
5329
+ }
5330
+ function materialize(P, snap, ob, opts = {}) {
5331
+ const { hero, n } = P;
5332
+ const hands = [], reps = [];
5333
+ hero.forEach((h, i) => {
5334
+ const x = snap.w[ob.orb[i]];
5335
+ if (x > 0) {
5336
+ hands.push({ a: h.a, b: h.b, w: x });
5337
+ reps.push(i);
5338
+ }
5339
+ });
5340
+ let mx = 0;
5341
+ for (const h of hands) if (h.w > mx) mx = h.w;
5342
+ for (const h of hands) h.w /= mx;
5343
+ if (!opts.top) return { hands, prefs: null, err: snap.err, scale: 1 / mx };
5344
+ const D = distances(P);
5345
+ const key = (i, r) => D[i * n + r] + (opts.sameClass && cls(hero[i]) !== cls(hero[r]) ? 10 : 0);
5346
+ const prefs = hero.map((h, i) => {
5347
+ const top = reps.slice().sort((x, y) => key(i, x) - key(i, y)).slice(0, opts.top);
5348
+ return [hid(h), top.map((r) => hid(hero[r])), top.map((r) => +key(i, r).toFixed(5))];
5349
+ });
5350
+ if (opts.transport) {
5351
+ const m = reps.length, eps = opts.transport;
5352
+ const a = hero.map((h) => h.w), b = hands.map((h) => h.w);
5353
+ const sa = a.reduce((x, y) => x + y, 0), sb = b.reduce((x, y) => x + y, 0);
5354
+ const K = new Float64Array(n * m);
5355
+ 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);
5356
+ const u = new Float64Array(n).fill(1), v = new Float64Array(m).fill(1);
5357
+ for (let it = 0; it < (opts.transportIters || 300); it++) {
5358
+ for (let i = 0; i < n; i++) {
5359
+ let t = 0;
5360
+ const o = i * m;
5361
+ for (let j = 0; j < m; j++) t += K[o + j] * v[j];
5362
+ u[i] = a[i] / sa / (t || 1e-300);
5363
+ }
5364
+ for (let j = 0; j < m; j++) {
5365
+ let t = 0;
5366
+ for (let i = 0; i < n; i++) t += K[i * m + j] * u[i];
5367
+ v[j] = b[j] / sb / (t || 1e-300);
5368
+ }
5369
+ }
5370
+ hero.forEach((h, i) => {
5371
+ const row = [];
5372
+ let tot = 0;
5373
+ for (let j = 0; j < m; j++) {
5374
+ const x = u[i] * K[i * m + j] * v[j];
5375
+ if (x > 0) row.push([j, x]);
5376
+ tot += x;
5377
+ }
5378
+ row.sort((x, y) => y[1] - x[1]);
5379
+ const top = row.slice(0, opts.top);
5380
+ 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))];
5381
+ });
5382
+ }
5383
+ return { hands, prefs, err: snap.err, scale: 1 / mx };
5384
+ }
5385
+ const asHands = (r) => typeof r === "string" ? parseRange2(r) : r.map((h) => {
5386
+ if (!h.hand) return h;
5387
+ let a = cardFromStr(h.hand.slice(0, 2)), b = cardFromStr(h.hand.slice(2, 4));
5388
+ if (a > b) {
5389
+ const t = a;
5390
+ a = b;
5391
+ b = t;
5392
+ }
5393
+ return { a, b, w: h.weight };
5394
+ });
5395
+ const asFlop = (f) => {
5396
+ const txt = typeof f === "string" ? f.replace(/[\s,]/g, "") : null;
5397
+ const b = txt !== null ? /^([2-9TJQKA][cdhs])*$/.test(txt) ? (txt.match(/../g) || []).map(cardFromStr) : [] : Array.isArray(f) ? f.slice() : [];
5398
+ 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));
5399
+ return b;
5400
+ };
5401
+ const boardOf = (o) => asFlop(o.board !== void 0 ? o.board : o.flop);
5402
+ const asMask = (b) => !b ? 0 : typeof b === "number" ? b : b.reduce((m, s) => m | 1 << (typeof s === "string" ? SUITS2.indexOf(s) : s), 0);
5403
+ const liveHands = (hands, flop) => hands.filter((h) => h.w > 0 && !flop.includes(h.a) && !flop.includes(h.b));
5404
+ function blankSuitsFor(flop) {
5405
+ flop = asFlop(flop);
5406
+ const fc = [0, 0, 0, 0];
5407
+ flop.forEach((c) => fc[c & 3]++);
5408
+ return [0, 1, 2, 3].filter((s) => fc[s] < 2).map((s) => SUITS2[s]);
5409
+ }
5410
+ const expectedFrequencyError = (mismatch) => 0.6 + 60 * mismatch;
5411
+ const binsFor = (o, st) => o.bins || (st.fixed.length === 2 ? 64 : 16);
5412
+ const arenaBytes = (nA, nB, st, bins) => {
5413
+ const n = Math.max(nA, nB);
5414
+ 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);
5415
+ };
5416
+ const elimOpts = (o, n, sym) => {
5417
+ const opts = { symmetric: o.symmetric !== false && sym, bins: o.bins, streetWeights: o.streetWeights, exact: o.exact, riverSample: o.riverSample || "auto" };
5418
+ if (o.size) opts.sizes = [Math.min(o.size, n)];
5419
+ else opts.tolerance = o.tolerance === void 0 ? 0.01 : o.tolerance;
5420
+ if (o.curve) opts.fullCurve = true;
5421
+ return opts;
5422
+ };
5423
+ function solveOne(P, o) {
5424
+ const eo = elimOpts(o, P.n, P.boardSym || P.perms.length === 1);
5425
+ eo.bins = binsFor(o, P.states);
5426
+ const el = eliminate(P, eo);
5427
+ const m = materialize(P, el.path[0], el.ob, { top: o.standIns || 0 });
5428
+ return { hands: m.hands, prefs: m.prefs, err: m.err, scale: m.scale, n: P.n, curve: o.curve ? el.curve : void 0 };
5429
+ }
5430
+ function present(r, states) {
5431
+ let standIns = null;
5432
+ if (r.prefs) {
5433
+ standIns = {};
5434
+ r.prefs.forEach(([id, list]) => {
5435
+ standIns[handToStr(id / 52 | 0, id % 52)] = list.map((x) => handToStr(x / 52 | 0, x % 52));
5436
+ });
5437
+ }
5438
+ const hands = r.hands;
5439
+ return {
5440
+ range: rangeToString(hands),
5441
+ get pio() {
5442
+ return hands.map((h) => handToStr(h.a, h.b) + ":" + h.w.toFixed(4)).join(",");
5443
+ },
5444
+ hands: hands.map((h) => ({ hand: handToStr(h.a, h.b), weight: h.w })),
5445
+ size: hands.length,
5446
+ originalSize: r.n,
5447
+ mismatch: r.err,
5448
+ expectedFrequencyError: expectedFrequencyError(r.err),
5449
+ standIns,
5450
+ curve: r.curve,
5451
+ weightScale: r.scale,
5452
+ 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
5453
+ };
5454
+ }
5455
+ function compress(o) {
5456
+ const flop = boardOf(o);
5457
+ const hero = liveHands(asHands(o.range), flop), villain = liveHands(asHands(o.opponent), flop);
5458
+ const states = deckStates(flop, asMask(o.blankSuits));
5459
+ return present(withArena(arenaBytes(hero.length, 0, states, binsFor(o, states)), () => solveOne(prepareBoth(hero, villain, flop, states, true, false)[0], o)), states);
5460
+ }
5461
+ function compressBoth(o) {
5462
+ const flop = boardOf(o);
5463
+ const a = liveHands(asHands(o.oop), flop), b = liveHands(asHands(o.ip), flop);
5464
+ const states = deckStates(flop, asMask(o.blankSuits));
5465
+ const r = withArena(arenaBytes(a.length, b.length, states, binsFor(o, states)), () => {
5466
+ const P = prepareBoth(a, b, flop, states);
5467
+ const mark = arena ? WK.top : 0;
5468
+ const x = solveOne(P[0], Object.assign({}, o, { size: o.sizeOop || o.size }));
5469
+ if (arena) WK.top = mark;
5470
+ return [x, solveOne(P[1], Object.assign({}, o, { size: o.sizeIp || o.size }))];
5471
+ });
5472
+ return { oop: present(r[0], states), ip: present(r[1], states) };
5473
+ }
5474
+ return {
5475
+ compress,
5476
+ compressBoth,
5477
+ blankSuitsFor,
5478
+ expectedFrequencyError,
5479
+ parseRange: parseRange2,
5480
+ rangeToString,
5481
+ cardFromStr,
5482
+ cardToStr,
5483
+ handToStr,
5484
+ /** true if the WebAssembly kernels loaded; setWasm(false) forces the JavaScript path */
5485
+ get wasm() {
5486
+ return !!wasm3();
5487
+ },
5488
+ setWasm(on) {
5489
+ wasmOn = !!on;
5490
+ },
5491
+ ready,
5492
+ releaseMemory
5493
+ };
5494
+ }
5495
+ var range_compress_default = factory();
5496
+
5497
+ // src/compress.ts
5498
+ function compressRanges(config, options = {}) {
5499
+ const board = parseCards(config.board);
5500
+ if (board.length < 3 || board.length > 5) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);
5501
+ const tolerance = options.tolerance ?? (board.length === 3 ? 0.01 : 5e-3);
5502
+ if (!(tolerance > 0 && tolerance < 1)) throw new Error(`tolerance must be above 0 and under 1; got ${tolerance}`);
5503
+ const sizes = options.size === void 0 ? void 0 : typeof options.size === "number" ? [options.size, options.size] : options.size;
5504
+ 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)}`);
5505
+ const onBoard = new Set(board);
5506
+ const floor = config.minWeight ?? 0;
5507
+ const live = (range, who) => {
5508
+ const weights = typeof range === "string" ? parseRange(range) : range;
5509
+ if (weights.length !== COMBOS) throw new Error(`The ${who} range has ${weights.length} weights; one per combination is ${COMBOS}`);
5510
+ const kept = [];
5511
+ let largest = 0;
5512
+ for (let combo = 0; combo < COMBOS; combo++) {
5513
+ const weight = weights[combo];
5514
+ if (!(weight > 0) || weight < floor) continue;
5515
+ if (onBoard.has(COMBO_CARDS[combo * 2]) || onBoard.has(COMBO_CARDS[combo * 2 + 1])) continue;
5516
+ kept.push(combo);
5517
+ if (weight > largest) largest = weight;
5518
+ }
5519
+ 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`);
5520
+ return kept.map((combo) => ({ hand: formatCombo(combo), weight: weights[combo] / largest }));
5521
+ };
5522
+ const oop = live(config.oop, "out-of-position");
5523
+ const ip = live(config.ip, "in-position");
5524
+ let result;
5525
+ try {
5526
+ result = range_compress_default.compressBoth({
5527
+ oop,
5528
+ ip,
5529
+ board: board.map(formatCard).join(""),
5530
+ ...sizes ? { sizeOop: Math.min(sizes[0], oop.length), sizeIp: Math.min(sizes[1], ip.length) } : { tolerance }
5531
+ });
5532
+ } finally {
5533
+ range_compress_default.releaseMemory();
5534
+ }
5535
+ const weightsOf = (hands) => {
5536
+ const weights = new Float64Array(COMBOS);
5537
+ for (const { hand, weight } of hands) weights[comboIndex(parseCard(hand.slice(0, 2)), parseCard(hand.slice(2, 4)))] = weight;
5538
+ return weights;
5539
+ };
5540
+ return {
5541
+ oop: weightsOf(result.oop.hands),
5542
+ ip: weightsOf(result.ip.hands),
5543
+ report: [
5544
+ { from: oop.length, to: result.oop.size, mismatch: result.oop.mismatch },
5545
+ { from: ip.length, to: result.ip.size, mismatch: result.ip.mismatch }
5546
+ ]
5547
+ };
5548
+ }
5549
+
3915
5550
  // src/presets.ts
3916
5551
  function sizesCut(caller, preset) {
3917
5552
  const from = bettingTree(caller);
@@ -4034,8 +5669,10 @@ function liteConfig(config, options = {}) {
4034
5669
  );
4035
5670
  const buckets = options.runoutBuckets ?? 3;
4036
5671
  const given = typeof config.runoutBuckets === "number" ? config.runoutBuckets : config.runoutBuckets ? 1 : 0;
5672
+ const compressed = options.compressRanges ? compressRanges(config, options.compressRanges === true ? {} : options.compressRanges) : void 0;
4037
5673
  return {
4038
5674
  ...config,
5675
+ ...compressed ? { oop: compressed.oop, ip: compressed.ip, minWeight: void 0 } : {},
4039
5676
  betSizes,
4040
5677
  ...raiseSizes === void 0 ? {} : { raiseSizes },
4041
5678
  maxRaises,
@@ -4065,10 +5702,11 @@ function nearest(row, target) {
4065
5702
  }
4066
5703
  function solveLite(config, options = {}) {
4067
5704
  const preset = litePreset(config, options);
4068
- const blueprint = preset.config;
5705
+ return liteSolution(solve(defineSpot(preset.config), preset.options), config, preset.config, preset.changes, options);
5706
+ }
5707
+ function liteSolution(solution, config, blueprint, changes, options) {
4069
5708
  const share = blueprint.shareHistories;
4070
5709
  const kept = typeof share === "object" ? [...share.keepLines ?? []] : [];
4071
- const solution = solve(defineSpot(blueprint), preset.options);
4072
5710
  const subgameSolve = pick(options, ["workers", "precision", "wasmStorage"]);
4073
5711
  const { tree } = solution.spot;
4074
5712
  const scale = solution.spot.chipScale;
@@ -4077,7 +5715,7 @@ function solveLite(config, options = {}) {
4077
5715
  blueprint,
4078
5716
  kept,
4079
5717
  source: config,
4080
- changes: preset.changes,
5718
+ changes,
4081
5719
  resolve(node, board, resolveOptions) {
4082
5720
  const round = tree.round[node];
4083
5721
  const prefix = `${solution.path(node)} `;
@@ -4093,10 +5731,96 @@ function solveLite(config, options = {}) {
4093
5731
  }
4094
5732
  };
4095
5733
  }
5734
+ var LITE_RESUME = 30;
5735
+ function openLite(config, options = {}) {
5736
+ const preset = litePreset(config, options);
5737
+ const { settle, ...rest } = preset.options;
5738
+ const moved = settle || options.resettle ? { ...settle, ...options.resettle } : null;
5739
+ const resettle = moved && options.algorithm === "cfr+" && options.resettle?.tolerance === void 0 ? { ...moved, tolerance: settlePlan(moved).tolerance / 2 } : moved;
5740
+ if (resettle) settlePlan(resettle);
5741
+ const compress = options.compressRanges ? options.compressRanges === true ? {} : options.compressRanges : null;
5742
+ let run = createRun(defineSpot(preset.config), preset.options);
5743
+ let source = config;
5744
+ let earlier = 0;
5745
+ const reading = (solution) => liteSolution(solution, source, run.spot.source, preset.changes, options);
5746
+ const settleRun = (plan) => reading(runToStop(run, plan ? { ...rest, settle: plan } : rest));
5747
+ const resumed = () => options.algorithm === "cfr+" ? run.totalIterations : Math.min(run.totalIterations, LITE_RESUME);
5748
+ let current;
5749
+ try {
5750
+ current = settleRun(settle);
5751
+ } catch (error) {
5752
+ run.close();
5753
+ throw error;
5754
+ }
5755
+ return {
5756
+ get current() {
5757
+ return current;
5758
+ },
5759
+ get iterations() {
5760
+ return earlier + run.completed;
5761
+ },
5762
+ setRange(player, range) {
5763
+ const next = { ...source, [player === 0 ? "oop" : "ip"]: typeof range === "string" ? range : range.slice() };
5764
+ let inPlace = false;
5765
+ if (!compress) {
5766
+ try {
5767
+ run.setRange(player, range, { resume: LITE_RESUME });
5768
+ inPlace = true;
5769
+ } catch (error) {
5770
+ if (!(error instanceof RangeNotInPlaceError)) throw error;
5771
+ }
5772
+ }
5773
+ if (!inPlace) {
5774
+ const ranges = compress ? compressRanges(next, compress) : next;
5775
+ const stored = (index) => Float64Array.from(index.slot, (slot) => slot >= 0 ? 1 : 0);
5776
+ const blueprint = {
5777
+ ...preset.config,
5778
+ oop: ranges.oop,
5779
+ ip: ranges.ip,
5780
+ ...compress ? {} : { oopReserve: stored(run.spot.players[0]), ipReserve: stored(run.spot.players[1]) }
5781
+ };
5782
+ const spot = defineSpot(blueprint);
5783
+ const count = resumed();
5784
+ run.close();
5785
+ let replacement;
5786
+ try {
5787
+ replacement = createRun(spot, { ...preset.options, warmStart: run, warmIteration: count });
5788
+ } catch (error) {
5789
+ run = createRun(run.spot, { ...preset.options, warmStart: run });
5790
+ throw error;
5791
+ }
5792
+ earlier += run.completed;
5793
+ run = replacement;
5794
+ }
5795
+ source = next;
5796
+ try {
5797
+ current = settleRun(resettle);
5798
+ } catch (error) {
5799
+ current = reading(run.snapshot([], "iterations"));
5800
+ throw error;
5801
+ }
5802
+ return current;
5803
+ },
5804
+ refine(count) {
5805
+ if (!(Number.isInteger(count) && count > 0)) throw new Error(`refine: iterations must be a positive whole number; got ${count}`);
5806
+ run.step(count);
5807
+ current = reading(run.snapshot([], "iterations"));
5808
+ return current;
5809
+ },
5810
+ close() {
5811
+ run.close();
5812
+ }
5813
+ };
5814
+ }
5815
+ var KEEP_TOLERANCE = 5e-3;
4096
5816
  function litePreset(config, options = {}) {
4097
5817
  const blueprint = keepWithin(liteConfig(config, options), options);
4098
5818
  const sampling = options.sampling === void 0 ? {} : options.sampling;
4099
- const settle = options.settle === void 0 ? {} : options.settle;
5819
+ const asked = options.settle === void 0 ? {} : options.settle;
5820
+ const share = blueprint.shareHistories;
5821
+ const keeps = options.keepBudget !== void 0 && typeof share === "object" && (share.keepLines?.length ?? 0) > 0;
5822
+ const settle = asked && keeps && asked.tolerance === void 0 ? { ...asked, tolerance: KEEP_TOLERANCE } : asked;
5823
+ const tolerance = settle ? settlePlan(settle).tolerance : 0;
4100
5824
  const solveOptions = {
4101
5825
  iterations: options.iterations ?? 2e3,
4102
5826
  ...settle ? { settle } : {},
@@ -4131,8 +5855,14 @@ function litePreset(config, options = {}) {
4131
5855
  if (dropped > 0) {
4132
5856
  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`);
4133
5857
  }
5858
+ if (options.compressRanges) {
5859
+ const count = (range) => activeCombos(typeof range === "string" ? parseRange(range) : range).length;
5860
+ 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`);
5861
+ }
4134
5862
  if (sampling) change("approximations.chanceSampling", void 0, sampling, samplingNote(sampling));
4135
- if (settle) change("settle", void 0, settle, "stops once the root play stops moving, not at an exploitability target");
5863
+ if (settle) {
5864
+ 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)"}`);
5865
+ }
4136
5866
  return { config: blueprint, options: solveOptions, changes: presetChanges(config, blueprint, settings, notes) };
4137
5867
  }
4138
5868
  function keepWithin(blueprint, options = {}) {
@@ -4201,6 +5931,11 @@ function bettingFrom(config, round) {
4201
5931
  };
4202
5932
  return out;
4203
5933
  }
5934
+ function exploitabilityInExact(lite, exact) {
5935
+ if (exact.solver.ctx.layout.shared) throw new Error("The Exact run shares histories; measure in one that keeps them apart");
5936
+ warmStart(exact.solver.ctx, lite.solver.ctx, true);
5937
+ return exact.exploitabilityPercent();
5938
+ }
4204
5939
 
4205
5940
  // src/index.ts
4206
5941
  var OPS_PER_SECOND = 2e8;
@@ -4238,6 +5973,9 @@ function defineSpot(config) {
4238
5973
  const rounds = 6 - board.length;
4239
5974
  if (config.pot <= 0) throw new Error("pot must be positive");
4240
5975
  if (config.stack <= 0) throw new Error("stack must be positive");
5976
+ if (config.evPot !== void 0 && !(Number.isFinite(config.evPot) && config.evPot > 0)) {
5977
+ throw new Error(`evPot must be a positive number of chips; got ${config.evPot}`);
5978
+ }
4241
5979
  const rows = betRows(config, rounds);
4242
5980
  const onBoard = new Set(board);
4243
5981
  const trim = (range, who) => {
@@ -4263,13 +6001,39 @@ function defineSpot(config) {
4263
6001
  }
4264
6002
  return weights;
4265
6003
  };
6004
+ const reserved = (range, who) => {
6005
+ if (range === void 0) return null;
6006
+ const hands = typeof range === "string" ? parseRange(range) : range;
6007
+ if (hands.length !== COMBOS) {
6008
+ throw new Error(`The ${who} reserve has ${hands.length} weights; one per combination is ${COMBOS}`);
6009
+ }
6010
+ const mask = new Float64Array(COMBOS);
6011
+ for (let combo = 0; combo < COMBOS; combo++) {
6012
+ if (hands[combo] > 0 && !onBoard.has(COMBO_CARDS[combo * 2]) && !onBoard.has(COMBO_CARDS[combo * 2 + 1])) mask[combo] = 1;
6013
+ }
6014
+ return mask;
6015
+ };
6016
+ const reserves = [reserved(config.oopReserve, "out-of-position"), reserved(config.ipReserve, "in-position")];
4266
6017
  const players = [
4267
- buildPlayerIndex(trim(config.oop, "out-of-position")),
4268
- buildPlayerIndex(trim(config.ip, "in-position"))
6018
+ buildPlayerIndex(trim(config.oop, "out-of-position"), reserves[0] ?? void 0),
6019
+ buildPlayerIndex(trim(config.ip, "in-position"), reserves[1] ?? void 0)
4269
6020
  ];
4270
- const symmetries = config.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights]);
6021
+ if (!holdable(players[0].weights, players[1].weights)) {
6022
+ throw new Error("No hand of one range can be held against a hand of the other: every pair shares a card");
6023
+ }
6024
+ for (const player of players) {
6025
+ if (config.maxCombos !== void 0 && player.count > config.maxCombos) {
6026
+ throw new Error(`A range and its reserve hold ${player.count} combinations, over the ${config.maxCombos} limit`);
6027
+ }
6028
+ }
6029
+ const symmetries = config.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights, ...reserves.filter((mask) => mask !== null)]);
4271
6030
  const merge = config.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config.runoutBuckets) : void 0;
4272
- const runouts = enumerateRunouts(board, symmetries, merge);
6031
+ const runouts = runoutsFor(board, symmetries, merge);
6032
+ const symmetryCombos = (symmetries ?? []).map((map) => {
6033
+ const image = new Uint16Array(COMBOS);
6034
+ for (let combo = 0; combo < COMBOS; combo++) image[combo] = comboIndex(map[COMBO_CARDS[combo * 2]], map[COMBO_CARDS[combo * 2 + 1]]);
6035
+ return image;
6036
+ }).filter((image) => image.some((combo, at) => combo !== at));
4273
6037
  const tree = buildTree(treeConfig(config, rows), runouts);
4274
6038
  const historyAlias = config.shareHistories ? shareHistories(tree, runouts, config, chipScale) : void 0;
4275
6039
  const layout = buildLayout(tree, runouts, players, 4, historyAlias);
@@ -4304,7 +6068,7 @@ function defineSpot(config) {
4304
6068
  suggestions
4305
6069
  };
4306
6070
  if (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);
4307
- return {
6071
+ const spot = {
4308
6072
  board,
4309
6073
  tree,
4310
6074
  runouts,
@@ -4319,7 +6083,52 @@ function defineSpot(config) {
4319
6083
  return resolveBoard(runouts, typeof cards === "string" ? parseCards(cards) : cards);
4320
6084
  }
4321
6085
  };
6086
+ spotSymmetries.set(spot, symmetryCombos);
6087
+ return spot;
6088
+ }
6089
+ var RANGE_RESUME = 10;
6090
+ var builtFrom = /* @__PURE__ */ new WeakMap();
6091
+ var keptRunouts = null;
6092
+ function runoutsFor(board, symmetries, merge) {
6093
+ let key = `${board.join(",")}|${(symmetries ?? []).map((map) => map.join(",")).join(";")}|`;
6094
+ if (merge) {
6095
+ key += `${merge.maxGap}:`;
6096
+ for (let a = 0; a < 13; a++) for (let b = 0; b < 13; b++) key += merge.ranks(a, b) ? "1" : "0";
6097
+ }
6098
+ if (keptRunouts?.key !== key) keptRunouts = { key, runouts: enumerateRunouts(board, symmetries, merge) };
6099
+ return keptRunouts.runouts;
4322
6100
  }
6101
+ var keptTables = null;
6102
+ function setupTables(spot, relevant) {
6103
+ const [first, second] = [spot.players[0].combos, spot.players[1].combos];
6104
+ const same = (a, b) => a.length === b.length && a.every((combo, i) => combo === b[i]);
6105
+ if (keptTables && keptTables.runouts === spot.runouts && same(keptTables.combos[0], first) && same(keptTables.combos[1], second)) {
6106
+ return keptTables.tables;
6107
+ }
6108
+ keptTables = null;
6109
+ const showdown = buildShowdownTable(spot.runouts, relevant);
6110
+ const active = buildActiveLists(spot.runouts, spot.players, showdown);
6111
+ const hands = buildHandSpace(spot.runouts, spot.players, active);
6112
+ keptTables = { runouts: spot.runouts, combos: [first, second], tables: { showdown, active, hands } };
6113
+ return keptTables.tables;
6114
+ }
6115
+ function releaseSetupCache() {
6116
+ keptRunouts = null;
6117
+ keptTables = null;
6118
+ }
6119
+ function holdable(a, b) {
6120
+ for (let i = 0; i < COMBOS; i++) {
6121
+ if (!(a[i] > 0)) continue;
6122
+ const [c, d] = [COMBO_CARDS[i * 2], COMBO_CARDS[i * 2 + 1]];
6123
+ for (let j = 0; j < COMBOS; j++) {
6124
+ if (!(b[j] > 0)) continue;
6125
+ const [e, f] = [COMBO_CARDS[j * 2], COMBO_CARDS[j * 2 + 1]];
6126
+ if (c !== e && c !== f && d !== e && d !== f) return true;
6127
+ }
6128
+ }
6129
+ return false;
6130
+ }
6131
+ var spotSymmetries = /* @__PURE__ */ new WeakMap();
4323
6132
  function shareHistories(tree, runouts, config, chipScale) {
4324
6133
  const asked = config.shareHistories === true ? {} : config.shareHistories || {};
4325
6134
  const keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : void 0;
@@ -4366,6 +6175,8 @@ var TREE_SETTINGS = [
4366
6175
  "mergeSizes",
4367
6176
  "thinSizes"
4368
6177
  ];
6178
+ var RangeNotInPlaceError = class extends Error {
6179
+ };
4369
6180
  function createRun(spot, options = {}) {
4370
6181
  if (options.analysisOnly && options.approximations?.currentProfileEv) {
4371
6182
  throw new Error("approximations.currentProfileEv needs regrets, and an analysisOnly run has none");
@@ -4381,39 +6192,60 @@ function createRun(spot, options = {}) {
4381
6192
  const clash = clashes.find(([set]) => set)?.[1];
4382
6193
  if (clash) throw new Error(`compactStorage does not combine with ${clash}`);
4383
6194
  }
4384
- const precision = compact ? options.precision ?? "f32" : options.analysisOnly ? "f32" : options.precision ?? (bytes <= maxBytes ? "f32" : "i16");
4385
- const coarsePlan = planCoarseStart(spot, options, precision, maxBytes);
6195
+ const defaulted = !compact && !options.analysisOnly && options.precision === void 0;
6196
+ let precision = compact ? options.precision ?? "f32" : options.analysisOnly ? "f32" : options.precision ?? (bytes <= maxBytes ? "f32" : "i16");
4386
6197
  const relevant = new Uint8Array(COMBOS);
4387
6198
  for (const combo of spot.players[0].combos) relevant[combo] = 1;
4388
6199
  for (const combo of spot.players[1].combos) relevant[combo] = 1;
4389
- const showdown = buildShowdownTable(spot.runouts, relevant);
4390
- const layout = buildLayout(
6200
+ if (!options.analysisOnly && options.engine !== "js" && options.simd !== false && (options.workers ?? 1) !== 1) {
6201
+ const engineLikely = precision === "f32" && !compact || options.wasmStorage !== void 0 && precision !== "f64" && (precision === "i16" || compact !== null);
6202
+ const asked = engineLikely ? resolveWorkers(options, true) : 1;
6203
+ if (asked > 1 && planShards(spot.tree, spot.runouts, asked)) warmEngineThreads(asked - 1);
6204
+ }
6205
+ const { showdown, active, hands } = setupTables(spot, relevant);
6206
+ const layoutAt = (at) => buildLayout(
4391
6207
  spot.tree,
4392
6208
  spot.runouts,
4393
6209
  spot.players,
4394
- PRECISION_BYTES[precision],
6210
+ PRECISION_BYTES[at],
4395
6211
  spot.historyAlias,
4396
6212
  compact ?? void 0
4397
6213
  );
6214
+ let layout = layoutAt(precision);
4398
6215
  const weights = runoutWeights(spot.runouts);
6216
+ const samplingOptions = options.approximations?.chanceSampling;
6217
+ const samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : void 0;
6218
+ const storageAt = (at, of) => compact ? of.bytes : Math.max(at === "i16" ? spot.estimate.compressedBytes : bytes, of.bytes);
6219
+ const baselineBytes = samplingPlan ? samplingBytes(samplingPlan) : 0;
6220
+ if (defaulted && precision === "f32" && samplingPlan && storageAt("f32", layout) + baselineBytes > maxBytes) {
6221
+ precision = "i16";
6222
+ layout = layoutAt(precision);
6223
+ }
6224
+ let storageBytes = storageAt(precision, layout);
6225
+ if (samplingPlan && storageBytes + baselineBytes > maxBytes) {
6226
+ throw new Error(
6227
+ `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`
6228
+ );
6229
+ }
6230
+ const held = (at, of) => Math.max(storageAt(at, of), storageCost(spot, at)) + baselineBytes;
6231
+ let coarsePlan;
6232
+ try {
6233
+ coarsePlan = planCoarseStart(spot, options, maxBytes, held(precision, layout));
6234
+ } catch (error) {
6235
+ if (!(error instanceof CoarseRefusal && defaulted && precision === "f32")) throw error;
6236
+ precision = "i16";
6237
+ layout = layoutAt(precision);
6238
+ storageBytes = storageAt(precision, layout);
6239
+ coarsePlan = planCoarseStart(spot, { ...options, precision }, maxBytes, held(precision, layout));
6240
+ }
4399
6241
  const storageEngine = options.wasmStorage !== void 0 && precision !== "f64" && (precision === "i16" || compact !== null);
4400
6242
  const wantsEngine = options.engine !== "js" && !options.analysisOnly && options.simd !== false && (precision === "f32" && !compact || storageEngine);
4401
- const samplingOptions = options.approximations?.chanceSampling;
4402
6243
  const requested = resolveWorkers(options, wantsEngine);
4403
6244
  const shards = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;
4404
6245
  const plan = shards && samplingOptions && sampledRounds(samplingOptions, spot.runouts.rounds).some((r) => r < shards.round) ? null : shards;
4405
6246
  const allocate = (bytes2) => plan ? new SharedArrayBuffer(bytes2) : new ArrayBuffer(bytes2);
4406
6247
  const width = PRECISION_BYTES[precision];
4407
6248
  const quantised = precision === "i16";
4408
- const active = buildActiveLists(spot.runouts, spot.players, showdown);
4409
- const hands = buildHandSpace(spot.runouts, spot.players, active);
4410
- const samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : void 0;
4411
- const storageBytes = compact ? layout.bytes : Math.max(quantised ? spot.estimate.compressedBytes : bytes, layout.bytes);
4412
- if (samplingPlan && storageBytes + samplingBytes(samplingPlan) > maxBytes) {
4413
- throw new Error(
4414
- `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`
4415
- );
4416
- }
4417
6249
  const engine = wantsEngine ? createEngine(
4418
6250
  {
4419
6251
  tree: spot.tree,
@@ -4494,8 +6326,9 @@ function createRun(spot, options = {}) {
4494
6326
  }
4495
6327
  if (warm) ctx.sampling?.lastUpdate.fill(offset);
4496
6328
  solver = makeSolver(ctx);
6329
+ if (engine?.profile) threadProfiles.set(solver, engine.profile);
4497
6330
  if (warm && coarsePlan) coarseMs.set(solver, coarsePlan.elapsed);
4498
- pool = plan && !engine ? startPool(ctx, solver, plan, { config: spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd, compact }, requested) : null;
6331
+ 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;
4499
6332
  } catch (error) {
4500
6333
  engine?.close();
4501
6334
  throw error;
@@ -4504,6 +6337,7 @@ function createRun(spot, options = {}) {
4504
6337
  if (engine) solver.useRoot(engine.root(ctx.dcfr));
4505
6338
  const threadCount = pool ? pool.workers : engine ? engine.threads : 1;
4506
6339
  let completed = 0;
6340
+ const nextRange = new Float64Array(COMBOS);
4507
6341
  return {
4508
6342
  spot,
4509
6343
  solver,
@@ -4521,6 +6355,69 @@ function createRun(spot, options = {}) {
4521
6355
  solver.iterate(count, offset + completed);
4522
6356
  completed += count;
4523
6357
  },
6358
+ setRange(player, range, options2 = {}) {
6359
+ if (options2.resume !== void 0 && !(Number.isInteger(options2.resume) && options2.resume >= 0)) {
6360
+ throw new Error(`setRange: resume must be a whole number of iterations; got ${options2.resume}`);
6361
+ }
6362
+ const given = typeof range === "string" ? parseRange(range) : range;
6363
+ if (given.length !== COMBOS) {
6364
+ throw new Error(`setRange: the range has ${given.length} weights; one per combination is ${COMBOS}`);
6365
+ }
6366
+ const index = spot.players[player];
6367
+ const floor = spot.source.minWeight ?? 0;
6368
+ const [first, second, third] = spot.board;
6369
+ const fourth = spot.board[3] ?? -1;
6370
+ const fifth = spot.board[4] ?? -1;
6371
+ const blocked = (card) => card === first || card === second || card === third || card === fourth || card === fifth;
6372
+ let live = 0;
6373
+ let unstored = -1;
6374
+ for (let combo = 0; combo < COMBOS; combo++) {
6375
+ let weight = given[combo];
6376
+ if (!(weight >= 0)) throw new Error(`setRange: a weight is ${weight}; weights are zero or more`);
6377
+ if (weight < floor) weight = 0;
6378
+ if (weight > 0 && index.slot[combo] < 0) {
6379
+ if (blocked(COMBO_CARDS[combo * 2]) || blocked(COMBO_CARDS[combo * 2 + 1])) weight = 0;
6380
+ else if (unstored < 0) unstored = combo;
6381
+ }
6382
+ if (weight > 0) live++;
6383
+ nextRange[combo] = weight;
6384
+ }
6385
+ if (live === 0) throw new Error("setRange: the range is empty once the board is removed");
6386
+ if (!holdable(nextRange, spot.players[1 - player].weights)) {
6387
+ throw new Error("setRange: no hand of this range can be held against the other range");
6388
+ }
6389
+ if (unstored >= 0) {
6390
+ throw new RangeNotInPlaceError(
6391
+ `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`
6392
+ );
6393
+ }
6394
+ for (const image of spotSymmetries.get(spot) ?? []) {
6395
+ for (let combo = 0; combo < COMBOS; combo++) {
6396
+ if (nextRange[combo] !== nextRange[image[combo]]) {
6397
+ throw new RangeNotInPlaceError(
6398
+ "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`"
6399
+ );
6400
+ }
6401
+ }
6402
+ }
6403
+ index.weights.set(nextRange);
6404
+ if (!builtFrom.has(spot)) builtFrom.set(spot, spot.source);
6405
+ const stored = Float64Array.from(index.slot, (slot) => slot >= 0 ? 1 : 0);
6406
+ spot.source = player === 0 ? { ...spot.source, oop: nextRange.slice(), oopReserve: stored } : { ...spot.source, ip: nextRange.slice(), ipReserve: stored };
6407
+ let resumed = offset + completed;
6408
+ if (ctx.dcfr) {
6409
+ resumed = Math.min(resumed, options2.resume ?? RANGE_RESUME);
6410
+ offset = resumed - completed;
6411
+ } else if (ctx.regret.length > 0 || ctx.compactRegret) {
6412
+ ctx.strategySum.fill(0);
6413
+ ctx.sumScale?.fill(0);
6414
+ ctx.compactSum?.forEach((sums) => sums.fill(0));
6415
+ ctx.sumShift?.forEach((shifts) => shifts.fill(0));
6416
+ }
6417
+ ctx.discounted?.fill(0);
6418
+ ctx.sampling?.lastWalk.fill(0);
6419
+ ctx.sampling?.lastUpdate.fill(resumed);
6420
+ },
4524
6421
  close() {
4525
6422
  solver.useRoot(null);
4526
6423
  pool?.close();
@@ -4584,8 +6481,10 @@ function compactPlan(settings, rounds) {
4584
6481
  };
4585
6482
  }
4586
6483
  var DEFAULT_COARSE_GAP = 3;
6484
+ var CoarseRefusal = class extends Error {
6485
+ };
4587
6486
  var coarseMs = /* @__PURE__ */ new WeakMap();
4588
- function planCoarseStart(spot, options, precision, maxBytes) {
6487
+ function planCoarseStart(spot, options, maxBytes, used) {
4589
6488
  const settings = options.approximations?.coarseStart;
4590
6489
  if (!settings) return null;
4591
6490
  const { iterations, runoutBuckets = DEFAULT_COARSE_GAP } = settings;
@@ -4602,15 +6501,17 @@ function planCoarseStart(spot, options, precision, maxBytes) {
4602
6501
  if (iterations === 0 || spot.board.length === 5 || runoutBuckets <= ownGap) return null;
4603
6502
  const coarseSpot = defineSpot({ ...spot.source, runoutBuckets });
4604
6503
  if (coarseSpot.runouts.counts.at(-1) >= spot.runouts.counts.at(-1)) return null;
4605
- const used = storageCost(spot, precision);
4606
6504
  const left = maxBytes - used;
4607
- const coarsePrecision = options.precision ?? (storageCost(coarseSpot, "f32") <= left ? "f32" : "i16");
4608
- const needs = storageCost(coarseSpot, coarsePrecision);
4609
- if (needs > left) {
4610
- throw new Error(
4611
- `coarseStart needs ~${formatBytes(needs)} beside this spot's ~${formatBytes(used)}, over the ${formatBytes(maxBytes)} limit; raise maxBytes or leave coarseStart off`
4612
- );
4613
- }
6505
+ const sampling = options.approximations?.chanceSampling;
6506
+ const refuse = (needs2) => new CoarseRefusal(
6507
+ `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`
6508
+ );
6509
+ const narrowest = storageCost(coarseSpot, options.precision ?? "i16");
6510
+ if (narrowest > left) throw refuse(narrowest);
6511
+ const coarseBaselines = sampling ? baselineCost(coarseSpot, sampling) : 0;
6512
+ const coarsePrecision = options.precision ?? (storageCost(coarseSpot, "f32") + coarseBaselines <= left ? "f32" : "i16");
6513
+ const needs = storageCost(coarseSpot, coarsePrecision) + coarseBaselines;
6514
+ if (needs > left) throw refuse(needs);
4614
6515
  return { spot: coarseSpot, iterations, precision: coarsePrecision, elapsed: 0 };
4615
6516
  }
4616
6517
  function solveCoarse(plan, options) {
@@ -4634,6 +6535,15 @@ function solveCoarse(plan, options) {
4634
6535
  plan.elapsed = Date.now() - started;
4635
6536
  return run;
4636
6537
  }
6538
+ function baselineCost(of, sampling) {
6539
+ const relevant = new Uint8Array(COMBOS);
6540
+ for (const combo of of.players[0].combos) relevant[combo] = 1;
6541
+ for (const combo of of.players[1].combos) relevant[combo] = 1;
6542
+ const active = buildActiveLists(of.runouts, of.players, buildShowdownTable(of.runouts, relevant));
6543
+ const compact = of.source.compactStorage ? compactPlan(of.source.compactStorage, of.runouts.rounds) : void 0;
6544
+ const layout = buildLayout(of.tree, of.runouts, of.players, 4, of.historyAlias, compact);
6545
+ return samplingBytes(planSampling(of.tree, of.runouts, active, layout, sampling));
6546
+ }
4637
6547
  function storageCost(of, at) {
4638
6548
  if (of.estimate.compactBytes === null) {
4639
6549
  return at === "i16" ? of.estimate.compressedBytes : of.estimate.bytes * (at === "f64" ? 2 : 1);
@@ -4643,7 +6553,7 @@ function storageCost(of, at) {
4643
6553
  return of.estimate.compactBytes + bytesAt(PRECISION_BYTES[at]) - bytesAt(4);
4644
6554
  }
4645
6555
  function sameSpot(a, b) {
4646
- const plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, ...game }) => JSON.stringify(game, (_, value) => value instanceof Float64Array ? Array.from(value) : value);
6556
+ const plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, evPot: _evPot, ...game }) => JSON.stringify(game, (_, value) => value instanceof Float64Array ? Array.from(value) : value);
4647
6557
  const kept = (config) => typeof config.shareHistories === "object" ? config.shareHistories.keepLines : void 0;
4648
6558
  if (kept(a) === void 0 && kept(b) === void 0) return plain(a) === plain(b);
4649
6559
  const mine = new Set(kept(a) ?? []);
@@ -4700,19 +6610,25 @@ function makeSumStore(precision, buffer) {
4700
6610
  return precision === "f32" ? new Float32Array(buffer) : new Uint16Array(buffer);
4701
6611
  }
4702
6612
  function solve(spot, options = {}) {
4703
- const iterations = options.iterations ?? 500;
4704
- const target = options.targetPercent ?? 0;
4705
- const fixed = options.exploitEvery ?? 0;
4706
- const settle = options.settle ? settlePlan(options.settle) : null;
6613
+ if (options.settle) settlePlan(options.settle);
4707
6614
  const run = createRun(spot, options);
4708
- const history = [];
4709
- const started = Date.now() - (coarseMs.get(run.solver) ?? 0);
4710
- const before = coarseMs.has(run.solver) ? run.totalIterations : 0;
4711
6615
  try {
4712
- return runAll();
6616
+ return runToStop(run, options);
4713
6617
  } finally {
4714
6618
  run.close();
4715
6619
  }
6620
+ }
6621
+ function runToStop(run, options = {}) {
6622
+ const { spot } = run;
6623
+ const iterations = options.iterations ?? 500;
6624
+ const target = options.targetPercent ?? 0;
6625
+ const fixed = options.exploitEvery ?? 0;
6626
+ const settle = options.settle ? settlePlan(options.settle) : null;
6627
+ const history = [];
6628
+ const coarse = run.completed === 0 ? coarseMs.get(run.solver) : void 0;
6629
+ const started = Date.now() - (coarse ?? 0);
6630
+ const before = coarse !== void 0 ? run.totalIterations : 0;
6631
+ return runAll();
4716
6632
  function runAll() {
4717
6633
  if (settle) return runSettled(settle);
4718
6634
  if (fixed <= 0 && target <= 0) {
@@ -4761,6 +6677,7 @@ function solve(spot, options = {}) {
4761
6677
  }
4762
6678
  function runSettled(plan) {
4763
6679
  const tracker = trackSettle(plan);
6680
+ if (run.completed > 0) tracker.check(run.snapshot(), 0);
4764
6681
  let stoppedAt = "iterations";
4765
6682
  let done = 0;
4766
6683
  while (done < iterations) {
@@ -4840,7 +6757,10 @@ function makeSolution(spot, solver, iterations, totalIterations, history, stoppe
4840
6757
  let cachedEv = null;
4841
6758
  const rootValues = () => cachedEv ??= solver.rootValues(currentProfileEv ? Mode.Current : Mode.Average);
4842
6759
  const cachedHands = [null, null];
6760
+ const cachedChips = [null, null];
4843
6761
  let cachedExploit = null;
6762
+ const evPot = spot.source.evPot ?? spot.potUnits / spot.chipScale;
6763
+ const share = (chips) => 100 * (chips + evPot / 2) / evPot;
4844
6764
  return {
4845
6765
  spot,
4846
6766
  iterations,
@@ -4849,13 +6769,21 @@ function makeSolution(spot, solver, iterations, totalIterations, history, stoppe
4849
6769
  workers,
4850
6770
  solver,
4851
6771
  history,
6772
+ evPot,
4852
6773
  ev(player) {
6774
+ return share(rootValues().totals[player]);
6775
+ },
6776
+ evChips(player) {
4853
6777
  return rootValues().totals[player];
4854
6778
  },
4855
6779
  handEvs(player) {
4856
- cachedHands[player] ??= solver.handEvs(player, rootValues().values[player]);
6780
+ cachedHands[player] ??= solver.handEvs(player, rootValues().values[player], share);
4857
6781
  return cachedHands[player].slice();
4858
6782
  },
6783
+ handEvsChips(player) {
6784
+ cachedChips[player] ??= solver.handEvs(player, rootValues().values[player]);
6785
+ return cachedChips[player].slice();
6786
+ },
4859
6787
  exploitability() {
4860
6788
  cachedExploit ??= solver.exploitability();
4861
6789
  return cachedExploit;
@@ -4907,6 +6835,8 @@ function makeSolution(spot, solver, iterations, totalIterations, history, stoppe
4907
6835
  return {
4908
6836
  board: formatCards(cards),
4909
6837
  pot: tree.pot[node] / spot.chipScale,
6838
+ // EV stays a share of the original spot's pot down a hand.
6839
+ evPot,
4910
6840
  stack: (spot.stackUnits - invested) / spot.chipScale,
4911
6841
  oop: reachAt(node, board, 0),
4912
6842
  ip: reachAt(node, board, 1),
@@ -4942,7 +6872,9 @@ export {
4942
6872
  NodeKind,
4943
6873
  PLATFORM,
4944
6874
  PRECISION_BYTES,
6875
+ RANGE_RESUME,
4945
6876
  RANKS,
6877
+ RangeNotInPlaceError,
4946
6878
  SUITS,
4947
6879
  SpotTooLargeError,
4948
6880
  activeCombos,
@@ -4951,10 +6883,12 @@ export {
4951
6883
  categoryOf,
4952
6884
  checkedDown,
4953
6885
  comboIndex,
6886
+ compressRanges,
4954
6887
  createRun,
4955
6888
  defineSpot,
4956
6889
  evaluate,
4957
6890
  evaluateCards,
6891
+ exploitabilityInExact,
4958
6892
  formatCard,
4959
6893
  formatCards,
4960
6894
  formatCombo,
@@ -4964,6 +6898,7 @@ export {
4964
6898
  litePreset,
4965
6899
  makeRegretStore,
4966
6900
  makeSumStore,
6901
+ openLite,
4967
6902
  parseCard,
4968
6903
  parseCards,
4969
6904
  parseRange,
@@ -4971,10 +6906,12 @@ export {
4971
6906
  rangeWeight,
4972
6907
  rankOf,
4973
6908
  rankSwap,
6909
+ releaseSetupCache,
4974
6910
  resolveSubgame,
4975
6911
  rootPlay,
4976
6912
  rootPlayMovement,
4977
6913
  rootPlayNodes,
6914
+ runToStop,
4978
6915
  simdAvailable,
4979
6916
  solve,
4980
6917
  solveLite,
@@ -4984,4 +6921,25 @@ export {
4984
6921
  trackSettle,
4985
6922
  turnLineReach
4986
6923
  };
6924
+ /*!
6925
+ * Vendored from https://github.com/DarraghGeo/poker-rangecompress (dist/range-compress.js) by
6926
+ * scripts/vendor-range-compress.ts: an ES module, single-threaded. Do not edit here.
6927
+ *
6928
+ * range-compress.js — shrink a poker range for a postflop solver while keeping how the range plays.
6929
+ *
6930
+ * What it does: given a player's range, the opponent's range and a flop, it keeps a subset of the combos
6931
+ * and re-weights them so that, on every turn and river the solver will deal, the range still has the same
6932
+ * distribution of hand strength. The result is an ordinary range (combos with weights 0..1).
6933
+ *
6934
+ * What it preserves: how often the range as a whole takes each action, and how its strong / medium / weak
6935
+ * parts act. What it does not preserve: what an individual combo does (see README).
6936
+ *
6937
+ * No dependencies. Works in browsers (global `RangeCompress`), web workers and Node (CommonJS).
6938
+ * Cards are 4*rank+suit with rank 0..12 = 2..A and suit 0..3 = c,d,h,s.
6939
+ *
6940
+ * Speed notes (v2): hands are never evaluated one by one. On each board the 91 rank classes are valued once
6941
+ * from rank-count bit masks (the suit-lane idea of poker-bitvaljs), flushes are patched in from a 13-bit
6942
+ * lane table, equities with exact card removal come from per-card prefix tables instead of sorting, and
6943
+ * the linear algebra works on suit orbits with a Cholesky inverse and triangular updates.
6944
+ */
4987
6945
  //# sourceMappingURL=browser.js.map