poker-flopsolve 0.5.0-beta.1 → 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;
@@ -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,113 +1789,120 @@ function buildActiveLists(runouts, players, showdown = null) {
1764
1789
  const start = new Int32Array(slots);
1765
1790
  const count = new Uint16Array(slots);
1766
1791
  const packedSlot = new Uint8Array(slots);
1767
- const entries = [];
1768
- const entrySlots = [];
1769
- const memberStart = [];
1770
- const members = [];
1792
+ const capacity = roundBase[runouts.rounds] * (players[0].count + players[1].count);
1793
+ const list = new Uint16Array(capacity);
1794
+ const entrySlot = new Uint16Array(capacity);
1795
+ const strength = new Int32Array(capacity);
1796
+ const memberStart = new Int32Array(capacity + 1);
1797
+ let members = new Uint16Array(capacity);
1771
1798
  const onBoard = new Uint8Array(DECK);
1772
1799
  const seen = new Uint8Array(COMBOS);
1800
+ const comboMaps = runouts.maps.combo;
1801
+ const last = runouts.rounds - 1;
1802
+ let entries = 0;
1803
+ let memberCount = 0;
1773
1804
  for (let round = 0; round < runouts.rounds; round++) {
1774
1805
  const width = runouts.width[round];
1775
1806
  const cards = runouts.cards[round];
1776
1807
  const stabStart = runouts.stabiliserStart[round];
1777
1808
  const stabMap = runouts.stabiliserMap[round];
1809
+ const ranked = showdown !== null && round === last ? showdown : null;
1778
1810
  for (let board = 0; board < runouts.counts[round]; board++) {
1779
1811
  onBoard.fill(0);
1780
1812
  for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1781
- const symmetric = stabStart[board + 1] - stabStart[board] > 1;
1813
+ const stabFrom = stabStart[board] + 1;
1814
+ const stabTo = stabStart[board + 1];
1815
+ const symmetric = stabTo > stabFrom;
1816
+ if (memberCount + (players[0].count + players[1].count) * (stabTo - stabFrom + 1) > members.length) {
1817
+ const grown = new Uint16Array(Math.max(members.length * 2, memberCount + (players[0].count + players[1].count) * (stabTo - stabFrom + 1)));
1818
+ grown.set(members.subarray(0, memberCount));
1819
+ members = grown;
1820
+ }
1782
1821
  for (let player = 0; player < 2; player++) {
1783
1822
  const index = players[player];
1784
1823
  const slot = (roundBase[round] + board) * 2 + player;
1785
- start[slot] = entries.length;
1786
- const here = [];
1787
- for (let i = 0; i < index.count; i++) {
1788
- const combo = index.combos[i];
1789
- if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1790
- if (symmetric && !orbitLeader(runouts, round, board, combo)) continue;
1791
- here.push(i);
1792
- }
1793
- if (showdown !== null && round === runouts.rounds - 1) {
1794
- const group = strengthOn(showdown, board);
1795
- here.sort((x, y) => group[index.combos[x]] - group[index.combos[y]] || x - y);
1796
- }
1797
- for (const i of here) {
1798
- const combo = index.combos[i];
1799
- entries.push(combo);
1800
- entrySlots.push(i);
1801
- memberStart.push(members.length);
1802
- members.push(combo);
1803
- if (!symmetric) continue;
1804
- seen[combo] = 1;
1805
- for (let k = stabStart[board] + 1; k < stabStart[board + 1]; k++) {
1806
- const image = runouts.maps.combo[stabMap[k]][combo];
1807
- if (seen[image]) continue;
1808
- seen[image] = 1;
1809
- members.push(image);
1810
- packedSlot[slot] = 1;
1824
+ start[slot] = entries;
1825
+ const candidates = ranked ? ranked.liveCount[board] : index.count;
1826
+ const orderBase = ranked ? board * ranked.stride : 0;
1827
+ const groupBase = ranked ? board * (ranked.stride + 1) : 0;
1828
+ let group = 0;
1829
+ for (let c = 0; c < candidates; c++) {
1830
+ let combo;
1831
+ let at;
1832
+ if (ranked) {
1833
+ while (c >= ranked.groupStart[groupBase + group + 1]) group++;
1834
+ combo = ranked.order[orderBase + c];
1835
+ at = index.slot[combo];
1836
+ if (at < 0) continue;
1837
+ } else {
1838
+ at = c;
1839
+ combo = index.combos[c];
1840
+ if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1841
+ }
1842
+ let leader = true;
1843
+ for (let k = stabFrom; k < stabTo; k++) {
1844
+ if (comboMaps[stabMap[k]][combo] < combo) {
1845
+ leader = false;
1846
+ break;
1847
+ }
1811
1848
  }
1812
- for (let m = memberStart[memberStart.length - 1]; m < members.length; m++) seen[members[m]] = 0;
1849
+ if (!leader) continue;
1850
+ list[entries] = combo;
1851
+ entrySlot[entries] = at;
1852
+ strength[entries] = group;
1853
+ memberStart[entries] = memberCount;
1854
+ members[memberCount++] = combo;
1855
+ if (symmetric) {
1856
+ const first = memberCount - 1;
1857
+ seen[combo] = 1;
1858
+ for (let k = stabFrom; k < stabTo; k++) {
1859
+ const image = comboMaps[stabMap[k]][combo];
1860
+ if (seen[image]) continue;
1861
+ seen[image] = 1;
1862
+ members[memberCount++] = image;
1863
+ packedSlot[slot] = 1;
1864
+ }
1865
+ for (let m = first; m < memberCount; m++) seen[members[m]] = 0;
1866
+ }
1867
+ entries++;
1813
1868
  }
1814
- count[slot] = entries.length - start[slot];
1869
+ count[slot] = entries - start[slot];
1815
1870
  }
1816
1871
  }
1817
1872
  }
1818
- memberStart.push(members.length);
1819
- const list = Uint16Array.from(entries);
1820
- const cardA = new Uint8Array(list.length);
1821
- const cardB = new Uint8Array(list.length);
1822
- const multiplicity = new Float64Array(list.length);
1823
- for (let e = 0; e < list.length; e++) {
1873
+ memberStart[entries] = memberCount;
1874
+ const cardA = new Uint8Array(entries);
1875
+ const cardB = new Uint8Array(entries);
1876
+ const multiplicity = new Float64Array(entries);
1877
+ for (let e = 0; e < entries; e++) {
1824
1878
  cardA[e] = COMBO_CARDS[list[e] * 2];
1825
1879
  cardB[e] = COMBO_CARDS[list[e] * 2 + 1];
1826
1880
  multiplicity[e] = memberStart[e + 1] - memberStart[e];
1827
1881
  }
1828
- const memberCombo = Uint16Array.from(members);
1829
- const memberA = new Uint8Array(members.length);
1830
- const memberB = new Uint8Array(members.length);
1831
- for (let m = 0; m < members.length; m++) {
1832
- memberA[m] = COMBO_CARDS[members[m] * 2];
1833
- memberB[m] = COMBO_CARDS[members[m] * 2 + 1];
1834
- }
1835
- const strength = new Int32Array(list.length);
1836
- if (showdown !== null) {
1837
- const last = runouts.rounds - 1;
1838
- for (let board = 0; board < runouts.counts[last]; board++) {
1839
- const group = strengthOn(showdown, board);
1840
- for (let player = 0; player < 2; player++) {
1841
- const slot = (roundBase[last] + board) * 2 + player;
1842
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) strength[e] = group[list[e]];
1843
- }
1844
- }
1882
+ const memberCombo = members.slice(0, memberCount);
1883
+ const memberA = new Uint8Array(memberCount);
1884
+ const memberB = new Uint8Array(memberCount);
1885
+ for (let m = 0; m < memberCount; m++) {
1886
+ memberA[m] = COMBO_CARDS[memberCombo[m] * 2];
1887
+ memberB[m] = COMBO_CARDS[memberCombo[m] * 2 + 1];
1845
1888
  }
1846
1889
  return {
1847
1890
  start,
1848
1891
  count,
1849
- list,
1850
- slot: Uint16Array.from(entrySlots),
1892
+ list: list.slice(0, entries),
1893
+ slot: entrySlot.slice(0, entries),
1851
1894
  roundBase,
1852
1895
  cardA,
1853
1896
  cardB,
1854
- strength,
1897
+ strength: strength.slice(0, entries),
1855
1898
  packed: packedSlot,
1856
1899
  multiplicity,
1857
- memberStart: Int32Array.from(memberStart),
1900
+ memberStart: memberStart.slice(0, entries + 1),
1858
1901
  memberCombo,
1859
1902
  memberA,
1860
1903
  memberB
1861
1904
  };
1862
1905
  }
1863
- var strengthScratch = new Int32Array(COMBOS);
1864
- function strengthOn(table, board) {
1865
- const orderBase = board * table.stride;
1866
- const groupBase = board * (table.stride + 1);
1867
- for (let g = 0; g < table.groupCount[board]; g++) {
1868
- for (let i = table.groupStart[groupBase + g]; i < table.groupStart[groupBase + g + 1]; i++) {
1869
- strengthScratch[table.order[orderBase + i]] = g;
1870
- }
1871
- }
1872
- return strengthScratch;
1873
- }
1874
1906
  function makeBuffers2(tree, maxActions, simd) {
1875
1907
  const depth = treeDepth2(tree) + 2;
1876
1908
  const make = (factory2) => Array.from({ length: depth }, factory2);
@@ -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,
@@ -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");
@@ -3000,6 +3034,33 @@ function scheduleViews(buffer, boards) {
3000
3034
  cost: new Float64Array(buffer, Math.ceil(boards / 2) * 8, 2 * boards)
3001
3035
  };
3002
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
+ }
3003
3064
  var MAX_MEMORY = 4294901760;
3004
3065
  var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, next: 7, size: 8 };
3005
3066
  function createEngine(input, pool) {
@@ -3024,15 +3085,16 @@ function createEngine(input, pool) {
3024
3085
  const [upRound, upStart] = flatten(hands.upStart);
3025
3086
  const [childRound, childStart] = flatten(runouts.childStart);
3026
3087
  const [orbitRound, orbitStart] = flatten(runouts.orbitStart);
3027
- 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];
3028
3090
  const stride = Math.ceil(maxCount / 4) * 4;
3029
3091
  const maxActions = Math.max(1, layout.maxActions);
3030
3092
  const depths = treeDepth2(tree) + 2;
3031
3093
  const rowBytes = stride * 4;
3032
3094
  const depthBytes = rowBytes * (3 + 2 * maxActions);
3033
3095
  const pieces = [];
3034
- const add = (data, bytes2 = data ? data.byteLength : 0) => {
3035
- 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 });
3036
3098
  return pieces.length - 1;
3037
3099
  };
3038
3100
  const common = [
@@ -3047,12 +3109,12 @@ function createEngine(input, pool) {
3047
3109
  add(layout.rowStart),
3048
3110
  add(active.roundBase),
3049
3111
  add(active.start),
3050
- add(Int32Array.from(active.count)),
3112
+ add(new Int32Array(active.count)),
3051
3113
  add(active.cardA),
3052
3114
  add(active.cardB),
3053
3115
  add(active.strength),
3054
3116
  add(active.packed),
3055
- add(Float32Array.from(active.multiplicity)),
3117
+ add(new Float32Array(active.multiplicity)),
3056
3118
  add(active.memberStart),
3057
3119
  add(active.memberA),
3058
3120
  add(active.memberB),
@@ -3078,7 +3140,7 @@ function createEngine(input, pool) {
3078
3140
  cardSums: add(null, 52 * 8 + stride * 8),
3079
3141
  rootMe: add(null, rowBytes),
3080
3142
  rootOpp: add(null, rowBytes),
3081
- header: add(null, 40 * 4)
3143
+ header: add(null, 40 * 4, false)
3082
3144
  }));
3083
3145
  const entries = pool ? pool.plan.entryNodes.length : 0;
3084
3146
  const entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;
@@ -3102,13 +3164,13 @@ function createEngine(input, pool) {
3102
3164
  } : null;
3103
3165
  const chunks = compact ? layout.chunkSlots.length : 0;
3104
3166
  const stored = storage ? {
3105
- block: add(null, 128),
3167
+ block: add(null, 128, false),
3106
3168
  blockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),
3107
3169
  regretScale: quantised ? add(null, layout.blocks * 8) : -1,
3108
3170
  sumScale: quantised ? add(null, layout.blocks * 8) : -1,
3109
3171
  compactChunk: compact ? add(layout.compactChunk) : -1,
3110
- handOffset: compact ? add(Int32Array.from(layout.handOffset)) : -1,
3111
- 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,
3112
3174
  regrets: layout.chunkSlots.map((slots) => add(null, slots * (compact.float ? 4 : 1))),
3113
3175
  shifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],
3114
3176
  sums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],
@@ -3128,6 +3190,10 @@ function createEngine(input, pool) {
3128
3190
  pieces.forEach((piece, i) => {
3129
3191
  if (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);
3130
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
+ );
3131
3197
  for (const mine of own) {
3132
3198
  const head = new Uint32Array(memory.buffer, offsets[mine.header], 40);
3133
3199
  common.forEach((slot, i) => head[i] = offsets[slot]);
@@ -3236,6 +3302,7 @@ function createEngine(input, pool) {
3236
3302
  let schedule = null;
3237
3303
  const workers = [];
3238
3304
  let failure = null;
3305
+ if (!pool) touchStorage(bytes, touch[0]);
3239
3306
  if (pool) {
3240
3307
  const plan2 = pool.plan;
3241
3308
  const controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);
@@ -3267,7 +3334,8 @@ function createEngine(input, pool) {
3267
3334
  ...share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] } : {},
3268
3335
  ...stored ? { storage: true } : {},
3269
3336
  ...samplingArgs ? { sampling: samplingArgs } : {},
3270
- profile: [profileBuffer, PROFILE.busy + w]
3337
+ profile: [profileBuffer, PROFILE.busy + w],
3338
+ touch: touch[w]
3271
3339
  };
3272
3340
  workers.push(pool.spawn(setup, (error) => {
3273
3341
  failure ??= error;
@@ -3277,6 +3345,7 @@ function createEngine(input, pool) {
3277
3345
  Atomics.notify(control, ENGINE_CONTROL.ready);
3278
3346
  }));
3279
3347
  }
3348
+ touchStorage(bytes, touch[0]);
3280
3349
  const deadline = Date.now() + WORKER_START_MS;
3281
3350
  for (; ; ) {
3282
3351
  const ready = Atomics.load(control, ENGINE_CONTROL.ready);
@@ -3569,70 +3638,119 @@ function warmStart(to, from, averages, cards, tolerance = SIZE_TOLERANCE) {
3569
3638
  const newSum = new Float64Array(width);
3570
3639
  const keepsRegrets = (ctx) => ctx.regret.length > 0 || (ctx.compactRegret ?? null) !== null;
3571
3640
  const hasRegret = keepsRegrets(to) && keepsRegrets(from);
3572
- 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();
3573
3644
  let matched = 0;
3574
3645
  for (const node of tree.decisionNodes) {
3575
3646
  const old = match[node];
3576
3647
  if (old < 0) continue;
3577
3648
  matched++;
3578
- const round = tree.round[node];
3579
- const owner = tree.player[node];
3580
3649
  const actions = tree.numEdges[node];
3581
- const oldActions = from.tree.numEdges[old];
3582
3650
  const actionOf = new Int32Array(actions).fill(-1);
3583
3651
  for (let e = 0; e < actions; e++) {
3584
3652
  const other = matchEdge(tree, tree.firstEdge[node] + e, node, from.tree, old, tolerance);
3585
3653
  if (other >= 0) actionOf[e] = other - from.tree.firstEdge[old];
3586
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;
3587
3663
  for (let board = 0; board < to.runouts.counts[round]; board++) {
3588
3664
  const resolved = resolveBoard(from.runouts, asSource(realCards(to.runouts, round, board)));
3589
- const oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;
3590
- const oldFrom = from.active.start[oldSlot];
3591
- const oldCount = from.active.count[oldSlot];
3592
- const oldBlock = from.layout.blockOffset[old] + resolved.board;
3593
- const oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];
3594
- const oldLength = oldActions * oldCount;
3595
- if (round >= from.layout.compactFrom) {
3596
- readCompactBlock(from, old, oldSlot, oldBlock, oldBase, oldActions, oldCount, hasRegret ? oldRegret : null, oldSum);
3597
- } else {
3598
- if (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);
3599
- readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);
3600
- }
3601
- markMembers(from.active, oldFrom, oldCount, position, false);
3602
- const newSlot = (to.active.roundBase[round] + board) * 2 + owner;
3603
- const newFrom = to.active.start[newSlot];
3604
- const count = to.active.count[newSlot];
3605
- const length = actions * count;
3606
- newRegret.fill(0, 0, length);
3607
- newSum.fill(0, 0, length);
3608
- for (let i = 0; i < count; i++) {
3609
- const firstMember = to.active.memberStart[newFrom + i];
3610
- const membersEnd = to.active.memberStart[newFrom + i + 1];
3611
- const share = 1 / (membersEnd - firstMember);
3612
- for (let m = firstMember; m < membersEnd; m++) {
3613
- const j = position[resolved.combos[comboOf[to.active.memberCombo[m]]]];
3614
- 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);
3615
3707
  for (let e = 0; e < actions; e++) {
3616
3708
  const action = actionOf[e];
3617
3709
  if (action < 0) continue;
3618
- newRegret[e * count + i] += share * oldRegret[action * oldCount + j];
3619
- 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);
3620
3732
  }
3621
3733
  }
3622
3734
  }
3623
- markMembers(from.active, oldFrom, oldCount, position, true);
3624
- const block = to.layout.blockOffset[node] + board;
3625
- const base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
3626
- if (round >= to.layout.compactFrom) {
3627
- writeCompactBlock(to, node, newSlot, block, base, actions, count, hasRegret ? newRegret : null, averages ? newSum : null);
3628
- } else {
3629
- if (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS2, block, base, length, newRegret);
3630
- if (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS2, block, base, length, newSum);
3631
- }
3632
3735
  }
3633
3736
  }
3634
3737
  return { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };
3635
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
+ }
3636
3754
  function checkRelabelling(cards, a, b) {
3637
3755
  const seen = new Uint8Array(DECK);
3638
3756
  if (cards.length !== DECK) throw new Error(`A card relabelling maps all ${DECK} cards; got ${cards.length}`);
@@ -4156,6 +4274,13 @@ function factory() {
4156
4274
  return v;
4157
4275
  }
4158
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
+ }
4159
4284
  const fm = new Set(flop);
4160
4285
  const blank = (s) => blankMask >> s & 1;
4161
4286
  const fc = [0, 0, 0, 0];
@@ -4196,7 +4321,19 @@ function factory() {
4196
4321
  }
4197
4322
  turns.push({ card: t, w: wt, rivs });
4198
4323
  }
4199
- return { rivers, turns, blankMask };
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;
4200
4337
  }
4201
4338
  const DCAP = 91 + 64;
4202
4339
  function side(h, other, R, T, want) {
@@ -4240,19 +4377,11 @@ function factory() {
4240
4377
  const S = [side(hA, hB, R, T, wantA), side(hB, hA, R, T, wantB)];
4241
4378
  const mir = [];
4242
4379
  if (perms && perms.length > 1) {
4243
- const ridx = new Map(states.rivers.map((r, k) => [r[0] * 52 + r[1], k]));
4380
+ const ridx = new Map(states.rivers.map((r, k) => [dealtKey(states, k), k]));
4244
4381
  for (const p of perms) {
4245
4382
  if (p[0] === 0 && p[1] === 1 && p[2] === 2 && p[3] === 3) continue;
4246
4383
  const bmap = mk(Int32Array, R);
4247
- for (let k = 0; k < R; k++) {
4248
- let a = states.rivers[k][0] & ~3 | p[states.rivers[k][0] & 3], b = states.rivers[k][1] & ~3 | p[states.rivers[k][1] & 3];
4249
- if (a > b) {
4250
- const t = a;
4251
- a = b;
4252
- b = t;
4253
- }
4254
- bmap[k] = ridx.get(a * 52 + b);
4255
- }
4384
+ for (let k = 0; k < R; k++) bmap[k] = ridx.get(dealtKey(states, k, p));
4256
4385
  const hmap = S.map((s) => {
4257
4386
  const idx = new Map(s.hands.map((h, i) => [hid(h), i]));
4258
4387
  const out = mk(Int32Array, s.n);
@@ -4288,7 +4417,7 @@ function factory() {
4288
4417
  });
4289
4418
  const fl = [0, 0, 0, 0];
4290
4419
  let f1 = 0, f2 = 0, f3 = 0, f4 = 0;
4291
- for (const c of flop) {
4420
+ for (const c of states.base || flop) {
4292
4421
  const bit = 1 << (c >> 2);
4293
4422
  fl[c & 3] |= bit;
4294
4423
  if (f3 & bit) f4 |= bit;
@@ -4631,8 +4760,8 @@ function factory() {
4631
4760
  const perms = states.blankMask ? [[0, 1, 2, 3]] : flopPerms(flop);
4632
4761
  const sym = perms.length > 1 && isSymmetric(hA, perms) && isSymmetric(hB, perms);
4633
4762
  const eq = equitiesBoth(hA, hB, flop, states, wantA, wantB, sym ? perms : null, only);
4634
- const one = (h, e) => e && { hero: h, flop, states, n: h.length, R: states.rivers.length, E: e.E, ef: e.ef, et: e.et, boardSym: sym, perms, sums: e };
4635
- return [one(hA, eq[0]), one(hB, eq[1])];
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)];
4636
4765
  }
4637
4766
  let lastPair = null;
4638
4767
  function prepare(hero, villain, flop, states) {
@@ -4686,7 +4815,7 @@ function factory() {
4686
4815
  states.turns.forEach((t, ti) => list.push(["et", ti * n, sw[1] * t.w / tw]));
4687
4816
  const rws = [], rks = [];
4688
4817
  const mirrored = symmetric && P.boardSym && ob.perms.length > 1;
4689
- const done = new Uint8Array(R), ridx = mirrored ? new Map(states.rivers.map((r, k) => [r[0] * 52 + r[1], k])) : null, repQ = new Int32Array(R);
4818
+ const done = new Uint8Array(R), ridx = mirrored ? new Map(states.rivers.map((r, k) => [dealtKey(states, k), k])) : null, repQ = new Int32Array(R);
4690
4819
  for (let k = 0; k < R; k++) {
4691
4820
  if (done[k]) continue;
4692
4821
  let wsum = states.rivers[k][2];
@@ -4694,13 +4823,7 @@ function factory() {
4694
4823
  if (mirrored) {
4695
4824
  wsum = 0;
4696
4825
  for (const p of ob.perms) {
4697
- let a = states.rivers[k][0] & ~3 | p[states.rivers[k][0] & 3], b = states.rivers[k][1] & ~3 | p[states.rivers[k][1] & 3];
4698
- if (a > b) {
4699
- const t = a;
4700
- a = b;
4701
- b = t;
4702
- }
4703
- const j = ridx.get(a * 52 + b);
4826
+ const j = ridx.get(dealtKey(states, k, p));
4704
4827
  if (!done[j]) {
4705
4828
  done[j] = 1;
4706
4829
  repQ[j] = rks.length;
@@ -4807,10 +4930,81 @@ function factory() {
4807
4930
  const W = walker(P, opts);
4808
4931
  if (P.gramKey === W.key) return P.gramRes;
4809
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);
4810
4935
  P.gramKey = W.key;
4811
- P.gramRes = { Go: symmetrize(a.U, a.diag, W.m), ob: W.ob, m: W.m };
4936
+ P.gramRes = { Go, ob: W.ob, m: W.m };
4812
4937
  return P.gramRes;
4813
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
+ }
4814
5008
  function invertSPD(A, m) {
4815
5009
  const L = new Float64Array(m * m);
4816
5010
  for (let i = 0; i < m; i++) {
@@ -5198,7 +5392,13 @@ function factory() {
5198
5392
  }
5199
5393
  return { a, b, w: h.weight };
5200
5394
  });
5201
- const asFlop = (f) => typeof f === "string" ? f.match(/../g).map(cardFromStr) : f;
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);
5202
5402
  const asMask = (b) => !b ? 0 : typeof b === "number" ? b : b.reduce((m, s) => m | 1 << (typeof s === "string" ? SUITS2.indexOf(s) : s), 0);
5203
5403
  const liveHands = (hands, flop) => hands.filter((h) => h.w > 0 && !flop.includes(h.a) && !flop.includes(h.b));
5204
5404
  function blankSuitsFor(flop) {
@@ -5208,9 +5408,10 @@ function factory() {
5208
5408
  return [0, 1, 2, 3].filter((s) => fc[s] < 2).map((s) => SUITS2[s]);
5209
5409
  }
5210
5410
  const expectedFrequencyError = (mismatch) => 0.6 + 60 * mismatch;
5211
- const arenaBytes = (nA, nB, st) => {
5411
+ const binsFor = (o, st) => o.bins || (st.fixed.length === 2 ? 64 : 16);
5412
+ const arenaBytes = (nA, nB, st, bins) => {
5212
5413
  const n = Math.max(nA, nB);
5213
- return (4 * (st.rivers.length + st.turns.length + 2) + 16 * st.turns.length + 96) * (nA + nB) + 56 * n * n + 16 * 16 * n + 12 * st.rivers.length * 8 + (4 << 20);
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);
5214
5415
  };
5215
5416
  const elimOpts = (o, n, sym) => {
5216
5417
  const opts = { symmetric: o.symmetric !== false && sym, bins: o.bins, streetWeights: o.streetWeights, exact: o.exact, riverSample: o.riverSample || "auto" };
@@ -5220,7 +5421,9 @@ function factory() {
5220
5421
  return opts;
5221
5422
  };
5222
5423
  function solveOne(P, o) {
5223
- const el = eliminate(P, elimOpts(o, P.n, P.boardSym || P.perms.length === 1));
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);
5224
5427
  const m = materialize(P, el.path[0], el.ob, { top: o.standIns || 0 });
5225
5428
  return { hands: m.hands, prefs: m.prefs, err: m.err, scale: m.scale, n: P.n, curve: o.curve ? el.curve : void 0 };
5226
5429
  }
@@ -5250,16 +5453,16 @@ function factory() {
5250
5453
  };
5251
5454
  }
5252
5455
  function compress(o) {
5253
- const flop = asFlop(o.flop);
5456
+ const flop = boardOf(o);
5254
5457
  const hero = liveHands(asHands(o.range), flop), villain = liveHands(asHands(o.opponent), flop);
5255
5458
  const states = deckStates(flop, asMask(o.blankSuits));
5256
- return present(withArena(arenaBytes(hero.length, 0, states), () => solveOne(prepareBoth(hero, villain, flop, states, true, false)[0], o)), states);
5459
+ return present(withArena(arenaBytes(hero.length, 0, states, binsFor(o, states)), () => solveOne(prepareBoth(hero, villain, flop, states, true, false)[0], o)), states);
5257
5460
  }
5258
5461
  function compressBoth(o) {
5259
- const flop = asFlop(o.flop);
5462
+ const flop = boardOf(o);
5260
5463
  const a = liveHands(asHands(o.oop), flop), b = liveHands(asHands(o.ip), flop);
5261
5464
  const states = deckStates(flop, asMask(o.blankSuits));
5262
- const r = withArena(arenaBytes(a.length, b.length, states), () => {
5465
+ const r = withArena(arenaBytes(a.length, b.length, states, binsFor(o, states)), () => {
5263
5466
  const P = prepareBoth(a, b, flop, states);
5264
5467
  const mark = arena ? WK.top : 0;
5265
5468
  const x = solveOne(P[0], Object.assign({}, o, { size: o.sizeOop || o.size }));
@@ -5294,8 +5497,8 @@ var range_compress_default = factory();
5294
5497
  // src/compress.ts
5295
5498
  function compressRanges(config, options = {}) {
5296
5499
  const board = parseCards(config.board);
5297
- if (board.length !== 3) throw new Error(`Ranges are compressed for a flop; the board ${config.board} has ${board.length} cards`);
5298
- const tolerance = options.tolerance ?? 0.01;
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);
5299
5502
  if (!(tolerance > 0 && tolerance < 1)) throw new Error(`tolerance must be above 0 and under 1; got ${tolerance}`);
5300
5503
  const sizes = options.size === void 0 ? void 0 : typeof options.size === "number" ? [options.size, options.size] : options.size;
5301
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)}`);
@@ -5323,7 +5526,7 @@ function compressRanges(config, options = {}) {
5323
5526
  result = range_compress_default.compressBoth({
5324
5527
  oop,
5325
5528
  ip,
5326
- flop: board.map(formatCard).join(""),
5529
+ board: board.map(formatCard).join(""),
5327
5530
  ...sizes ? { sizeOop: Math.min(sizes[0], oop.length), sizeIp: Math.min(sizes[1], ip.length) } : { tolerance }
5328
5531
  });
5329
5532
  } finally {
@@ -5499,10 +5702,11 @@ function nearest(row, target) {
5499
5702
  }
5500
5703
  function solveLite(config, options = {}) {
5501
5704
  const preset = litePreset(config, options);
5502
- 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) {
5503
5708
  const share = blueprint.shareHistories;
5504
5709
  const kept = typeof share === "object" ? [...share.keepLines ?? []] : [];
5505
- const solution = solve(defineSpot(blueprint), preset.options);
5506
5710
  const subgameSolve = pick(options, ["workers", "precision", "wasmStorage"]);
5507
5711
  const { tree } = solution.spot;
5508
5712
  const scale = solution.spot.chipScale;
@@ -5511,7 +5715,7 @@ function solveLite(config, options = {}) {
5511
5715
  blueprint,
5512
5716
  kept,
5513
5717
  source: config,
5514
- changes: preset.changes,
5718
+ changes,
5515
5719
  resolve(node, board, resolveOptions) {
5516
5720
  const round = tree.round[node];
5517
5721
  const prefix = `${solution.path(node)} `;
@@ -5527,6 +5731,87 @@ function solveLite(config, options = {}) {
5527
5731
  }
5528
5732
  };
5529
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
+ }
5530
5815
  var KEEP_TOLERANCE = 5e-3;
5531
5816
  function litePreset(config, options = {}) {
5532
5817
  const blueprint = keepWithin(liteConfig(config, options), options);
@@ -5572,7 +5857,7 @@ function litePreset(config, options = {}) {
5572
5857
  }
5573
5858
  if (options.compressRanges) {
5574
5859
  const count = (range) => activeCombos(typeof range === "string" ? parseRange(range) : range).length;
5575
- 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 flop's boards; approximate: the blueprint has no strategy for a combination left out, and what one combination does is not preserved`);
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`);
5576
5861
  }
5577
5862
  if (sampling) change("approximations.chanceSampling", void 0, sampling, samplingNote(sampling));
5578
5863
  if (settle) {
@@ -5716,13 +6001,39 @@ function defineSpot(config) {
5716
6001
  }
5717
6002
  return weights;
5718
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")];
5719
6017
  const players = [
5720
- buildPlayerIndex(trim(config.oop, "out-of-position")),
5721
- 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)
5722
6020
  ];
5723
- 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)]);
5724
6030
  const merge = config.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config.runoutBuckets) : void 0;
5725
- 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));
5726
6037
  const tree = buildTree(treeConfig(config, rows), runouts);
5727
6038
  const historyAlias = config.shareHistories ? shareHistories(tree, runouts, config, chipScale) : void 0;
5728
6039
  const layout = buildLayout(tree, runouts, players, 4, historyAlias);
@@ -5757,7 +6068,7 @@ function defineSpot(config) {
5757
6068
  suggestions
5758
6069
  };
5759
6070
  if (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);
5760
- return {
6071
+ const spot = {
5761
6072
  board,
5762
6073
  tree,
5763
6074
  runouts,
@@ -5772,7 +6083,52 @@ function defineSpot(config) {
5772
6083
  return resolveBoard(runouts, typeof cards === "string" ? parseCards(cards) : cards);
5773
6084
  }
5774
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;
5775
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();
5776
6132
  function shareHistories(tree, runouts, config, chipScale) {
5777
6133
  const asked = config.shareHistories === true ? {} : config.shareHistories || {};
5778
6134
  const keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : void 0;
@@ -5819,6 +6175,8 @@ var TREE_SETTINGS = [
5819
6175
  "mergeSizes",
5820
6176
  "thinSizes"
5821
6177
  ];
6178
+ var RangeNotInPlaceError = class extends Error {
6179
+ };
5822
6180
  function createRun(spot, options = {}) {
5823
6181
  if (options.analysisOnly && options.approximations?.currentProfileEv) {
5824
6182
  throw new Error("approximations.currentProfileEv needs regrets, and an analysisOnly run has none");
@@ -5839,7 +6197,12 @@ function createRun(spot, options = {}) {
5839
6197
  const relevant = new Uint8Array(COMBOS);
5840
6198
  for (const combo of spot.players[0].combos) relevant[combo] = 1;
5841
6199
  for (const combo of spot.players[1].combos) relevant[combo] = 1;
5842
- const showdown = buildShowdownTable(spot.runouts, relevant);
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);
5843
6206
  const layoutAt = (at) => buildLayout(
5844
6207
  spot.tree,
5845
6208
  spot.runouts,
@@ -5850,8 +6213,6 @@ function createRun(spot, options = {}) {
5850
6213
  );
5851
6214
  let layout = layoutAt(precision);
5852
6215
  const weights = runoutWeights(spot.runouts);
5853
- const active = buildActiveLists(spot.runouts, spot.players, showdown);
5854
- const hands = buildHandSpace(spot.runouts, spot.players, active);
5855
6216
  const samplingOptions = options.approximations?.chanceSampling;
5856
6217
  const samplingPlan = samplingOptions ? planSampling(spot.tree, spot.runouts, active, layout, samplingOptions) : void 0;
5857
6218
  const storageAt = (at, of) => compact ? of.bytes : Math.max(at === "i16" ? spot.estimate.compressedBytes : bytes, of.bytes);
@@ -5967,7 +6328,7 @@ function createRun(spot, options = {}) {
5967
6328
  solver = makeSolver(ctx);
5968
6329
  if (engine?.profile) threadProfiles.set(solver, engine.profile);
5969
6330
  if (warm && coarsePlan) coarseMs.set(solver, coarsePlan.elapsed);
5970
- 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;
5971
6332
  } catch (error) {
5972
6333
  engine?.close();
5973
6334
  throw error;
@@ -5976,6 +6337,7 @@ function createRun(spot, options = {}) {
5976
6337
  if (engine) solver.useRoot(engine.root(ctx.dcfr));
5977
6338
  const threadCount = pool ? pool.workers : engine ? engine.threads : 1;
5978
6339
  let completed = 0;
6340
+ const nextRange = new Float64Array(COMBOS);
5979
6341
  return {
5980
6342
  spot,
5981
6343
  solver,
@@ -5993,6 +6355,69 @@ function createRun(spot, options = {}) {
5993
6355
  solver.iterate(count, offset + completed);
5994
6356
  completed += count;
5995
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
+ },
5996
6421
  close() {
5997
6422
  solver.useRoot(null);
5998
6423
  pool?.close();
@@ -6185,19 +6610,25 @@ function makeSumStore(precision, buffer) {
6185
6610
  return precision === "f32" ? new Float32Array(buffer) : new Uint16Array(buffer);
6186
6611
  }
6187
6612
  function solve(spot, options = {}) {
6188
- const iterations = options.iterations ?? 500;
6189
- const target = options.targetPercent ?? 0;
6190
- const fixed = options.exploitEvery ?? 0;
6191
- const settle = options.settle ? settlePlan(options.settle) : null;
6613
+ if (options.settle) settlePlan(options.settle);
6192
6614
  const run = createRun(spot, options);
6193
- const history = [];
6194
- const started = Date.now() - (coarseMs.get(run.solver) ?? 0);
6195
- const before = coarseMs.has(run.solver) ? run.totalIterations : 0;
6196
6615
  try {
6197
- return runAll();
6616
+ return runToStop(run, options);
6198
6617
  } finally {
6199
6618
  run.close();
6200
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();
6201
6632
  function runAll() {
6202
6633
  if (settle) return runSettled(settle);
6203
6634
  if (fixed <= 0 && target <= 0) {
@@ -6246,6 +6677,7 @@ function solve(spot, options = {}) {
6246
6677
  }
6247
6678
  function runSettled(plan) {
6248
6679
  const tracker = trackSettle(plan);
6680
+ if (run.completed > 0) tracker.check(run.snapshot(), 0);
6249
6681
  let stoppedAt = "iterations";
6250
6682
  let done = 0;
6251
6683
  while (done < iterations) {
@@ -6440,7 +6872,9 @@ export {
6440
6872
  NodeKind,
6441
6873
  PLATFORM,
6442
6874
  PRECISION_BYTES,
6875
+ RANGE_RESUME,
6443
6876
  RANKS,
6877
+ RangeNotInPlaceError,
6444
6878
  SUITS,
6445
6879
  SpotTooLargeError,
6446
6880
  activeCombos,
@@ -6464,6 +6898,7 @@ export {
6464
6898
  litePreset,
6465
6899
  makeRegretStore,
6466
6900
  makeSumStore,
6901
+ openLite,
6467
6902
  parseCard,
6468
6903
  parseCards,
6469
6904
  parseRange,
@@ -6471,10 +6906,12 @@ export {
6471
6906
  rangeWeight,
6472
6907
  rankOf,
6473
6908
  rankSwap,
6909
+ releaseSetupCache,
6474
6910
  resolveSubgame,
6475
6911
  rootPlay,
6476
6912
  rootPlayMovement,
6477
6913
  rootPlayNodes,
6914
+ runToStop,
6478
6915
  simdAvailable,
6479
6916
  solve,
6480
6917
  solveLite,