poker-flopsolve 0.4.0 → 0.5.0-beta.0

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
@@ -135,6 +135,10 @@ function mergeBetSizes(sizes, distance) {
135
135
  flush();
136
136
  return [...merged, ...others];
137
137
  }
138
+ function actionLabel(action, target, chipScale) {
139
+ return action >= ActionKind.Bet ? `${ACTION_LABELS[action]} ${target / chipScale}` : ACTION_LABELS[action];
140
+ }
141
+ var THIN_BASE = 0.75;
138
142
  function buildTree(config, runouts) {
139
143
  const kind = [];
140
144
  const player = [];
@@ -169,6 +173,27 @@ function buildTree(config, runouts) {
169
173
  });
170
174
  const noDonk = perRound(config.noDonk ?? false, Array.isArray(config.noDonk), rounds, "noDonk");
171
175
  const half = Math.round(potUnits / 2);
176
+ const remove = config.removeActions && config.removeActions.length > 0 ? new Set(config.removeActions) : null;
177
+ const removed = /* @__PURE__ */ new Set();
178
+ const extend = (path, step) => remove ? path ? `${path} ${step}` : step : "";
179
+ const thin = config.thinSizes === true;
180
+ const thinned = (sized, state) => {
181
+ if (state.round === 0 && state.aggressions === 0 && state.acted === 0) return sized;
182
+ const me = state.toAct;
183
+ const mine = state.invested[me];
184
+ const owed = Math.max(0, state.invested[1 - me] - mine);
185
+ const potAfterCall = potUnits + state.invested[0] + state.invested[1] + owed;
186
+ const fraction2 = (target) => (target - mine - owed) / potAfterCall;
187
+ let nearest2 = -1;
188
+ sized.forEach((entry, i) => {
189
+ const distance = Math.abs(fraction2(entry.target) - THIN_BASE);
190
+ if (nearest2 < 0 || distance < Math.abs(fraction2(sized[nearest2].target) - THIN_BASE)) nearest2 = i;
191
+ });
192
+ const big = rounds > 1 && state.round === rounds - 1 && owed === 0 && state.streetsBet > 0;
193
+ return sized.filter(
194
+ (entry, i) => i === nearest2 || big && (entry.action === ActionKind.AllIn || fraction2(entry.target) > 1)
195
+ );
196
+ };
172
197
  const addNode = (nodeKind, nodePlayer, nodeRound, nodePot, nodePayoff) => {
173
198
  kind.push(nodeKind);
174
199
  player.push(nodePlayer);
@@ -179,7 +204,7 @@ function buildTree(config, runouts) {
179
204
  payoff.push(nodePayoff);
180
205
  return kind.length - 1;
181
206
  };
182
- const closeRound = (state) => {
207
+ const closeRound = (state, path) => {
183
208
  const total = potUnits + state.invested[0] + state.invested[1];
184
209
  const allIn = state.invested[0] >= stackUnits || state.invested[1] >= stackUnits;
185
210
  if (state.round + 1 >= runouts.rounds) {
@@ -195,9 +220,10 @@ function buildTree(config, runouts) {
195
220
  acted: 0,
196
221
  base: state.invested[0],
197
222
  aggressor: -1,
198
- previousAggressor: state.aggressor
223
+ previousAggressor: state.aggressor,
224
+ streetsBet: state.streetsBet + (state.aggressions > 0 ? 1 : 0)
199
225
  };
200
- const child = allIn ? closeRound(next) : buildDecision(next);
226
+ const child = allIn ? closeRound(next, extend(path, "/")) : buildDecision(next, extend(path, "/"));
201
227
  firstEdge[node] = edgeChild.length;
202
228
  numEdges[node] = 1;
203
229
  edgeAction.push(ActionKind.Check);
@@ -221,14 +247,10 @@ function buildTree(config, runouts) {
221
247
  if (target <= theirs) return null;
222
248
  const raiseSize = target - theirs;
223
249
  const minimum = Math.max(state.lastRaise, minRaiseUnits);
224
- if (raiseSize < minimum) {
225
- const bumped = theirs + minimum;
226
- if (bumped > cap) return null;
227
- target = bumped;
228
- }
250
+ if (raiseSize < minimum) target = Math.min(theirs + minimum, cap);
229
251
  return target;
230
252
  };
231
- const buildDecision = (state) => {
253
+ const buildDecision = (state, path) => {
232
254
  const me = state.toAct;
233
255
  const opp = 1 - me;
234
256
  const mine = state.invested[me];
@@ -247,6 +269,7 @@ function buildTree(config, runouts) {
247
269
  const donk = noDonk[state.round] && me === 0 && owed === 0 && state.aggressions === 0 && state.previousAggressor === 1;
248
270
  if (state.aggressions < maxRaises[me][state.round] && myRemaining > owed && !donk) {
249
271
  const seen = /* @__PURE__ */ new Set();
272
+ const sized = [];
250
273
  const myRaises = raiseSizes[me];
251
274
  const sizes = owed > 0 && myRaises ? [...myRaises[state.round]] : [...betSizes[me][state.round] ?? []].filter((size) => !(typeof size === "object" && "times" in size));
252
275
  if (allowAllIn[me][state.round]) sizes.push("allin");
@@ -258,10 +281,17 @@ function buildTree(config, runouts) {
258
281
  if (target === null || seen.has(target)) continue;
259
282
  seen.add(target);
260
283
  const isShove = target >= stackUnits;
261
- actions.push({
262
- action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet,
263
- target
264
- });
284
+ sized.push({ action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet, target });
285
+ }
286
+ for (const entry of thin ? thinned(sized, state) : sized) {
287
+ if (remove) {
288
+ const line = extend(path, actionLabel(entry.action, entry.target, chipScale));
289
+ if (remove.has(line)) {
290
+ removed.add(line);
291
+ continue;
292
+ }
293
+ }
294
+ actions.push(entry);
265
295
  }
266
296
  }
267
297
  const base = edgeChild.length;
@@ -273,6 +303,7 @@ function buildTree(config, runouts) {
273
303
  edgeChild.push(-1);
274
304
  }
275
305
  actions.forEach((entry, i) => {
306
+ const line = remove ? extend(path, actionLabel(entry.action, entry.target, chipScale)) : "";
276
307
  const invested = me === 0 ? [entry.target, theirs] : [theirs, entry.target];
277
308
  let child;
278
309
  if (entry.action === ActionKind.Fold) {
@@ -280,7 +311,7 @@ function buildTree(config, runouts) {
280
311
  child = addNode(NodeKind.TerminalFold, -1, state.round, total, value);
281
312
  } else if (entry.action === ActionKind.Check || entry.action === ActionKind.Call) {
282
313
  const closed = invested[0] === invested[1] && state.acted + 1 >= 2;
283
- child = closed ? closeRound({ ...state, invested, acted: state.acted + 1 }) : buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 });
314
+ child = closed ? closeRound({ ...state, invested, acted: state.acted + 1 }, line) : buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 }, line);
284
315
  } else {
285
316
  child = buildDecision({
286
317
  round: state.round,
@@ -291,8 +322,9 @@ function buildTree(config, runouts) {
291
322
  acted: state.acted + 1,
292
323
  base: state.base,
293
324
  aggressor: me,
294
- previousAggressor: state.previousAggressor
295
- });
325
+ previousAggressor: state.previousAggressor,
326
+ streetsBet: state.streetsBet
327
+ }, line);
296
328
  }
297
329
  edgeChild[base + i] = child;
298
330
  });
@@ -307,8 +339,16 @@ function buildTree(config, runouts) {
307
339
  acted: 0,
308
340
  base: 0,
309
341
  aggressor: -1,
310
- previousAggressor: -1
311
- });
342
+ previousAggressor: -1,
343
+ streetsBet: 0
344
+ }, "");
345
+ if (remove && removed.size < remove.size) {
346
+ const under = (line) => [...removed].some((cut) => line.startsWith(`${cut} `));
347
+ const missing = [...remove].filter((line) => !removed.has(line) && !under(line));
348
+ if (missing.length > 0) throw new Error(
349
+ `removeActions: no bet, raise or shove in this tree ends the line ${missing.map((m) => `"${m}"`).join(", ")}. Give each as Solution.path writes the node the action leads to, e.g. "check bet 18.15"; checks, calls and folds cannot be removed`
350
+ );
351
+ }
312
352
  const decisionNodes = [];
313
353
  for (let i = 0; i < kind.length; i++) if (kind[i] === NodeKind.Decision) decisionNodes.push(i);
314
354
  return {
@@ -447,8 +487,6 @@ function enumerateRunouts(board, symmetries, merge) {
447
487
  stabiliserMap.push(Int32Array.from(flat));
448
488
  };
449
489
  recordStabilisers(stabilisers);
450
- const used = new Uint8Array(DECK);
451
- const seen = new Uint8Array(DECK);
452
490
  for (let round = 1; round < rounds; round++) {
453
491
  const previousWidth = width[round - 1];
454
492
  const previousCount = counts[round - 1];
@@ -463,49 +501,9 @@ function enumerateRunouts(board, symmetries, merge) {
463
501
  const nextStabilisers = [];
464
502
  for (let p = 0; p < previousCount; p++) {
465
503
  starts[p] = parents.length;
466
- used.fill(0);
467
- seen.fill(0);
468
504
  const base = p * previousWidth;
469
- for (let i = 0; i < previousWidth; i++) used[previousCards[base + i]] = 1;
470
- const stabiliser = stabilisers[p];
471
- const children = [];
472
- for (let card = 0; card < DECK; card++) {
473
- if (used[card] || seen[card]) continue;
474
- const child = { card, maps: [], cards: [], fixing: [], merged: false };
475
- for (const sigma of stabiliser) {
476
- const image = maps.card[sigma][card];
477
- if (image === card) child.fixing.push(sigma);
478
- if (seen[image]) continue;
479
- seen[image] = 1;
480
- child.maps.push(image === card ? 0 : maps.inverse(sigma));
481
- child.cards.push(image);
482
- }
483
- children.push(child);
484
- }
485
- if (merge) {
486
- const boardRanks = /* @__PURE__ */ new Set();
487
- for (let i = 0; i < previousWidth; i++) boardRanks.add(previousCards[base + i] >> 2);
488
- for (let j = 0; j < children.length; j++) {
489
- const later = children[j];
490
- const rankJ = later.card >> 2;
491
- if (boardRanks.has(rankJ)) continue;
492
- for (let i = 0; i < j; i++) {
493
- const earlier = children[i];
494
- if (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;
495
- const rankI = earlier.card >> 2;
496
- if (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;
497
- if (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;
498
- const swap = maps.add(rankSwap(rankI, rankJ));
499
- for (let m = 0; m < later.maps.length; m++) {
500
- earlier.maps.push(maps.then(later.maps[m], swap));
501
- earlier.cards.push(later.cards[m]);
502
- }
503
- later.merged = true;
504
- approximate = true;
505
- break;
506
- }
507
- }
508
- }
505
+ const children = dealChildren(maps, previousCards, base, previousWidth, stabilisers[p], merge);
506
+ for (const child of children) if (child.merged) approximate = true;
509
507
  for (const child of children) {
510
508
  if (child.merged) continue;
511
509
  for (let i = 0; i < previousWidth; i++) level.push(previousCards[base + i]);
@@ -548,6 +546,53 @@ function enumerateRunouts(board, symmetries, merge) {
548
546
  initial: [...board]
549
547
  };
550
548
  }
549
+ var usedScratch = new Uint8Array(DECK);
550
+ var seenScratch = new Uint8Array(DECK);
551
+ function dealChildren(maps, cards, base, width, stabiliser, merge) {
552
+ const used = usedScratch;
553
+ const seen = seenScratch;
554
+ used.fill(0);
555
+ seen.fill(0);
556
+ for (let i = 0; i < width; i++) used[cards[base + i]] = 1;
557
+ const children = [];
558
+ for (let card = 0; card < DECK; card++) {
559
+ if (used[card] || seen[card]) continue;
560
+ const child = { card, maps: [], cards: [], fixing: [], merged: false };
561
+ for (const sigma of stabiliser) {
562
+ const image = maps.card[sigma][card];
563
+ if (image === card) child.fixing.push(sigma);
564
+ if (seen[image]) continue;
565
+ seen[image] = 1;
566
+ child.maps.push(image === card ? 0 : maps.inverse(sigma));
567
+ child.cards.push(image);
568
+ }
569
+ children.push(child);
570
+ }
571
+ if (merge) {
572
+ const boardRanks = /* @__PURE__ */ new Set();
573
+ for (let i = 0; i < width; i++) boardRanks.add(cards[base + i] >> 2);
574
+ for (let j = 0; j < children.length; j++) {
575
+ const later = children[j];
576
+ const rankJ = later.card >> 2;
577
+ if (boardRanks.has(rankJ)) continue;
578
+ for (let i = 0; i < j; i++) {
579
+ const earlier = children[i];
580
+ if (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;
581
+ const rankI = earlier.card >> 2;
582
+ if (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;
583
+ if (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;
584
+ const swap = maps.add(rankSwap(rankI, rankJ));
585
+ for (let m = 0; m < later.maps.length; m++) {
586
+ earlier.maps.push(maps.then(later.maps[m], swap));
587
+ earlier.cards.push(later.cards[m]);
588
+ }
589
+ later.merged = true;
590
+ break;
591
+ }
592
+ }
593
+ }
594
+ return children;
595
+ }
551
596
  function rankSwap(a, b) {
552
597
  const out = new Uint8Array(DECK);
553
598
  for (let card = 0; card < DECK; card++) {
@@ -590,11 +635,13 @@ function resolveBoard(runouts, board) {
590
635
  const round = i - start + 1;
591
636
  const dealt = runouts.maps.card[map][board[i]];
592
637
  let found = -1;
593
- for (let child = runouts.childStart[round][index]; child < runouts.childStart[round][index + 1] && found < 0; child++) {
638
+ const children = runouts.childStart[round];
639
+ const relabel = runouts.orbitMap[round];
640
+ for (let child = children[index]; child < children[index + 1] && found < 0; child++) {
594
641
  for (let m = runouts.orbitStart[round][child]; m < runouts.orbitStart[round][child + 1]; m++) {
595
642
  if (runouts.orbitCard[round][m] !== dealt) continue;
596
643
  found = child;
597
- map = runouts.maps.then(map, runouts.orbitMap[round][m]);
644
+ map = runouts.maps.then(map, relabel[m]);
598
645
  break;
599
646
  }
600
647
  }
@@ -977,6 +1024,13 @@ function buildShowdownTable(runouts, relevant) {
977
1024
  }
978
1025
 
979
1026
  // src/hands.ts
1027
+ function markMembers(lists, from, count, indexOf, clear) {
1028
+ for (let i = 0; i < count; i++) {
1029
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
1030
+ indexOf[lists.memberCombo[m]] = clear ? -1 : i;
1031
+ }
1032
+ }
1033
+ }
980
1034
  function span(lists, round, board, player) {
981
1035
  const slot = (lists.roundBase[round] + board) * 2 + player;
982
1036
  return [lists.start[slot], lists.count[slot]];
@@ -993,7 +1047,7 @@ function buildHandSpace(runouts, players, lists) {
993
1047
  const parent = runouts.parent[round][child];
994
1048
  for (let player = 0; player < 2; player++) {
995
1049
  const [parentFrom, parentCount] = span(lists, round - 1, parent, player);
996
- for (let i = 0; i < parentCount; i++) indexOf[lists.list[parentFrom + i]] = i;
1050
+ markMembers(lists, parentFrom, parentCount, indexOf, false);
997
1051
  const [childFrom, childCount] = span(lists, round, child, player);
998
1052
  for (let m = orbitStart[child]; m < orbitStart[child + 1]; m++) {
999
1053
  const back = runouts.maps.combo[runouts.maps.inverse(runouts.orbitMap[round][m])];
@@ -1005,7 +1059,7 @@ function buildHandSpace(runouts, players, lists) {
1005
1059
  up.push(at);
1006
1060
  }
1007
1061
  }
1008
- for (let i = 0; i < parentCount; i++) indexOf[lists.list[parentFrom + i]] = -1;
1062
+ markMembers(lists, parentFrom, parentCount, indexOf, true);
1009
1063
  }
1010
1064
  }
1011
1065
  upStart.push(starts);
@@ -1018,11 +1072,11 @@ function buildHandSpace(runouts, players, lists) {
1018
1072
  for (let player = 0; player < 2; player++) {
1019
1073
  const slot = (lists.roundBase[round] + board) * 2 + player;
1020
1074
  const [otherFrom, otherCount] = span(lists, round, board, 1 - player);
1021
- for (let j = 0; j < otherCount; j++) indexOf[lists.list[otherFrom + j]] = j;
1075
+ markMembers(lists, otherFrom, otherCount, indexOf, false);
1022
1076
  const [from, count] = span(lists, round, board, player);
1023
1077
  sameStart[slot] = same.length;
1024
1078
  for (let i = 0; i < count; i++) same.push(indexOf[lists.list[from + i]]);
1025
- for (let j = 0; j < otherCount; j++) indexOf[lists.list[otherFrom + j]] = -1;
1079
+ markMembers(lists, otherFrom, otherCount, indexOf, true);
1026
1080
  }
1027
1081
  }
1028
1082
  }
@@ -1074,6 +1128,48 @@ function showdownValuesHands(oppReach, cardA, cardB, strength, oppFrom, oppCount
1074
1128
  }
1075
1129
  sums.fill(0, 0, DECK);
1076
1130
  }
1131
+ function addMembers(reach, entry, memberStart, memberA, memberB, sums) {
1132
+ const to = memberStart[entry + 1];
1133
+ for (let m = memberStart[entry]; m < to; m++) {
1134
+ sums[memberA[m]] += reach;
1135
+ sums[memberB[m]] += reach;
1136
+ }
1137
+ return reach * (to - memberStart[entry]);
1138
+ }
1139
+ function foldValuesPacked(oppReach, cardA, cardB, memberStart, memberA, memberB, oppFrom, oppCount, myFrom, myCount, same, sameFrom, payoff, sums, out) {
1140
+ let total = 0;
1141
+ for (let j = 0; j < oppCount; j++) total += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);
1142
+ for (let i = 0; i < myCount; i++) {
1143
+ const twin = same[sameFrom + i];
1144
+ const both = twin >= 0 ? oppReach[twin] : 0;
1145
+ out[i] = payoff * (total - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]] - both));
1146
+ }
1147
+ sums.fill(0, 0, DECK);
1148
+ }
1149
+ function showdownValuesPacked(oppReach, cardA, cardB, memberStart, memberA, memberB, strength, oppFrom, oppCount, myFrom, myCount, payoff, sums, out) {
1150
+ let running = 0;
1151
+ let j = 0;
1152
+ for (let i = 0; i < myCount; i++) {
1153
+ const level = strength[myFrom + i];
1154
+ while (j < oppCount && strength[oppFrom + j] < level) {
1155
+ running += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);
1156
+ j++;
1157
+ }
1158
+ out[i] = running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]]);
1159
+ }
1160
+ sums.fill(0, 0, DECK);
1161
+ running = 0;
1162
+ j = oppCount - 1;
1163
+ for (let i = myCount - 1; i >= 0; i--) {
1164
+ const level = strength[myFrom + i];
1165
+ while (j >= 0 && strength[oppFrom + j] > level) {
1166
+ running += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);
1167
+ j--;
1168
+ }
1169
+ out[i] = payoff * (out[i] - (running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]])));
1170
+ }
1171
+ sums.fill(0, 0, DECK);
1172
+ }
1077
1173
 
1078
1174
  // src/pairs.ts
1079
1175
  var CHUNK = 64;
@@ -1105,7 +1201,8 @@ function makeBuffers(ctx, width) {
1105
1201
  hands: make(() => new Uint16Array(width)),
1106
1202
  strategy: make(() => new Float64Array(actions * COMBOS)),
1107
1203
  rank: new Int32Array(COMBOS),
1108
- position: new Int32Array(COMBOS)
1204
+ position: new Int32Array(COMBOS).fill(-1),
1205
+ at: make(() => new Int32Array(width))
1109
1206
  };
1110
1207
  }
1111
1208
  function pairValues(ctx, node, board, traverser, hands, handReach, live, liveCount) {
@@ -1202,20 +1299,23 @@ function walk(ctx, buffers, traverser, hands, node, board, colReach, cols, colCo
1202
1299
  const childLive = buffers.live[depth];
1203
1300
  const childCols2 = buffers.cols[depth + 1];
1204
1301
  const mappedHands = buffers.hands[depth];
1205
- for (let childBoard = runouts.childStart[nextRound][board]; childBoard < runouts.childStart[nextRound][board + 1]; childBoard++) {
1302
+ const starts = runouts.childStart[nextRound];
1303
+ for (let childBoard = starts[board]; childBoard < starts[board + 1]; childBoard++) {
1304
+ const stored = dealtCards[childBoard * width + width - 1];
1206
1305
  for (let m = orbitStart[childBoard]; m < orbitStart[childBoard + 1]; m++) {
1207
- const dealt = m === orbitStart[childBoard] ? dealtCards[childBoard * width + width - 1] : runouts.orbitCard[nextRound][m];
1306
+ const dealt = m === orbitStart[childBoard] ? stored : runouts.orbitCard[nextRound][m];
1208
1307
  const map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];
1308
+ const blocked = (combo) => cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt;
1209
1309
  let childCount = 0;
1210
1310
  for (let i = 0; i < liveCount; i++) {
1211
1311
  const combo = live[i];
1212
- if (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;
1312
+ if (blocked(combo)) continue;
1213
1313
  childLive[childCount++] = map[combo];
1214
1314
  }
1215
1315
  let childColCount = 0;
1216
1316
  for (let c = 0; c < colCount; c++) {
1217
1317
  const k = cols[c];
1218
- if (cards[hands[k] * 2] !== dealt && cards[hands[k] * 2 + 1] !== dealt) childCols2[childColCount++] = k;
1318
+ if (!blocked(hands[k])) childCols2[childColCount++] = k;
1219
1319
  }
1220
1320
  if (childColCount === 0) continue;
1221
1321
  for (let k = 0; k < hands.length; k++) mappedHands[k] = map[hands[k]];
@@ -1237,7 +1337,7 @@ function walk(ctx, buffers, traverser, hands, node, board, colReach, cols, colCo
1237
1337
  const row = childCols2[c] * COMBOS;
1238
1338
  for (let i = 0; i < liveCount; i++) {
1239
1339
  const combo = live[i];
1240
- if (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;
1340
+ if (blocked(combo)) continue;
1241
1341
  out[row + combo] += value[row + map[combo]];
1242
1342
  }
1243
1343
  }
@@ -1250,16 +1350,14 @@ function walk(ctx, buffers, traverser, hands, node, board, colReach, cols, colCo
1250
1350
  const owner = tree.player[node];
1251
1351
  const lists = ctx.active;
1252
1352
  const listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;
1253
- const active = lists.list;
1254
1353
  const activeFrom = lists.start[listSlot];
1255
1354
  const activeCount = lists.count[listSlot];
1256
1355
  const stride = activeCount;
1257
1356
  const slotBase = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];
1258
1357
  const strategy = buffers.strategy[depth];
1259
- averageStrategy(ctx.strategySum, slotBase, actions, stride, strategy, ctx.regret);
1358
+ storedStrategy(ctx, node, slotBase, actions, stride, strategy);
1260
1359
  if (owner === traverser) {
1261
1360
  for (let a = 0; a < actions; a++) {
1262
- const offset = a * COMBOS;
1263
1361
  const value = walk(
1264
1362
  ctx,
1265
1363
  buffers,
@@ -1277,8 +1375,11 @@ function walk(ctx, buffers, traverser, hands, node, board, colReach, cols, colCo
1277
1375
  for (let c = 0; c < colCount; c++) {
1278
1376
  const row = cols[c] * COMBOS;
1279
1377
  for (let i = 0; i < activeCount; i++) {
1280
- const combo = active[activeFrom + i];
1281
- out[row + combo] += strategy[a * stride + i] * value[row + combo];
1378
+ const share = strategy[a * stride + i];
1379
+ for (let m = lists.memberStart[activeFrom + i]; m < lists.memberStart[activeFrom + i + 1]; m++) {
1380
+ const combo = lists.memberCombo[m];
1381
+ out[row + combo] += share * value[row + combo];
1382
+ }
1282
1383
  }
1283
1384
  }
1284
1385
  }
@@ -1287,13 +1388,15 @@ function walk(ctx, buffers, traverser, hands, node, board, colReach, cols, colCo
1287
1388
  const childReach = buffers.colReach[depth + 1];
1288
1389
  const childCols = buffers.cols[depth + 1];
1289
1390
  const position = buffers.position;
1290
- for (let i = 0; i < activeCount; i++) position[active[activeFrom + i]] = i;
1391
+ markMembers(lists, activeFrom, activeCount, position, false);
1392
+ const at = buffers.at[depth];
1393
+ for (let c = 0; c < colCount; c++) at[cols[c]] = position[hands[cols[c]]];
1394
+ markMembers(lists, activeFrom, activeCount, position, true);
1291
1395
  for (let a = 0; a < actions; a++) {
1292
- const offset = a * COMBOS;
1293
1396
  let childCount = 0;
1294
1397
  for (let c = 0; c < colCount; c++) {
1295
1398
  const k = cols[c];
1296
- const r = colReach[k] * strategy[a * stride + position[hands[k]]];
1399
+ const r = at[k] < 0 ? 0 : colReach[k] * strategy[a * stride + at[k]];
1297
1400
  childReach[k] = r;
1298
1401
  if (r !== 0) childCols[childCount++] = k;
1299
1402
  }
@@ -1385,58 +1488,243 @@ function buildPlayerIndex(weights) {
1385
1488
  }
1386
1489
  return { combos: Uint16Array.from(combos), count: combos.length, slot, weights };
1387
1490
  }
1388
- function buildLayout(tree, runouts, players, bytesPerElement) {
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
+ var INT32_MAX = 2 ** 31 - 1;
1500
+ function buildLayout(tree, runouts, players, bytesPerElement, alias, compact) {
1389
1501
  const roundBase = new Int32Array(runouts.rounds + 1);
1390
1502
  for (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];
1391
1503
  const rowStart = new Int32Array(roundBase[runouts.rounds] * 2);
1392
1504
  const totals = new Int32Array(runouts.rounds * 2);
1393
1505
  const onBoard = new Uint8Array(DECK);
1394
1506
  for (let round = 0; round < runouts.rounds; round++) {
1395
- const width = runouts.width[round];
1507
+ const width2 = runouts.width[round];
1396
1508
  const cards = runouts.cards[round];
1397
1509
  for (let board = 0; board < runouts.counts[round]; board++) {
1398
1510
  onBoard.fill(0);
1399
- for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1511
+ for (let i = 0; i < width2; i++) onBoard[cards[board * width2 + i]] = 1;
1400
1512
  for (let player = 0; player < 2; player++) {
1401
1513
  const index = players[player];
1402
1514
  let live = 0;
1403
1515
  for (let i = 0; i < index.count; i++) {
1404
1516
  const combo = index.combos[i];
1405
- if (!onBoard[COMBO_CARDS[combo * 2]] && !onBoard[COMBO_CARDS[combo * 2 + 1]]) live++;
1517
+ if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1518
+ if (!orbitLeader(runouts, round, board, combo)) continue;
1519
+ live++;
1406
1520
  }
1407
1521
  rowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];
1408
1522
  totals[round * 2 + player] += live;
1409
1523
  }
1410
1524
  }
1411
1525
  }
1412
- const offset = new Int32Array(tree.nodeCount).fill(-1);
1526
+ const offset = new Float64Array(tree.nodeCount).fill(-1);
1413
1527
  const blockOffset = new Int32Array(tree.nodeCount).fill(-1);
1528
+ const compactFrom = compact ? compact.from : runouts.rounds;
1529
+ const handOffset = compact ? new Float64Array(tree.nodeCount).fill(-1) : null;
1530
+ const compactChunk = compact ? new Int32Array(tree.nodeCount).fill(-1) : null;
1531
+ const chunkSlots = [];
1532
+ const chunkHands = [];
1533
+ const chunkStart = [];
1534
+ const width = compact?.float ? 4 : 1;
1414
1535
  let total = 0;
1536
+ let compactSlots = 0;
1537
+ let compactHands = 0;
1415
1538
  let blocks = 0;
1416
1539
  let maxActions = 0;
1540
+ let shared = false;
1541
+ let walked = 0;
1417
1542
  for (let i = 0; i < tree.decisionNodes.length; i++) {
1418
1543
  const node = tree.decisionNodes[i];
1419
1544
  const actions = tree.numEdges[node];
1420
1545
  if (actions > maxActions) maxActions = actions;
1421
- offset[node] = total;
1546
+ const hands = totals[tree.round[node] * 2 + tree.player[node]];
1547
+ walked += actions * hands;
1548
+ if (alias !== void 0 && alias[node] !== node) {
1549
+ const owner = alias[node];
1550
+ if (owner > node) throw new Error("buildLayout: a storage owner must come before the nodes it owns");
1551
+ offset[node] = offset[owner];
1552
+ blockOffset[node] = blockOffset[owner];
1553
+ if (compact) {
1554
+ handOffset[node] = handOffset[owner];
1555
+ compactChunk[node] = compactChunk[owner];
1556
+ }
1557
+ shared = true;
1558
+ continue;
1559
+ }
1422
1560
  blockOffset[node] = blocks;
1423
- total += actions * totals[tree.round[node] * 2 + tree.player[node]];
1424
1561
  blocks += runouts.counts[tree.round[node]];
1562
+ if (tree.round[node] >= compactFrom) {
1563
+ const slots = actions * hands;
1564
+ let chunk = chunkSlots.length - 1;
1565
+ if (slots * width > compact.chunkBytes) {
1566
+ throw new Error(
1567
+ `compactStorage.chunkBytes is ${compact.chunkBytes}, but one decision needs ${slots * width} bytes`
1568
+ );
1569
+ }
1570
+ if (chunk < 0 || (chunkSlots[chunk] + slots) * width > compact.chunkBytes || chunkHands[chunk] + hands > compact.chunkBytes) {
1571
+ chunk++;
1572
+ chunkSlots.push(0);
1573
+ chunkHands.push(0);
1574
+ chunkStart.push(compactSlots);
1575
+ }
1576
+ compactChunk[node] = chunk;
1577
+ offset[node] = chunkSlots[chunk];
1578
+ handOffset[node] = chunkHands[chunk];
1579
+ chunkSlots[chunk] += slots;
1580
+ chunkHands[chunk] += hands;
1581
+ compactSlots += slots;
1582
+ compactHands += hands;
1583
+ } else {
1584
+ offset[node] = total;
1585
+ total += actions * hands;
1586
+ }
1425
1587
  }
1426
1588
  const scales = bytesPerElement === 2 ? blocks * 8 * 2 : 0;
1589
+ const compactBytes = !compact ? 0 : compact.float ? compactSlots * 4 : (compactSlots + (compact.perHand ? compactHands : blocks * 8)) * (compact.sums ? 2 : 1);
1427
1590
  return {
1428
- offset,
1591
+ offset: Math.max(total, ...chunkSlots) <= INT32_MAX ? Int32Array.from(offset) : offset,
1429
1592
  blockOffset,
1430
1593
  blocks,
1431
1594
  totalSlots: total,
1595
+ walkedSlots: walked,
1432
1596
  maxActions,
1433
1597
  rowStart,
1434
1598
  roundBase,
1435
- bytes: total * bytesPerElement * 2 + scales
1599
+ bytes: total * bytesPerElement * 2 + scales + compactBytes,
1600
+ shared,
1601
+ reachWeighted: shared ? sharedNodes(tree, alias) : null,
1602
+ compactFrom,
1603
+ compactSlots,
1604
+ handOffset,
1605
+ compactHands,
1606
+ compactChunk,
1607
+ chunkSlots,
1608
+ chunkHands,
1609
+ chunkStart
1436
1610
  };
1437
1611
  }
1612
+ function sharedNodes(tree, alias) {
1613
+ const marks = new Uint8Array(tree.nodeCount);
1614
+ for (let node = 0; node < tree.nodeCount; node++) {
1615
+ if (alias[node] !== node) marks[node] = marks[alias[node]] = 1;
1616
+ }
1617
+ return marks;
1618
+ }
1438
1619
  var REGRET_STEPS = 32767;
1439
1620
  var SUM_STEPS = 65535;
1621
+ function sampledRounds(options, rounds) {
1622
+ const asked = options.rounds ?? Array.from({ length: rounds }, (_, r) => r);
1623
+ return asked.filter((r) => r > 0 && r < rounds);
1624
+ }
1625
+ function planSampling(tree, runouts, active, layout, options) {
1626
+ const rounds = new Uint8Array(runouts.rounds);
1627
+ for (const r of sampledRounds(options, runouts.rounds)) rounds[r] = 1;
1628
+ const boardOffset = new Int32Array(active.roundBase[runouts.rounds] * 2);
1629
+ const perNode = new Float64Array(runouts.rounds);
1630
+ for (let r = 1; r < runouts.rounds; r++) {
1631
+ if (!rounds[r]) continue;
1632
+ let total = 0;
1633
+ for (let b = 0; b < runouts.counts[r]; b++) {
1634
+ for (let p2 = 0; p2 < 2; p2++) {
1635
+ const slot = (active.roundBase[r] + b) * 2 + p2;
1636
+ boardOffset[slot] = total;
1637
+ total += active.count[slot];
1638
+ }
1639
+ }
1640
+ perNode[r] = total;
1641
+ }
1642
+ const baseOffset = new Int32Array(tree.nodeCount).fill(-1);
1643
+ const walkOffset = new Int32Array(tree.nodeCount).fill(-1);
1644
+ let values = 0;
1645
+ let walks = 0;
1646
+ for (let node = 0; node < tree.nodeCount; node++) {
1647
+ if (tree.kind[node] !== NodeKind.Chance) continue;
1648
+ const next = tree.round[node] + 1;
1649
+ if (next >= runouts.rounds || !rounds[next]) continue;
1650
+ baseOffset[node] = values;
1651
+ walkOffset[node] = walks;
1652
+ values += perNode[next];
1653
+ walks += runouts.counts[next] * 2;
1654
+ }
1655
+ if (values > 1073741823) throw new Error("chanceSampling: too many baseline values for this spot");
1656
+ const every = options.every ?? 0;
1657
+ const p = every > 0 ? 1 / every : options.p ?? 0.35;
1658
+ if (!(p > 0 && p <= 1)) throw new Error(`chanceSampling: p must be in (0, 1], got ${p}`);
1659
+ return {
1660
+ rounds,
1661
+ p,
1662
+ every,
1663
+ unbiased: (options.estimator ?? "unbiased") === "unbiased",
1664
+ catchUp: options.catchUp ?? true,
1665
+ baseOffset,
1666
+ boardOffset,
1667
+ walkOffset,
1668
+ values,
1669
+ walks,
1670
+ blocks: layout.blocks
1671
+ };
1672
+ }
1673
+ function samplingBytes(plan) {
1674
+ return (plan.values + plan.walks + plan.blocks) * 4;
1675
+ }
1676
+ function makeSampling(plan, storage, allocate = (bytes) => new ArrayBuffer(bytes)) {
1677
+ return {
1678
+ ...plan,
1679
+ baseline: storage?.baseline ?? new Float32Array(allocate(plan.values * 4)),
1680
+ lastWalk: storage?.lastWalk ?? new Int32Array(allocate(plan.walks * 4)),
1681
+ lastUpdate: storage?.lastUpdate ?? new Int32Array(allocate(plan.blocks * 4)),
1682
+ bytes: samplingBytes(plan)
1683
+ };
1684
+ }
1685
+ function sampled(s, node, board, t) {
1686
+ let h = Math.imul(node ^ Math.imul(board, 2654435761), 2246822507);
1687
+ if (s.every > 0) {
1688
+ h ^= h >>> 13;
1689
+ h = Math.imul(h, 3266489909);
1690
+ h ^= h >>> 16;
1691
+ return ((h >>> 0) + t) % s.every === 0;
1692
+ }
1693
+ h ^= Math.imul(t, 668265263);
1694
+ h ^= h >>> 15;
1695
+ h = Math.imul(h, 3266489909);
1696
+ h ^= h >>> 13;
1697
+ h = Math.imul(h, 374761393);
1698
+ h ^= h >>> 16;
1699
+ return (h >>> 0) / 4294967296 < s.p;
1700
+ }
1701
+ var factorCache = [];
1702
+ function cachedFactors(t) {
1703
+ let f = factorCache[t];
1704
+ if (f === void 0) factorCache[t] = f = dcfrFactors(t);
1705
+ return f;
1706
+ }
1707
+ function blockFactors(ctx, block, iterWeight) {
1708
+ let { keepPositive, keepNegative, keepSum } = cachedFactors(iterWeight);
1709
+ const discounted = ctx.discounted;
1710
+ if (discounted !== void 0 && discounted !== null) {
1711
+ if (discounted[block] === iterWeight) keepPositive = keepNegative = keepSum = 1;
1712
+ discounted[block] = iterWeight;
1713
+ }
1714
+ const sampling = ctx.sampling;
1715
+ if (sampling !== void 0 && sampling !== null) {
1716
+ if (sampling.catchUp) {
1717
+ for (let s = sampling.lastUpdate[block] + 1; s < iterWeight; s++) {
1718
+ const f = cachedFactors(s);
1719
+ keepPositive *= f.keepPositive;
1720
+ keepNegative *= f.keepNegative;
1721
+ keepSum *= f.keepSum;
1722
+ }
1723
+ }
1724
+ sampling.lastUpdate[block] = iterWeight;
1725
+ }
1726
+ return { keepPositive, keepNegative, keepSum };
1727
+ }
1440
1728
  function runoutWeights(runouts) {
1441
1729
  const weights = new Float64Array(runouts.rounds).fill(1);
1442
1730
  for (let round = 0; round < runouts.rounds; round++) {
@@ -1475,15 +1763,22 @@ function buildActiveLists(runouts, players, showdown = null) {
1475
1763
  const slots = roundBase[runouts.rounds] * 2;
1476
1764
  const start = new Int32Array(slots);
1477
1765
  const count = new Uint16Array(slots);
1766
+ const packedSlot = new Uint8Array(slots);
1478
1767
  const entries = [];
1479
1768
  const entrySlots = [];
1769
+ const memberStart = [];
1770
+ const members = [];
1480
1771
  const onBoard = new Uint8Array(DECK);
1772
+ const seen = new Uint8Array(COMBOS);
1481
1773
  for (let round = 0; round < runouts.rounds; round++) {
1482
1774
  const width = runouts.width[round];
1483
1775
  const cards = runouts.cards[round];
1776
+ const stabStart = runouts.stabiliserStart[round];
1777
+ const stabMap = runouts.stabiliserMap[round];
1484
1778
  for (let board = 0; board < runouts.counts[round]; board++) {
1485
1779
  onBoard.fill(0);
1486
1780
  for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1781
+ const symmetric = stabStart[board + 1] - stabStart[board] > 1;
1487
1782
  for (let player = 0; player < 2; player++) {
1488
1783
  const index = players[player];
1489
1784
  const slot = (roundBase[round] + board) * 2 + player;
@@ -1492,6 +1787,7 @@ function buildActiveLists(runouts, players, showdown = null) {
1492
1787
  for (let i = 0; i < index.count; i++) {
1493
1788
  const combo = index.combos[i];
1494
1789
  if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1790
+ if (symmetric && !orbitLeader(runouts, round, board, combo)) continue;
1495
1791
  here.push(i);
1496
1792
  }
1497
1793
  if (showdown !== null && round === runouts.rounds - 1) {
@@ -1499,47 +1795,42 @@ function buildActiveLists(runouts, players, showdown = null) {
1499
1795
  here.sort((x, y) => group[index.combos[x]] - group[index.combos[y]] || x - y);
1500
1796
  }
1501
1797
  for (const i of here) {
1502
- entries.push(index.combos[i]);
1798
+ const combo = index.combos[i];
1799
+ entries.push(combo);
1503
1800
  entrySlots.push(i);
1504
- }
1505
- count[slot] = entries.length - start[slot];
1506
- }
1507
- }
1508
- }
1509
- const tieStart = new Int32Array(slots + 1);
1510
- const ties = [];
1511
- for (let round = 0; round < runouts.rounds; round++) {
1512
- const stabStart = runouts.stabiliserStart[round];
1513
- const stabMap = runouts.stabiliserMap[round];
1514
- for (let board = 0; board < runouts.counts[round]; board++) {
1515
- for (let player = 0; player < 2; player++) {
1516
- const slot = (roundBase[round] + board) * 2 + player;
1517
- tieStart[slot] = ties.length;
1518
- if (stabStart[board + 1] - stabStart[board] < 2) continue;
1519
- const position = /* @__PURE__ */ new Map();
1520
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) position.set(entries[e], e - start[slot]);
1521
- const seen = new Uint8Array(count[slot]);
1522
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) {
1523
- if (seen[e - start[slot]]) continue;
1524
- const members = [];
1525
- for (let k = stabStart[board]; k < stabStart[board + 1]; k++) {
1526
- const image = position.get(runouts.maps.combo[stabMap[k]][entries[e]]);
1527
- if (image === void 0 || seen[image]) continue;
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;
1528
1808
  seen[image] = 1;
1529
1809
  members.push(image);
1810
+ packedSlot[slot] = 1;
1530
1811
  }
1531
- if (members.length > 1) ties.push(members.length, ...members);
1812
+ for (let m = memberStart[memberStart.length - 1]; m < members.length; m++) seen[members[m]] = 0;
1532
1813
  }
1814
+ count[slot] = entries.length - start[slot];
1533
1815
  }
1534
1816
  }
1535
1817
  }
1536
- tieStart[slots] = ties.length;
1818
+ memberStart.push(members.length);
1537
1819
  const list = Uint16Array.from(entries);
1538
1820
  const cardA = new Uint8Array(list.length);
1539
1821
  const cardB = new Uint8Array(list.length);
1822
+ const multiplicity = new Float64Array(list.length);
1540
1823
  for (let e = 0; e < list.length; e++) {
1541
1824
  cardA[e] = COMBO_CARDS[list[e] * 2];
1542
1825
  cardB[e] = COMBO_CARDS[list[e] * 2 + 1];
1826
+ multiplicity[e] = memberStart[e + 1] - memberStart[e];
1827
+ }
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];
1543
1834
  }
1544
1835
  const strength = new Int32Array(list.length);
1545
1836
  if (showdown !== null) {
@@ -1558,11 +1849,15 @@ function buildActiveLists(runouts, players, showdown = null) {
1558
1849
  list,
1559
1850
  slot: Uint16Array.from(entrySlots),
1560
1851
  roundBase,
1561
- tieStart,
1562
- ties: Int32Array.from(ties),
1563
1852
  cardA,
1564
1853
  cardB,
1565
- strength
1854
+ strength,
1855
+ packed: packedSlot,
1856
+ multiplicity,
1857
+ memberStart: Int32Array.from(memberStart),
1858
+ memberCombo,
1859
+ memberA,
1860
+ memberB
1566
1861
  };
1567
1862
  }
1568
1863
  var strengthScratch = new Int32Array(COMBOS);
@@ -1576,35 +1871,6 @@ function strengthOn(table, board) {
1576
1871
  }
1577
1872
  return strengthScratch;
1578
1873
  }
1579
- function tieMirrors(store, slotBase, actions, stride, ties, from, to, integer) {
1580
- for (let a = 0; a < actions; a++) {
1581
- const row = slotBase + a * stride;
1582
- for (let k = from; k < to; ) {
1583
- const size = ties[k];
1584
- let sum = 0;
1585
- for (let j = 1; j <= size; j++) sum += store[row + ties[k + j]];
1586
- let mean = sum / size;
1587
- if (integer) mean = Math.round(mean);
1588
- for (let j = 1; j <= size; j++) store[row + ties[k + j]] = mean;
1589
- k += size + 1;
1590
- }
1591
- }
1592
- }
1593
- function tieBlock(ctx, node, board) {
1594
- const { tree } = ctx;
1595
- const owner = tree.player[node];
1596
- const lists = ctx.active;
1597
- const listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;
1598
- const from = lists.tieStart[listSlot];
1599
- const to = lists.tieStart[listSlot + 1];
1600
- if (from === to) return;
1601
- const actions = tree.numEdges[node];
1602
- const count = lists.count[listSlot];
1603
- const base = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];
1604
- const integer = ctx.regretScale !== null;
1605
- if (ctx.regret.length > 0) tieMirrors(ctx.regret, base, actions, count, lists.ties, from, to, integer);
1606
- tieMirrors(ctx.strategySum, base, actions, count, lists.ties, from, to, integer);
1607
- }
1608
1874
  function makeBuffers2(tree, maxActions, simd) {
1609
1875
  const depth = treeDepth2(tree) + 2;
1610
1876
  const make = (factory) => Array.from({ length: depth }, factory);
@@ -1650,7 +1916,7 @@ function dcfrFactors(t) {
1650
1916
  keepSum: ((t - 1) / t) ** DCFR_GAMMA
1651
1917
  };
1652
1918
  }
1653
- var Mode = { Train: 0, BestResponse: 1, Average: 2 };
1919
+ var Mode = { Train: 0, BestResponse: 1, Average: 2, Current: 3 };
1654
1920
  function normalise(source, base, actions, count, strategy) {
1655
1921
  const uniform = 1 / actions;
1656
1922
  for (let i = 0; i < count; i++) {
@@ -1669,6 +1935,20 @@ function normalise(source, base, actions, count, strategy) {
1669
1935
  }
1670
1936
  }
1671
1937
  }
1938
+ var TIE_TOLERANCE = 2 ** -20;
1939
+ function snapTies(actionValues, out, actions, count) {
1940
+ for (let a = 0; a < actions; a++) {
1941
+ const offset = a * count;
1942
+ for (let i = 0; i < count; i++) {
1943
+ const v = actionValues[offset + i];
1944
+ const value = out[i];
1945
+ const gap = v < value ? value - v : v - value;
1946
+ const size = v < 0 ? -v : v;
1947
+ const valueSize = value < 0 ? -value : value;
1948
+ if (gap <= TIE_TOLERANCE * (size > valueSize ? size : valueSize)) actionValues[offset + i] = value;
1949
+ }
1950
+ }
1951
+ }
1672
1952
  function regretMatch(regret, base, actions, count, strategy) {
1673
1953
  normalise(regret, base, actions, count, strategy);
1674
1954
  }
@@ -1719,6 +1999,26 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1719
1999
  const signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];
1720
2000
  const weight = ctx.runoutWeight[round] / ctx.chipScale;
1721
2001
  const hands = ctx.hands;
2002
+ if (lists.packed[oppSlot]) {
2003
+ foldValuesPacked(
2004
+ reachOpp,
2005
+ lists.cardA,
2006
+ lists.cardB,
2007
+ lists.memberStart,
2008
+ lists.memberA,
2009
+ lists.memberB,
2010
+ oppFrom,
2011
+ oppCount,
2012
+ myFrom,
2013
+ myCount,
2014
+ hands.same,
2015
+ hands.sameStart[mySlot],
2016
+ signed * weight,
2017
+ buffers.cardSums,
2018
+ out
2019
+ );
2020
+ return out;
2021
+ }
1722
2022
  foldValuesHands(
1723
2023
  reachOpp,
1724
2024
  lists.cardA,
@@ -1737,6 +2037,25 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1737
2037
  }
1738
2038
  if (kind === NodeKind.TerminalShowdown) {
1739
2039
  const weight = ctx.runoutWeight[round] / ctx.chipScale;
2040
+ if (lists.packed[oppSlot]) {
2041
+ showdownValuesPacked(
2042
+ reachOpp,
2043
+ lists.cardA,
2044
+ lists.cardB,
2045
+ lists.memberStart,
2046
+ lists.memberA,
2047
+ lists.memberB,
2048
+ lists.strength,
2049
+ oppFrom,
2050
+ oppCount,
2051
+ myFrom,
2052
+ myCount,
2053
+ tree.payoff[node] * weight,
2054
+ buffers.cardSums,
2055
+ out
2056
+ );
2057
+ return out;
2058
+ }
1740
2059
  showdownValuesHands(
1741
2060
  reachOpp,
1742
2061
  lists.cardA,
@@ -1776,10 +2095,13 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1776
2095
  const childMe = buffers.reachFor[traverser][depth];
1777
2096
  const childOpp = buffers.reachFor[opponent][depth];
1778
2097
  const sharded = nextRound === ctx.shardRound;
1779
- const first = runouts.childStart[nextRound][board];
1780
- const last = runouts.childStart[nextRound][board + 1];
2098
+ const starts = runouts.childStart[nextRound];
2099
+ const first = starts[board];
2100
+ const last = starts[board + 1];
1781
2101
  const from = sharded && ctx.shardStart > first ? ctx.shardStart : first;
1782
2102
  const to = sharded && ctx.shardEnd < last ? ctx.shardEnd : last;
2103
+ const sampling = ctx.sampling ?? null;
2104
+ const sampleHere = sampling !== null && mode === Mode.Train && ctx.applyUpdates && !ctx.expandOrbits && sampling.rounds[nextRound] === 1;
1783
2105
  for (let childBoard = from; childBoard < to; childBoard++) {
1784
2106
  const childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;
1785
2107
  const childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;
@@ -1790,15 +2112,40 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1790
2112
  let value = null;
1791
2113
  for (let m = firstMember; m < membersEnd; m++) {
1792
2114
  const upMe = upStart[m * 2 + traverser];
1793
- if (value === null || ctx.expandOrbits) {
2115
+ if (sampleHere && value === null) {
2116
+ value = sampledValue(
2117
+ ctx,
2118
+ sampling,
2119
+ buffers,
2120
+ traverser,
2121
+ iterWeight,
2122
+ node,
2123
+ child,
2124
+ nextRound,
2125
+ childBoard,
2126
+ reachMe,
2127
+ reachOpp,
2128
+ childMe,
2129
+ childOpp,
2130
+ depth
2131
+ );
2132
+ } else if (value === null || ctx.expandOrbits) {
1794
2133
  const upOpp = upStart[m * 2 + opponent];
1795
2134
  for (let k = 0; k < nMe; k++) childMe[k] = reachMe[up[upMe + k]];
1796
2135
  for (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp[up[upOpp + k]];
1797
2136
  value = traverse(ctx, buffers, mode, traverser, iterWeight, child, childBoard, childMe, childOpp, depth + 1);
1798
2137
  }
1799
- for (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];
2138
+ if (lists.packed[childMySlot]) {
2139
+ const childFrom = lists.start[childMySlot];
2140
+ for (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k] * lists.multiplicity[childFrom + k];
2141
+ } else {
2142
+ for (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];
2143
+ }
1800
2144
  }
1801
2145
  }
2146
+ if (lists.packed[mySlot]) {
2147
+ for (let i = 0; i < myCount; i++) out[i] /= lists.multiplicity[myFrom + i];
2148
+ }
1802
2149
  return out;
1803
2150
  }
1804
2151
  const actions = tree.numEdges[node];
@@ -1811,12 +2158,19 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1811
2158
  const slotBase = ctx.layout.offset[node] + actions * ctx.layout.rowStart[listSlot];
1812
2159
  const strategy = buffers.strategy[depth];
1813
2160
  const length = actions * stride;
1814
- if (mode === Mode.Train && buffers.kernels !== null) {
2161
+ const compactNode = round >= ctx.layout.compactFrom;
2162
+ const chunk = compactNode ? ctx.layout.compactChunk[node] : 0;
2163
+ const regrets = compactNode ? ctx.compactRegret[chunk] : ctx.regret;
2164
+ const compactSums = compactNode && ctx.compact.sums;
2165
+ const current = mode === Mode.Train || mode === Mode.Current || compactNode && !compactSums;
2166
+ if (current && buffers.kernels !== null) {
1815
2167
  const kernels = buffers.kernels;
1816
- kernels.input.set(ctx.regret.subarray(slotBase, slotBase + length));
2168
+ kernels.input.set(regrets.subarray(slotBase, slotBase + length));
1817
2169
  kernels.regretMatch(strategy, actions, stride);
1818
- } else if (mode === Mode.Train) {
1819
- regretMatch(ctx.regret, slotBase, actions, stride, strategy);
2170
+ } else if (current) {
2171
+ regretMatch(regrets, slotBase, actions, stride, strategy);
2172
+ } else if (compactSums) {
2173
+ averageStrategy(ctx.compactSum[chunk], slotBase, actions, stride, strategy, regrets);
1820
2174
  } else if (buffers.kernels !== null) {
1821
2175
  const kernels = buffers.kernels;
1822
2176
  kernels.input.set(ctx.strategySum.subarray(slotBase, slotBase + length));
@@ -1877,9 +2231,36 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1877
2231
  for (let i = 0; i < myCount; i++) out[i] += value[i];
1878
2232
  }
1879
2233
  }
1880
- if (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.regretScale !== null) {
2234
+ if (isTraverser && mode === Mode.Train && ctx.applyUpdates) snapTies(actionValues, out, actions, myCount);
2235
+ const weighted = ctx.layout.reachWeighted;
2236
+ if (weighted !== null && weighted[node] && isTraverser && mode === Mode.Train && ctx.applyUpdates) {
2237
+ for (let a = 0; a < actions; a++) {
2238
+ const offset = a * myCount;
2239
+ for (let i = 0; i < myCount; i++) {
2240
+ actionValues[offset + i] = out[i] + reachMe[i] * (actionValues[offset + i] - out[i]);
2241
+ }
2242
+ }
2243
+ }
2244
+ if (isTraverser && mode === Mode.Train && ctx.applyUpdates && compactNode) {
2245
+ updateCompact(
2246
+ ctx,
2247
+ node,
2248
+ chunk,
2249
+ ctx.layout.blockOffset[node] + board,
2250
+ slotBase,
2251
+ ctx.layout.handOffset[node] + ctx.layout.rowStart[listSlot],
2252
+ actions,
2253
+ stride,
2254
+ iterWeight,
2255
+ reachMe,
2256
+ strategy,
2257
+ actionValues,
2258
+ out
2259
+ );
2260
+ } else if (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.regretScale !== null) {
1881
2261
  updateQuantised(
1882
2262
  ctx,
2263
+ node,
1883
2264
  ctx.layout.blockOffset[node] + board,
1884
2265
  slotBase,
1885
2266
  actions,
@@ -1891,7 +2272,7 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1891
2272
  out
1892
2273
  );
1893
2274
  } else if (isTraverser && mode === Mode.Train && ctx.applyUpdates && ctx.dcfr) {
1894
- const { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);
2275
+ const { keepPositive, keepNegative, keepSum } = blockFactors(ctx, ctx.layout.blockOffset[node] + board, iterWeight);
1895
2276
  const regret = ctx.regret;
1896
2277
  const strategySum = ctx.strategySum;
1897
2278
  for (let a = 0; a < actions; a++) {
@@ -1902,7 +2283,7 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1902
2283
  const at = slotRow + i;
1903
2284
  const accumulated = regret[at];
1904
2285
  regret[at] = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + i] - out[i];
1905
- strategySum[at] = strategySum[at] * keepSum + reachMe[i] * strategy[row + i];
2286
+ strategySum[at] = strategySum[at] * keepSum + strategy[row + i];
1906
2287
  }
1907
2288
  }
1908
2289
  } else if (isTraverser && mode === Mode.Train && ctx.applyUpdates) {
@@ -1920,18 +2301,39 @@ function traverse(ctx, buffers, mode, traverser, iterWeight, node, board, reachM
1920
2301
  }
1921
2302
  }
1922
2303
  }
1923
- if (isTraverser && mode === Mode.Train && ctx.applyUpdates) {
1924
- const tieFrom = lists.tieStart[listSlot];
1925
- const tieTo = lists.tieStart[listSlot + 1];
1926
- if (tieFrom < tieTo) {
1927
- const integer = ctx.regretScale !== null;
1928
- tieMirrors(ctx.regret, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);
1929
- tieMirrors(ctx.strategySum, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);
1930
- }
1931
- }
1932
2304
  return out;
1933
2305
  }
1934
- function updateQuantised(ctx, block, slotBase, actions, count, iterWeight, reachMe, strategy, actionValues, out) {
2306
+ function sampledValue(ctx, s, buffers, traverser, t, node, child, nextRound, childBoard, reachMe, reachOpp, childMe, childOpp, depth) {
2307
+ const lists = ctx.active;
2308
+ const opponent = 1 - traverser;
2309
+ const childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;
2310
+ const nMe = lists.count[childMySlot];
2311
+ const at = s.baseOffset[node] + s.boardOffset[childMySlot];
2312
+ const walkAt = s.walkOffset[node] + childBoard * 2 + traverser;
2313
+ const fresh = s.lastWalk[walkAt] === 0;
2314
+ if (!fresh && !sampled(s, node, childBoard, t)) return s.baseline.subarray(at, at + nMe);
2315
+ const childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;
2316
+ const nOpp = lists.count[childOppSlot];
2317
+ const member = ctx.runouts.orbitStart[nextRound][childBoard];
2318
+ const upStart = ctx.hands.upStart[nextRound];
2319
+ const up = ctx.hands.up;
2320
+ const upMe = upStart[member * 2 + traverser];
2321
+ const upOpp = upStart[member * 2 + opponent];
2322
+ for (let k = 0; k < nMe; k++) childMe[k] = reachMe[up[upMe + k]];
2323
+ for (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp[up[upOpp + k]];
2324
+ const value = traverse(ctx, buffers, Mode.Train, traverser, t, child, childBoard, childMe, childOpp, depth + 1);
2325
+ const weight = s.unbiased ? 1 / s.p : 1;
2326
+ const baseline = s.baseline;
2327
+ for (let k = 0; k < nMe; k++) {
2328
+ const v = value[k];
2329
+ const b = baseline[at + k];
2330
+ baseline[at + k] = v;
2331
+ if (!fresh) value[k] = v + (weight - 1) * (v - b);
2332
+ }
2333
+ s.lastWalk[walkAt] = t;
2334
+ return value;
2335
+ }
2336
+ function updateQuantised(ctx, node, block, slotBase, actions, count, iterWeight, reachMe, strategy, actionValues, out) {
1935
2337
  const regret = ctx.regret;
1936
2338
  const strategySum = ctx.strategySum;
1937
2339
  const regretScale = ctx.regretScale;
@@ -1944,7 +2346,7 @@ function updateQuantised(ctx, block, slotBase, actions, count, iterWeight, reach
1944
2346
  let weight = iterWeight;
1945
2347
  const clamp = !ctx.dcfr;
1946
2348
  if (ctx.dcfr) {
1947
- ({ keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight));
2349
+ ({ keepPositive, keepNegative, keepSum } = blockFactors(ctx, block, iterWeight));
1948
2350
  weight = 1;
1949
2351
  }
1950
2352
  let largestRegret = 0;
@@ -1960,13 +2362,15 @@ function updateQuantised(ctx, block, slotBase, actions, count, iterWeight, reach
1960
2362
  const magnitude = updated < 0 ? -updated : updated;
1961
2363
  if (magnitude > largestRegret) largestRegret = magnitude;
1962
2364
  actionValues[offset + i] = updated;
1963
- const sum = strategySum[at] * oldSum * keepSum + weight * reachMe[i] * strategy[a * count + i];
2365
+ const added = clamp ? weight * reachMe[i] * strategy[a * count + i] : weight * strategy[a * count + i];
2366
+ const sum = strategySum[at] * oldSum * keepSum + added;
1964
2367
  if (sum > largestSum) largestSum = sum;
1965
2368
  strategy[a * count + i] = sum;
1966
2369
  }
1967
2370
  }
1968
2371
  const regretStep = largestRegret > 0 ? REGRET_STEPS / largestRegret : 0;
1969
2372
  const sumStep = largestSum > 0 ? SUM_STEPS / largestSum : 0;
2373
+ const salt = ctx.layout.shared ? node : 0;
1970
2374
  for (let a = 0; a < actions; a++) {
1971
2375
  const offset = a * count;
1972
2376
  const slotRow = slotBase + a * count;
@@ -1974,15 +2378,157 @@ function updateQuantised(ctx, block, slotBase, actions, count, iterWeight, reach
1974
2378
  const at = slotRow + i;
1975
2379
  const r = actionValues[offset + i] * regretStep;
1976
2380
  regret[at] = r < 0 ? r - 0.5 : r + 0.5;
1977
- const s = strategy[a * count + i] * sumStep + dither(at, iterWeight);
2381
+ const s = strategy[a * count + i] * sumStep + dither(at, iterWeight, salt);
1978
2382
  strategySum[at] = s < SUM_STEPS ? s : SUM_STEPS;
1979
2383
  }
1980
2384
  }
1981
2385
  regretScale[block] = largestRegret / REGRET_STEPS;
1982
2386
  sumScale[block] = largestSum / SUM_STEPS;
1983
2387
  }
1984
- function dither(slot, iteration) {
1985
- let h = Math.imul(slot ^ Math.imul(iteration, 2654435761), 2246822507);
2388
+ var SHIFT_BIAS = 160;
2389
+ var SHIFT_SCALE = Float64Array.from({ length: 256 }, (_, e) => e === 0 ? 0 : 2 ** (e - SHIFT_BIAS));
2390
+ function updateCompact(ctx, node, chunk, block, slotBase, handBase, actions, count, iterWeight, reachMe, strategy, actionValues, out) {
2391
+ const plan = ctx.compact;
2392
+ const q = ctx.compactRegret[chunk];
2393
+ const hashBase = ctx.layout.chunkStart[chunk] + slotBase;
2394
+ const salt = ctx.layout.shared ? node : 0;
2395
+ const steps = plan.steps;
2396
+ let keepPositive = 1;
2397
+ let keepNegative = 0;
2398
+ let keepSum = 1;
2399
+ let weight = iterWeight;
2400
+ const clamp = !ctx.dcfr;
2401
+ if (ctx.dcfr) {
2402
+ ({ keepPositive, keepNegative, keepSum } = blockFactors(ctx, block, iterWeight));
2403
+ weight = 1;
2404
+ }
2405
+ if (plan.float) {
2406
+ for (let k = 0; k < actions * count; k++) {
2407
+ const accumulated = q[slotBase + k];
2408
+ const updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[k % count];
2409
+ q[slotBase + k] = clamp && updated < 0 ? 0 : updated;
2410
+ }
2411
+ return;
2412
+ }
2413
+ if (!plan.perHand) {
2414
+ const scales = ctx.compactScale;
2415
+ const old = scales[block];
2416
+ let largest = 0;
2417
+ for (let a = 0; a < actions; a++) {
2418
+ const row = a * count;
2419
+ for (let i = 0; i < count; i++) {
2420
+ const accumulated = q[slotBase + row + i] * old;
2421
+ let updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[row + i] - out[i];
2422
+ if (clamp && updated < 0) updated = 0;
2423
+ actionValues[row + i] = updated;
2424
+ const magnitude = updated < 0 ? -updated : updated;
2425
+ if (magnitude > largest) largest = magnitude;
2426
+ }
2427
+ }
2428
+ const step = largest > 0 ? steps / largest : 0;
2429
+ const stochastic2 = plan.stochastic;
2430
+ for (let a = 0; a < actions; a++) {
2431
+ const row = a * count;
2432
+ let h = stochastic2 ? streamSeed(hashBase + row, iterWeight, salt) : 0;
2433
+ for (let i = 0; i < count; i++) {
2434
+ const value = actionValues[row + i] * step;
2435
+ let rounded;
2436
+ if (stochastic2) {
2437
+ h = nextState(h);
2438
+ rounded = Math.floor(value + (h >>> 0) / 4294967296);
2439
+ } else {
2440
+ rounded = Math.round(value);
2441
+ }
2442
+ q[slotBase + row + i] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;
2443
+ }
2444
+ }
2445
+ scales[block] = largest / steps;
2446
+ return;
2447
+ }
2448
+ const shifts = ctx.handShift[chunk];
2449
+ const stochastic = plan.stochastic;
2450
+ const sums = plan.sums ? ctx.compactSum[chunk] : null;
2451
+ const sumShifts = plan.sums ? ctx.sumShift[chunk] : null;
2452
+ for (let i = 0; i < count; i++) {
2453
+ const scale = SHIFT_SCALE[shifts[handBase + i]];
2454
+ let largest = 0;
2455
+ for (let a = 0; a < actions; a++) {
2456
+ const k = a * count + i;
2457
+ const accumulated = q[slotBase + k] * scale;
2458
+ let updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[i];
2459
+ if (clamp && updated < 0) updated = 0;
2460
+ actionValues[k] = updated;
2461
+ const magnitude = updated < 0 ? -updated : updated;
2462
+ if (magnitude > largest) largest = magnitude;
2463
+ }
2464
+ const exponent = scaleExponent(largest, steps);
2465
+ shifts[handBase + i] = exponent;
2466
+ const inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];
2467
+ let h = stochastic || sums !== null ? streamSeed(hashBase + i, iterWeight, salt) : 0;
2468
+ for (let a = 0; a < actions; a++) {
2469
+ const k = a * count + i;
2470
+ const value = actionValues[k] * inverse;
2471
+ let rounded;
2472
+ if (stochastic) {
2473
+ h = nextState(h);
2474
+ rounded = Math.floor(value + (h >>> 0) / 4294967296);
2475
+ } else {
2476
+ rounded = Math.round(value);
2477
+ }
2478
+ q[slotBase + k] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;
2479
+ }
2480
+ if (sums === null) continue;
2481
+ const sumScale = SHIFT_SCALE[sumShifts[handBase + i]];
2482
+ let largestSum = 0;
2483
+ for (let a = 0; a < actions; a++) {
2484
+ const k = a * count + i;
2485
+ const added = clamp ? weight * reachMe[i] * strategy[k] : weight * strategy[k];
2486
+ const sum = sums[slotBase + k] * sumScale * keepSum + added;
2487
+ strategy[k] = sum;
2488
+ if (sum > largestSum) largestSum = sum;
2489
+ }
2490
+ const sumExponent = scaleExponent(largestSum, COMPACT_SUM_STEPS);
2491
+ sumShifts[handBase + i] = sumExponent;
2492
+ const sumInverse = sumExponent === 0 ? 0 : 1 / SHIFT_SCALE[sumExponent];
2493
+ for (let a = 0; a < actions; a++) {
2494
+ const k = a * count + i;
2495
+ h = nextState(h);
2496
+ const rounded = Math.floor(strategy[k] * sumInverse + (h >>> 0) / 4294967296);
2497
+ sums[slotBase + k] = rounded < COMPACT_SUM_STEPS ? rounded : COMPACT_SUM_STEPS;
2498
+ }
2499
+ }
2500
+ }
2501
+ var COMPACT_SUM_STEPS = 255;
2502
+ function scaleExponent(largest, steps) {
2503
+ if (!(largest > 0)) return 0;
2504
+ EXPONENT_FLOAT[0] = largest / steps;
2505
+ const high2 = EXPONENT_BITS[1];
2506
+ let exponent = (high2 >>> 20 & 2047) - 1023 + SHIFT_BIAS;
2507
+ if ((high2 & 1048575) !== 0 || EXPONENT_BITS[0] !== 0) exponent++;
2508
+ return exponent < 1 ? 0 : exponent > 255 ? 255 : exponent;
2509
+ }
2510
+ function streamSeed(slot, iteration, salt) {
2511
+ return Math.imul(slot ^ Math.imul(iteration, 2654435761) ^ Math.imul(salt, 2146121005) ^ 1540483477, 2246822507) | 1;
2512
+ }
2513
+ function nextState(h) {
2514
+ h ^= h >>> 15;
2515
+ h = Math.imul(h, 739982445);
2516
+ return h ^ h >>> 12;
2517
+ }
2518
+ var EXPONENT_FLOAT = new Float64Array(1);
2519
+ var EXPONENT_BITS = new Uint32Array(EXPONENT_FLOAT.buffer);
2520
+ function storedStrategy(ctx, node, base, actions, count, strategy) {
2521
+ if (ctx.tree.round[node] >= ctx.layout.compactFrom && ctx.compact.sums) {
2522
+ const chunk = ctx.layout.compactChunk[node];
2523
+ averageStrategy(ctx.compactSum[chunk], base, actions, count, strategy, ctx.compactRegret[chunk]);
2524
+ } else if (ctx.tree.round[node] >= ctx.layout.compactFrom) {
2525
+ regretMatch(ctx.compactRegret[ctx.layout.compactChunk[node]], base, actions, count, strategy);
2526
+ } else {
2527
+ averageStrategy(ctx.strategySum, base, actions, count, strategy, ctx.regret);
2528
+ }
2529
+ }
2530
+ function dither(slot, iteration, salt = 0) {
2531
+ let h = Math.imul(slot ^ Math.imul(iteration, 2654435761) ^ Math.imul(salt, 668265263), 2246822507);
1986
2532
  h ^= h >>> 13;
1987
2533
  h = Math.imul(h, 3266489909);
1988
2534
  h ^= h >>> 16;
@@ -2024,7 +2570,7 @@ function makeSolver(ctx) {
2024
2570
  const weights = ctx.players[traverser].weights;
2025
2571
  const [from, count] = listOf(0, 0, traverser);
2026
2572
  let sum = 0;
2027
- for (let i = 0; i < count; i++) sum += weights[lists.list[from + i]] * values[i];
2573
+ for (let i = 0; i < count; i++) sum += weights[lists.list[from + i]] * lists.multiplicity[from + i] * values[i];
2028
2574
  return sum / ctx.totalMass;
2029
2575
  };
2030
2576
  return {
@@ -2034,6 +2580,9 @@ function makeSolver(ctx) {
2034
2580
  return rootCount;
2035
2581
  },
2036
2582
  traverseRoot: run,
2583
+ get root() {
2584
+ return root;
2585
+ },
2037
2586
  useRoot(next) {
2038
2587
  root = next ?? run;
2039
2588
  },
@@ -2050,17 +2599,79 @@ function makeSolver(ctx) {
2050
2599
  expectedValue() {
2051
2600
  return [total(root(Mode.Average, 0, 0), 0), total(root(Mode.Average, 1, 0), 1)];
2052
2601
  },
2602
+ rootValues(mode) {
2603
+ if (mode === Mode.Current && ctx.regret.length === 0 && !ctx.compactRegret) {
2604
+ throw new Error("The current profile needs regrets, and an analysis-only run has none");
2605
+ }
2606
+ const one = (player) => {
2607
+ const values = root(mode, player, 0);
2608
+ return [total(values, player), values.slice(0, listOf(0, 0, player)[1])];
2609
+ };
2610
+ const [total0, values0] = one(0);
2611
+ const [total1, values1] = one(1);
2612
+ return { totals: [total0, total1], values: [values0, values1] };
2613
+ },
2614
+ handEvs(player, values) {
2615
+ const opponent = ctx.players[1 - player];
2616
+ const evs = new Float64Array(COMBOS);
2617
+ const [from, count] = listOf(0, 0, player);
2618
+ if (values.length !== count) {
2619
+ throw new Error(`Player ${player} has ${count} root hands, but ${values.length} values were given`);
2620
+ }
2621
+ const scale = ctx.runoutWeight[0];
2622
+ for (let i = 0; i < count; i++) {
2623
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
2624
+ const combo = lists.memberCombo[m];
2625
+ const a = COMBO_CARDS[combo * 2];
2626
+ const b = COMBO_CARDS[combo * 2 + 1];
2627
+ let mass = 0;
2628
+ for (let j = 0; j < opponent.count; j++) {
2629
+ const other = opponent.combos[j];
2630
+ const c = COMBO_CARDS[other * 2];
2631
+ const d = COMBO_CARDS[other * 2 + 1];
2632
+ if (c !== a && c !== b && d !== a && d !== b) mass += opponent.weights[other];
2633
+ }
2634
+ evs[combo] = mass > 0 ? values[i] / (mass * scale) : 0;
2635
+ }
2636
+ }
2637
+ return evs;
2638
+ },
2053
2639
  exploitability() {
2054
2640
  const br0 = total(root(Mode.BestResponse, 0, 0), 0);
2055
2641
  const br1 = total(root(Mode.BestResponse, 1, 0), 1);
2056
2642
  return (br0 + br1) / 2;
2057
2643
  },
2058
2644
  valuesAt(node, board, traverser, reachMe, reachOpp, live, liveCount) {
2645
+ void live;
2646
+ void liveCount;
2647
+ const round = ctx.tree.round[node];
2648
+ const opponent = 1 - traverser;
2649
+ const [oppFrom, oppCount] = listOf(round, board, opponent);
2650
+ let symmetric = true;
2651
+ for (let j = 0; j < oppCount && symmetric; j++) {
2652
+ const own = reachOpp[lists.list[oppFrom + j]];
2653
+ for (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {
2654
+ if (reachOpp[lists.memberCombo[m]] !== own) symmetric = false;
2655
+ }
2656
+ }
2657
+ const members = (player) => {
2658
+ const [from, count] = listOf(round, board, player);
2659
+ return lists.memberCombo.slice(lists.memberStart[from], lists.memberStart[from + count]);
2660
+ };
2661
+ if (!symmetric) {
2662
+ const theirs = members(opponent).filter((combo) => reachOpp[combo] !== 0);
2663
+ const mine = members(traverser);
2664
+ const handReach = Float64Array.from(theirs, (combo) => reachOpp[combo]);
2665
+ const rows = pairValues(ctx, node, board, traverser, theirs, handReach, mine, mine.length);
2666
+ const result = new Float64Array(COMBOS);
2667
+ for (let k = 0; k < theirs.length; k++) {
2668
+ for (const combo of mine) result[combo] += rows[k * COMBOS + combo];
2669
+ }
2670
+ return result;
2671
+ }
2059
2672
  const expanded = ctx.expandOrbits;
2060
2673
  ctx.expandOrbits = true;
2061
2674
  try {
2062
- const round = ctx.tree.round[node];
2063
- const opponent = 1 - traverser;
2064
2675
  const me = new Float64Array(COMBOS);
2065
2676
  const opp = new Float64Array(COMBOS);
2066
2677
  gather(reachMe, round, board, traverser, me);
@@ -2068,9 +2679,11 @@ function makeSolver(ctx) {
2068
2679
  const value = traverse(ctx, buffers, Mode.Average, traverser, 0, node, board, me, opp, 0);
2069
2680
  const result = new Float64Array(COMBOS);
2070
2681
  const [from, count] = listOf(round, board, traverser);
2071
- for (let i = 0; i < count; i++) result[lists.list[from + i]] = value[i];
2072
- void live;
2073
- void liveCount;
2682
+ for (let i = 0; i < count; i++) {
2683
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
2684
+ result[lists.memberCombo[m]] = value[i];
2685
+ }
2686
+ }
2074
2687
  return result;
2075
2688
  } finally {
2076
2689
  ctx.expandOrbits = expanded;
@@ -2088,11 +2701,13 @@ function makeSolver(ctx) {
2088
2701
  const count = lists.count[slot];
2089
2702
  const base = ctx.layout.offset[node] + actions * ctx.layout.rowStart[slot];
2090
2703
  const strategy = new Float64Array(actions * count);
2091
- averageStrategy(ctx.strategySum, base, actions, count, strategy, ctx.regret);
2704
+ storedStrategy(ctx, node, base, actions, count, strategy);
2092
2705
  const probs = new Float64Array(index.count * actions).fill(1 / actions);
2093
2706
  for (let i = 0; i < count; i++) {
2094
- const at = lists.slot[from + i];
2095
- for (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];
2707
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
2708
+ const at = index.slot[lists.memberCombo[m]];
2709
+ for (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];
2710
+ }
2096
2711
  }
2097
2712
  return { actions, probs };
2098
2713
  }
@@ -2100,23 +2715,41 @@ function makeSolver(ctx) {
2100
2715
  }
2101
2716
 
2102
2717
  // src/wasm/engine.ts
2103
- var ENGINE_WASM = "AGFzbQEAAAABTglgAX8AYAZ/f39/f38Bf2AFf39/f38AYAd/f39/f3x/AGADf39/AGACf38AYAR/f39/AGAKf39/f399fX19fwF/YAl/f39/fX19fX8BfwIPAQNlbnYGbWVtb3J5AgAAAwsKAQIDBAUABgcIAAaOAjJ/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt8AUQAAAAAAADwPwt/AUF/C38BQQALfwFBAAt/AUEAC38BQQELfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC30BQwAAgD8LfQFDAAAAAAt9AUMAAIA/C30BQwAAgD8LfwFBAAt/AUEBCwdXCAhzZXRTaGFyZAADC3NldEV4Y2hhbmdlAAYIc2V0UGhhc2UABARpbml0AAkNc2V0TWF4QWN0aW9ucwAFA3J1bgAICXJ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JcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBJCEgACgCiAEkIiAAKAKMASQjIAAoApABuCQkCw==";
2104
2719
 
2105
2720
  // src/wasm/engine-shared.ts
2106
- var ENGINE_SHARED_WASM = "AGFzbQEAAAABTglgAX8AYAZ/f39/f38Bf2AFf39/f38AYAd/f39/f3x/AGADf39/AGACf38AYAR/f39/AGAKf39/f399fX19fwF/YAl/f39/fX19fX8BfwISAQNlbnYGbWVtb3J5AgMAgIAEAwsKAQIDBAUABgcIAAaOAjJ/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC38BQQALfwFBAAt8AUQAAAAAAADwPwt/AUF/C38BQQALfwFBAAt/AUEAC38BQQELfwFBAAt/AUEAC38BQQALfwFBAAt/AUEAC30BQwAAgD8LfQFDAAAAAAt9AUMAAIA/C30BQwAAgD8LfwFBAAt/AUEBCwdXCAhzZXRTaGFyZAADC3NldEV4Y2hhbmdlAAYIc2V0UGhhc2UABARpbml0AAkNc2V0TWF4QWN0aW9ucwAFA3J1bgAICXJ1bkNoYW5jZQAHBm1lbW9yeQIACqshCuIYBBV/An0FewN8Ix0gBSMebGohDSACIwkjASABai0AACIHQQJ0aigCAGpBAXQiCCAAaiIPQQJ0IgkjCmooAgAhCiMLIAlqKAIAIQtBASAAayIQIAhqIghBAnQiESMKaigCACESIwsgEWooAgAhESMAIAFqLQAAIhNBAkYEQCMUIAlqKAIAIQIjBiABQQJ0aigCALciIpogIiAAQQFGGyMaIAdBA3RqKwMAoiMhoyEkQQAhAANAIAAgEUgEQCAjIAQgAEECdGoqAg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8jMARAIBOsIAEgAUENdnNBtdzKlXxsIgFBEHYgAXOtfCMwrYJQDAELIy8gASATQa/W074CbHMiAUEPdiABc0G13MqVfGwiAUENdiABc0Gxz9myAWwiAUEQdiABc7hEAAAAAAAA8D2iZAtFCwRAIBAPCyMLIANBASAAa2pBAnRqKAIAIQEDQCAMIA9IBEAgCSAMQQJ0aiAHIAUgDEEBdGovAQBBAnRqKgIAOAIAIAxBAWohDAwBCwsDQCABIA1KBEAgCiANQQJ0aiAIIAYgDUEBdGovAQBBAnRqKgIAOAIAIA1BAWohDQwBCwsgACACIAQgCSAKIAtBAWoQACEAA0AgDiAPSARAIA5BAnQiASAAaiICKgIAIRQgASAQaiIBKgIAIRUgASAUOAIAIBJFBEAgAiAUIzFDAACAv5IgFCAVk5SSOAIACyAOQQFqIQ4MAQsLIBEjOjYCACAACysAIAAkQSAFJEIgBiRDIAckRCAIJEUgCUEARyRGIAEgAkEAIAMgBEEAEAALKwAgACRBIAQkQiAFJEMgBiREIAckRSAIQQBHJEYgAUEAQQAgAiADQQAQAAuOAgAgACgCACQAIAAoAgQkASAAKAIIJAIgACgCDCQDIAAoAhAkBCAAKAIUJAUgACgCGCQGIAAoAhwkByAAKAIgJAggACgCJCQJIAAoAigkCiAAKAIsJAsgACgCMCQMIAAoAjQkDSAAKAI4JA4gACgCPCQPIABBQGsoAgAkECAAKAJEJBEgACgCSCQSIAAoAkwkEyAAKAJQJBQgACgCVCQVIAAoAlgkFiAAKAJcJBcgACgCYCQYIAAoAmQkGSAAKAJoJBogACgCbCQbIAAoAnAkHCAAKAJ0JB0gACgCeCQeIAAoAnwkHyAAKAKAASQgIAAoAoQBJCEgACgCiAEkIiAAKAKMASQjIAAoApABuCQkCw==";
2722
+
2723
+ // src/platform/browser-threads.ts
2724
+ var THREADS_KEY = /* @__PURE__ */ Symbol.for("poker-flopsolve.browser-threads");
2725
+ var pending = Promise.resolve();
2107
2726
 
2108
2727
  // src/platform/browser.ts
2109
2728
  var PLATFORM = "browser";
2110
- var THREADS_AVAILABLE = false;
2111
2729
  var DEFAULT_MAX_BYTES = 512 * 1024 * 1024;
2730
+ function provider() {
2731
+ return globalThis[THREADS_KEY];
2732
+ }
2733
+ function threadLimit(engine) {
2734
+ const threads = provider();
2735
+ if (!engine || !threads || threads.idle() === 0) return 1;
2736
+ return compiledEngine("shared") ? 1 + threads.idle() : 1;
2737
+ }
2112
2738
  function defaultWorkerCount() {
2113
- return 1;
2739
+ return 1 + (provider()?.idle() ?? 0);
2740
+ }
2741
+ function threadAdvice(engine) {
2742
+ if (!provider()) return "call enableThreads() from poker-flopsolve/threads first, in a cross-origin isolated Web Worker";
2743
+ if (!engine) return "browser threads run only the WebAssembly engine (default engine, f32 precision)";
2744
+ return "the other threads are held by open runs; close() a run to free its threads";
2114
2745
  }
2115
2746
  function spawnWorker(_setup, _onError) {
2116
- throw new Error("Worker threads are only available in the Node build; use workers: 1 in the browser");
2747
+ throw new Error("The browser build threads only the WebAssembly engine; use workers: 1 with this solve");
2117
2748
  }
2118
- function spawnEngineWorker(_setup, _onError) {
2119
- throw new Error("Worker threads are only available in the Node build; use workers: 1 in the browser");
2749
+ function spawnEngineWorker(setup, onError) {
2750
+ const threads = provider();
2751
+ if (!threads) throw new Error("No engine threads; call enableThreads() from poker-flopsolve/threads first");
2752
+ return threads.spawn(setup, onError);
2120
2753
  }
2121
2754
 
2122
2755
  // src/parallel.ts
@@ -2128,8 +2761,31 @@ var CONTROL = {
2128
2761
  iterWeight: 4,
2129
2762
  ready: 5,
2130
2763
  mode: 6,
2764
+ /** Set, never cleared, once any thread's part of a step threw; see src/worker.ts. */
2765
+ failed: 7,
2131
2766
  size: 8
2132
2767
  };
2768
+ var THREAD_FAILED_ERROR = "A solver thread failed mid-iteration; this run cannot continue. Close it and solve again, or use workers: 1.";
2769
+ var THREAD_LOST_ERROR = "A solver thread stopped answering mid-iteration; it may have run out of memory or been killed. This run cannot continue. Close it and solve again, or use workers: 1.";
2770
+ var THREAD_BACKSTOP_FLOOR_MS = 6e4;
2771
+ var THREAD_BACKSTOP_FACTOR = 20;
2772
+ function backstopMs(ownMs, floorMs = THREAD_BACKSTOP_FLOOR_MS) {
2773
+ return Math.max(floorMs, THREAD_BACKSTOP_FACTOR * ownMs);
2774
+ }
2775
+ var WAIT_SLICE_MS = 50;
2776
+ var STOPPED_MS = 1e3;
2777
+ function awaitThreads(control, slot, target, dispatched, floorMs, stopped) {
2778
+ let giveUp = dispatched + backstopMs(performance.now() - dispatched, floorMs);
2779
+ for (; ; ) {
2780
+ const done = Atomics.load(control, slot);
2781
+ if (done >= target || stopped()) return null;
2782
+ const before = performance.now();
2783
+ if (before > giveUp) return new Error(THREAD_LOST_ERROR);
2784
+ Atomics.wait(control, slot, done, WAIT_SLICE_MS);
2785
+ const overrun = performance.now() - before - WAIT_SLICE_MS;
2786
+ if (overrun > STOPPED_MS) giveUp += overrun;
2787
+ }
2788
+ }
2133
2789
  var COMMAND = { work: 0, exit: 1 };
2134
2790
  var WORKER_START_MS = 3e4;
2135
2791
  var WORKER_START_ERROR = "Worker threads did not start within 30 s. Run with workers: 1, or check that worker threads can load this package.";
@@ -2158,7 +2814,7 @@ function planShards(tree, runouts, workers) {
2158
2814
  for (let w = 0; w <= workers; w++) bounds[w] = Math.round(boards * w / workers);
2159
2815
  return { round, boards, entryNodes: Int32Array.from(entryNodes), entryIndexOf, bounds };
2160
2816
  }
2161
- function startPool(ctx, solver, plan, payload, workers) {
2817
+ function startPool(ctx, solver, plan, payload, workers, spawn = spawnWorker, backstopFloorMs = THREAD_BACKSTOP_FLOOR_MS) {
2162
2818
  const entryCount = plan.entryNodes.length;
2163
2819
  const spawned = workers - 1;
2164
2820
  const reachFloats = entryCount * 2 * COMBOS;
@@ -2169,6 +2825,12 @@ function startPool(ctx, solver, plan, payload, workers) {
2169
2825
  const control = new Int32Array(controlBuffer);
2170
2826
  const threads = [];
2171
2827
  let failure = null;
2828
+ const samplingBuffers = ctx.sampling ? [ctx.sampling.baseline, ctx.sampling.lastWalk, ctx.sampling.lastUpdate].map((view) => {
2829
+ if (!(view.buffer instanceof SharedArrayBuffer) || view.byteOffset !== 0 || view.byteLength !== view.buffer.byteLength) {
2830
+ throw new Error("chanceSampling on worker threads needs its state in shared buffers of its own");
2831
+ }
2832
+ return view.buffer;
2833
+ }) : null;
2172
2834
  for (let w = 0; w < spawned; w++) {
2173
2835
  const setup = {
2174
2836
  workerId: w,
@@ -2180,11 +2842,17 @@ function startPool(ctx, solver, plan, payload, workers) {
2180
2842
  strategySum: ctx.strategySum.buffer,
2181
2843
  regretScale: ctx.regretScale?.buffer ?? null,
2182
2844
  sumScale: ctx.sumScale?.buffer ?? null,
2845
+ compactRegret: ctx.compactRegret?.map((chunk) => chunk.buffer) ?? null,
2846
+ handShift: ctx.handShift?.map((chunk) => chunk.buffer) ?? null,
2847
+ compactSum: ctx.compactSum?.map((chunk) => chunk.buffer) ?? null,
2848
+ sumShift: ctx.sumShift?.map((chunk) => chunk.buffer) ?? null,
2849
+ compactScale: ctx.compactScale?.buffer ?? null,
2850
+ sampling: samplingBuffers ? [samplingBuffers[0], samplingBuffers[1], samplingBuffers[2]] : null,
2183
2851
  control: controlBuffer,
2184
2852
  exchange: exchangeBuffer,
2185
2853
  entryCount
2186
2854
  };
2187
- const thread = spawnWorker(setup, (error) => {
2855
+ const thread = spawn(setup, (error) => {
2188
2856
  failure ??= error;
2189
2857
  Atomics.store(control, CONTROL.ready, spawned);
2190
2858
  Atomics.add(control, CONTROL.done, spawned);
@@ -2208,6 +2876,7 @@ function startPool(ctx, solver, plan, payload, workers) {
2208
2876
  const chanceValues = new Float64Array(entryCount * COMBOS);
2209
2877
  const mainReachMe = new Float64Array(COMBOS);
2210
2878
  const mainReachOpp = new Float64Array(COMBOS);
2879
+ const failed = () => failure ?? (Atomics.load(control, CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);
2211
2880
  const dispatch = (mode, traverser, iterWeight) => {
2212
2881
  Atomics.store(control, CONTROL.done, 0);
2213
2882
  Atomics.store(control, CONTROL.mode, mode);
@@ -2216,6 +2885,7 @@ function startPool(ctx, solver, plan, payload, workers) {
2216
2885
  Atomics.store(control, CONTROL.command, COMMAND.work);
2217
2886
  Atomics.add(control, CONTROL.generation, 1);
2218
2887
  Atomics.notify(control, CONTROL.generation);
2888
+ const dispatched = performance.now();
2219
2889
  const fullStart = ctx.shardStart;
2220
2890
  const fullEnd = ctx.shardEnd;
2221
2891
  ctx.shardStart = plan.bounds[0];
@@ -2241,43 +2911,49 @@ function startPool(ctx, solver, plan, payload, workers) {
2241
2911
  ctx.shardStart = fullStart;
2242
2912
  ctx.shardEnd = fullEnd;
2243
2913
  }
2244
- for (; ; ) {
2245
- const done = Atomics.load(control, CONTROL.done);
2246
- if (done >= spawned) break;
2247
- if (failure) throw failure;
2248
- Atomics.wait(control, CONTROL.done, done, 50);
2249
- }
2250
- if (failure) throw failure;
2914
+ failure ??= awaitThreads(control, CONTROL.done, spawned, dispatched, backstopFloorMs, () => failure !== null);
2915
+ const dead = failed();
2916
+ if (dead) throw dead;
2251
2917
  };
2252
- return {
2253
- workers,
2254
- traverse(mode, traverser, iterWeight) {
2255
- ctx.applyUpdates = false;
2256
- ctx.chanceOverride = null;
2257
- ctx.chanceCollect = (node, reachMe, reachOpp) => {
2258
- const entry = plan.entryIndexOf[node];
2259
- exchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);
2260
- exchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);
2261
- };
2262
- try {
2263
- solver.traverseRoot(mode, traverser, iterWeight);
2264
- } finally {
2265
- ctx.chanceCollect = null;
2266
- }
2267
- dispatch(mode, traverser, iterWeight);
2268
- for (let w = 0; w < spawned; w++) {
2269
- const base = reachFloats + w * entryCount * COMBOS;
2270
- for (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];
2271
- }
2272
- ctx.chanceOverride = chanceValues;
2273
- ctx.applyUpdates = true;
2918
+ const traverseAll = (mode, traverser, iterWeight) => {
2919
+ ctx.applyUpdates = false;
2920
+ ctx.chanceOverride = null;
2921
+ ctx.chanceCollect = (node, reachMe, reachOpp) => {
2922
+ const entry = plan.entryIndexOf[node];
2923
+ exchange.set(reachMe.subarray(0, COMBOS), entry * 2 * COMBOS);
2924
+ exchange.set(reachOpp.subarray(0, COMBOS), entry * 2 * COMBOS + COMBOS);
2925
+ };
2926
+ try {
2927
+ solver.traverseRoot(mode, traverser, iterWeight);
2928
+ } finally {
2929
+ ctx.chanceCollect = null;
2930
+ }
2931
+ dispatch(mode, traverser, iterWeight);
2932
+ for (let w = 0; w < spawned; w++) {
2933
+ const base = reachFloats + w * entryCount * COMBOS;
2934
+ for (let i = 0; i < entryCount * COMBOS; i++) chanceValues[i] += exchange[base + i];
2935
+ }
2936
+ ctx.chanceOverride = chanceValues;
2937
+ ctx.applyUpdates = true;
2938
+ try {
2939
+ const value = solver.traverseRoot(mode, traverser, iterWeight);
2940
+ total.set(value.subarray(0, COMBOS));
2941
+ } finally {
2942
+ ctx.chanceOverride = null;
2943
+ }
2944
+ return total;
2945
+ };
2946
+ return {
2947
+ workers,
2948
+ traverse(mode, traverser, iterWeight) {
2949
+ const dead = failed();
2950
+ if (dead) throw dead;
2274
2951
  try {
2275
- const value = solver.traverseRoot(mode, traverser, iterWeight);
2276
- total.set(value.subarray(0, COMBOS));
2277
- } finally {
2278
- ctx.chanceOverride = null;
2952
+ return traverseAll(mode, traverser, iterWeight);
2953
+ } catch (error) {
2954
+ Atomics.store(control, CONTROL.failed, 1);
2955
+ throw error;
2279
2956
  }
2280
- return total;
2281
2957
  },
2282
2958
  close() {
2283
2959
  Atomics.store(control, CONTROL.command, COMMAND.exit);
@@ -2292,25 +2968,40 @@ function startPool(ctx, solver, plan, payload, workers) {
2292
2968
  var wasm2 = globalThis.WebAssembly;
2293
2969
  var modules = { plain: void 0, shared: void 0 };
2294
2970
  function compiledEngine(kind) {
2295
- if (modules[kind] !== void 0) return modules[kind];
2296
- modules[kind] = null;
2971
+ return compileInto(modules, kind, kind === "plain" ? ENGINE_WASM : ENGINE_SHARED_WASM);
2972
+ }
2973
+ function compileInto(cache, kind, text) {
2974
+ if (cache[kind] !== void 0) return cache[kind];
2975
+ cache[kind] = null;
2297
2976
  try {
2298
2977
  if (!wasm2) return null;
2299
- const text = kind === "plain" ? ENGINE_WASM : ENGINE_SHARED_WASM;
2300
2978
  const bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
2301
2979
  if (!wasm2.validate(bytes)) return null;
2302
- modules[kind] = new wasm2.Module(bytes);
2980
+ cache[kind] = new wasm2.Module(bytes);
2303
2981
  } catch {
2304
- modules[kind] = null;
2982
+ cache[kind] = null;
2305
2983
  }
2306
- return modules[kind];
2984
+ return cache[kind];
2307
2985
  }
2308
- var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, size: 8 };
2986
+ var storageModules = /* @__PURE__ */ new WeakMap();
2987
+ function compiledStorage(source, kind) {
2988
+ let cache = storageModules.get(source);
2989
+ if (!cache) storageModules.set(source, cache = { plain: void 0, shared: void 0 });
2990
+ return compileInto(cache, kind, source[kind]);
2991
+ }
2992
+ var MAX_MEMORY = 4294901760;
2993
+ var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 };
2309
2994
  function createEngine(input, pool) {
2310
2995
  const shared = pool !== void 0;
2311
- const compiledModule = compiledEngine(shared ? "shared" : "plain");
2996
+ const storage = input.storage ?? null;
2997
+ const compiledModule = storage ? compiledStorage(storage.source, shared ? "shared" : "plain") : compiledEngine(shared ? "shared" : "plain");
2312
2998
  if (!compiledModule || !wasm2) return null;
2313
2999
  const { tree, runouts, layout, active, hands } = input;
3000
+ const compact = storage?.compact ?? null;
3001
+ const quantised = storage?.quantised ?? false;
3002
+ const width = quantised ? 2 : 4;
3003
+ const compactBytes = !compact ? 0 : compact.float ? layout.compactSlots * 4 : (layout.compactSlots + (compact.perHand ? layout.compactHands : 0)) * (compact.sums ? 2 : 1);
3004
+ if (layout.totalSlots * width * 2 + compactBytes > MAX_MEMORY || !(layout.offset instanceof Int32Array)) return null;
2314
3005
  const threads = pool ? pool.threads : 1;
2315
3006
  const flatten = (parts) => {
2316
3007
  const bases = new Int32Array(parts.length + 1);
@@ -2349,8 +3040,11 @@ function createEngine(input, pool) {
2349
3040
  add(active.cardA),
2350
3041
  add(active.cardB),
2351
3042
  add(active.strength),
2352
- add(active.tieStart),
2353
- add(active.ties),
3043
+ add(active.packed),
3044
+ add(Float32Array.from(active.multiplicity)),
3045
+ add(active.memberStart),
3046
+ add(active.memberA),
3047
+ add(active.memberB),
2354
3048
  add(upRound),
2355
3049
  add(upStart),
2356
3050
  add(hands.up),
@@ -2361,13 +3055,13 @@ function createEngine(input, pool) {
2361
3055
  add(orbitRound),
2362
3056
  add(orbitStart),
2363
3057
  add(input.runoutWeight),
2364
- add(null, layout.totalSlots * 4),
3058
+ add(null, layout.totalSlots * width),
2365
3059
  // regret
2366
- add(null, layout.totalSlots * 4)
3060
+ add(null, layout.totalSlots * width)
2367
3061
  // strategy sums
2368
3062
  ];
2369
- const REGRET = common[27];
2370
- const SUMS = common[28];
3063
+ const REGRET = common[common.length - 2];
3064
+ const SUMS = common[common.length - 1];
2371
3065
  const own = Array.from({ length: threads }, () => ({
2372
3066
  buffers: add(null, depths * depthBytes),
2373
3067
  cardSums: add(null, 52 * 8 + stride * 8),
@@ -2380,13 +3074,43 @@ function createEngine(input, pool) {
2380
3074
  const reach = pool ? add(null, entries * 2 * rowBytes) : -1;
2381
3075
  const values = pool ? add(null, entries * rowBytes) : -1;
2382
3076
  const partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;
3077
+ const plan = input.sampling;
3078
+ const sample = plan ? {
3079
+ baseOffset: add(plan.baseOffset),
3080
+ boardOffset: add(plan.boardOffset),
3081
+ walkOffset: add(plan.walkOffset),
3082
+ blockOffset: add(layout.blockOffset),
3083
+ baseline: add(null, plan.values * 4),
3084
+ lastWalk: add(null, plan.walks * 4),
3085
+ lastUpdate: add(null, plan.blocks * 4)
3086
+ } : null;
3087
+ const share = layout.shared ? {
3088
+ marks: add(null, layout.blocks * 4),
3089
+ blockOffset: sample ? sample.blockOffset : add(layout.blockOffset),
3090
+ weighted: layout.reachWeighted ? add(layout.reachWeighted) : -1
3091
+ } : null;
3092
+ const chunks = compact ? layout.chunkSlots.length : 0;
3093
+ const stored = storage ? {
3094
+ block: add(null, 128),
3095
+ blockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),
3096
+ regretScale: quantised ? add(null, layout.blocks * 8) : -1,
3097
+ sumScale: quantised ? add(null, layout.blocks * 8) : -1,
3098
+ compactChunk: compact ? add(layout.compactChunk) : -1,
3099
+ handOffset: compact ? add(Int32Array.from(layout.handOffset)) : -1,
3100
+ tables: compact ? add(null, chunks * 4 * 5) : -1,
3101
+ regrets: layout.chunkSlots.map((slots) => add(null, slots * (compact.float ? 4 : 1))),
3102
+ shifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],
3103
+ sums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],
3104
+ sumShifts: compact?.sums ? layout.chunkHands.map((count) => add(null, count)) : [],
3105
+ compactScale: compact && !compact.perHand && !compact.float ? add(null, layout.blocks * 8) : -1
3106
+ } : null;
2383
3107
  const offsets = [];
2384
- let total = 64;
3108
+ let total = 64 + Math.ceil(Math.max(input.lowBytes ?? 0, 0) / 16) * 16;
2385
3109
  for (const piece of pieces) {
2386
3110
  offsets.push(total);
2387
3111
  total += piece.bytes;
2388
3112
  }
2389
- if (total > 4294901760) return null;
3113
+ if (total > MAX_MEMORY) return null;
2390
3114
  const pages = Math.ceil(total / 65536) + 1;
2391
3115
  const memory = shared ? new wasm2.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm2.Memory({ initial: pages });
2392
3116
  const bytes = new Uint8Array(memory.buffer);
@@ -2396,20 +3120,91 @@ function createEngine(input, pool) {
2396
3120
  for (const mine of own) {
2397
3121
  const head = new Uint32Array(memory.buffer, offsets[mine.header], 40);
2398
3122
  common.forEach((slot, i) => head[i] = offsets[slot]);
2399
- head[29] = offsets[mine.buffers];
2400
- head[30] = depthBytes;
2401
- head[31] = rowBytes;
2402
- head[32] = offsets[mine.cardSums];
2403
- head[33] = input.chipScale;
3123
+ head[common.length] = offsets[mine.buffers];
3124
+ head[common.length + 1] = depthBytes;
3125
+ head[common.length + 2] = rowBytes;
3126
+ head[common.length + 3] = offsets[mine.cardSums];
3127
+ head[common.length + 4] = input.chipScale;
3128
+ if (stored) head[common.length + 5] = offsets[stored.block];
3129
+ }
3130
+ if (stored) {
3131
+ const at = (slot) => slot >= 0 ? offsets[slot] : 0;
3132
+ const block = new Uint32Array(memory.buffer, offsets[stored.block], 20);
3133
+ block.set([
3134
+ quantised ? 1 : 0,
3135
+ compact ? compact.from : 255,
3136
+ !compact ? 0 : compact.float ? 3 : compact.perHand ? 1 : 2,
3137
+ compact?.sums ? 1 : 0,
3138
+ compact?.stochastic ? 1 : 0,
3139
+ compact?.steps ?? 127,
3140
+ at(stored.regretScale),
3141
+ at(stored.sumScale),
3142
+ offsets[stored.blockOffset],
3143
+ at(stored.compactChunk),
3144
+ at(stored.handOffset)
3145
+ ]);
3146
+ if (compact) {
3147
+ const tables = offsets[stored.tables];
3148
+ const table = new Uint32Array(memory.buffer, tables, chunks * 5);
3149
+ for (let c = 0; c < chunks; c++) {
3150
+ table[c] = offsets[stored.regrets[c]];
3151
+ table[chunks + c] = stored.shifts.length ? offsets[stored.shifts[c]] : 0;
3152
+ table[2 * chunks + c] = stored.sums.length ? offsets[stored.sums[c]] : 0;
3153
+ table[3 * chunks + c] = stored.sumShifts.length ? offsets[stored.sumShifts[c]] : 0;
3154
+ table[4 * chunks + c] = layout.chunkStart[c] >>> 0;
3155
+ }
3156
+ block.set([tables, tables + chunks * 4, tables + chunks * 8, tables + chunks * 12, tables + chunks * 16, at(stored.compactScale)], 11);
3157
+ }
2404
3158
  }
3159
+ const factors = stored ? new Float64Array(memory.buffer, offsets[stored.block] + 80, 4) : null;
2405
3160
  const instance = new wasm2.Instance(compiledModule, { env: { memory, abort: () => {
2406
3161
  throw new Error("engine abort");
2407
3162
  } } });
2408
3163
  const exports = instance.exports;
2409
3164
  exports.init(offsets[own[0].header]);
2410
3165
  exports.setMaxActions(maxActions);
2411
- const regret = new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);
2412
- const strategySum = new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);
3166
+ let samplingViews = null;
3167
+ let samplingArgs = null;
3168
+ if (plan && sample) {
3169
+ let mask = 0;
3170
+ for (let r = 0; r < plan.rounds.length; r++) if (plan.rounds[r]) mask |= 1 << r;
3171
+ samplingArgs = [
3172
+ mask,
3173
+ plan.p,
3174
+ plan.every,
3175
+ plan.unbiased ? 1 : 0,
3176
+ plan.catchUp ? 1 : 0,
3177
+ offsets[sample.baseOffset],
3178
+ offsets[sample.boardOffset],
3179
+ offsets[sample.walkOffset],
3180
+ offsets[sample.baseline],
3181
+ offsets[sample.lastWalk],
3182
+ offsets[sample.lastUpdate],
3183
+ offsets[sample.blockOffset]
3184
+ ];
3185
+ const a = samplingArgs;
3186
+ exports.setSampling(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]);
3187
+ samplingViews = {
3188
+ baseline: new Float32Array(memory.buffer, offsets[sample.baseline], plan.values),
3189
+ lastWalk: new Int32Array(memory.buffer, offsets[sample.lastWalk], plan.walks),
3190
+ lastUpdate: new Int32Array(memory.buffer, offsets[sample.lastUpdate], plan.blocks)
3191
+ };
3192
+ }
3193
+ const weightedAt = share && share.weighted >= 0 ? offsets[share.weighted] : 0;
3194
+ if (share) exports.setShared(offsets[share.marks], offsets[share.blockOffset], weightedAt);
3195
+ const discounted = share ? new Int32Array(memory.buffer, offsets[share.marks], layout.blocks) : null;
3196
+ const regret = quantised ? new Int16Array(memory.buffer, offsets[REGRET], layout.totalSlots) : new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);
3197
+ const strategySum = quantised ? new Uint16Array(memory.buffer, offsets[SUMS], layout.totalSlots) : new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);
3198
+ const scaleView = (slot) => slot >= 0 ? new Float64Array(memory.buffer, offsets[slot], layout.blocks) : null;
3199
+ const compactViews = stored && compact ? {
3200
+ regret: stored.regrets.map(
3201
+ (slot, c) => compact.float ? new Float32Array(memory.buffer, offsets[slot], layout.chunkSlots[c]) : new Int8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])
3202
+ ),
3203
+ handShift: compact.perHand ? stored.shifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,
3204
+ sum: compact.sums ? stored.sums.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])) : null,
3205
+ sumShift: compact.sums ? stored.sumShifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,
3206
+ scale: scaleView(stored.compactScale)
3207
+ } : null;
2413
3208
  const me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);
2414
3209
  const opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);
2415
3210
  const result = new Float64Array(COMBOS);
@@ -2429,7 +3224,7 @@ function createEngine(input, pool) {
2429
3224
  const workers = [];
2430
3225
  let failure = null;
2431
3226
  if (pool) {
2432
- const plan = pool.plan;
3227
+ const plan2 = pool.plan;
2433
3228
  const controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);
2434
3229
  const settingsBuffer = new SharedArrayBuffer(8 * 8);
2435
3230
  control = new Int32Array(controlBuffer);
@@ -2442,14 +3237,17 @@ function createEngine(input, pool) {
2442
3237
  header: offsets[own[w].header],
2443
3238
  maxActions,
2444
3239
  exchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],
2445
- shard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],
2446
- entryNodes: plan.entryNodes,
3240
+ shard: [plan2.round, plan2.bounds[w], plan2.bounds[w + 1]],
3241
+ entryNodes: plan2.entryNodes,
2447
3242
  rootMe: offsets[own[w].rootMe],
2448
3243
  rootOpp: offsets[own[w].rootOpp],
2449
3244
  partial: offsets[partials] + (w - 1) * entries * rowBytes,
2450
3245
  stride,
2451
3246
  control: controlBuffer,
2452
- settings: settingsBuffer
3247
+ settings: settingsBuffer,
3248
+ ...share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] } : {},
3249
+ ...stored ? { storage: true } : {},
3250
+ ...samplingArgs ? { sampling: samplingArgs } : {}
2453
3251
  };
2454
3252
  workers.push(pool.spawn(setup, (error) => {
2455
3253
  failure ??= error;
@@ -2471,7 +3269,14 @@ function createEngine(input, pool) {
2471
3269
  throw failure;
2472
3270
  }
2473
3271
  }
2474
- const run = (mode, traverser, iterWeight, dcfr) => {
3272
+ const failed = () => failure ?? (control && Atomics.load(control, ENGINE_CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);
3273
+ let iteration = 0;
3274
+ let dcfrRule = 0;
3275
+ const run = (asked, traverser, iterWeight, dcfr) => {
3276
+ const dead = failed();
3277
+ if (dead) throw dead;
3278
+ const apply = asked === Mode.Current ? 0 : 1;
3279
+ const mode = asked === Mode.Current ? Mode.Train : asked;
2475
3280
  for (const player of [0, 1]) {
2476
3281
  const [from, count2] = rootList(player);
2477
3282
  const into = player === traverser ? me : opp;
@@ -2479,53 +3284,81 @@ function createEngine(input, pool) {
2479
3284
  for (let i = 0; i < count2; i++) into[i] = weights[active.list[from + i]];
2480
3285
  }
2481
3286
  const [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);
3287
+ iteration = mode === Mode.Train ? iterWeight : 0;
3288
+ dcfrRule = dcfr ? 1 : 0;
3289
+ if (plan || share || stored) exports.setIteration(iteration, dcfrRule);
3290
+ factors?.set([positive, mode === Mode.Train && !dcfr ? 0 : negative, sum, weight]);
2482
3291
  let at;
2483
3292
  if (!pool) {
2484
- at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);
3293
+ if (apply === 0) exports.setPhase(0, 0);
3294
+ try {
3295
+ at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;
3296
+ } finally {
3297
+ if (apply === 0) exports.setPhase(0, 1);
3298
+ }
2485
3299
  } else {
2486
- const plan = pool.plan;
2487
- exports.setShard(plan.round, 0, 0);
2488
- exports.setPhase(1, 0);
2489
- exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);
2490
- settings.set([positive, negative, sum, weight, clamp]);
2491
- Atomics.store(control, ENGINE_CONTROL.done, 0);
2492
- Atomics.store(control, ENGINE_CONTROL.mode, mode);
2493
- Atomics.store(control, ENGINE_CONTROL.traverser, traverser);
2494
- Atomics.store(control, ENGINE_CONTROL.command, 0);
2495
- Atomics.add(control, ENGINE_CONTROL.generation, 1);
2496
- Atomics.notify(control, ENGINE_CONTROL.generation);
2497
- exports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);
2498
- exports.setPhase(0, 1);
2499
- const valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);
2500
- for (let entry = 0; entry < entries; entry++) {
2501
- const slot = offsets[reach] + entry * 2 * rowBytes;
2502
- const out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp);
2503
- valueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);
2504
- }
2505
- for (; ; ) {
2506
- const done = Atomics.load(control, ENGINE_CONTROL.done);
2507
- if (done >= threads - 1 || failure) break;
2508
- Atomics.wait(control, ENGINE_CONTROL.done, done, 50);
2509
- }
2510
- if (failure) throw failure;
2511
- const partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);
2512
- for (let w = 0; w < threads - 1; w++) {
2513
- for (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];
2514
- }
2515
- exports.setShard(plan.round, 0, 0);
2516
- exports.setPhase(2, 1);
2517
- at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);
2518
- exports.setPhase(0, 1);
2519
- exports.setShard(-1, 0, 0);
3300
+ try {
3301
+ at = runThreaded(mode, traverser, apply, positive, negative, sum, weight, clamp);
3302
+ } catch (error) {
3303
+ Atomics.store(control, ENGINE_CONTROL.failed, 1);
3304
+ throw error;
3305
+ }
2520
3306
  }
2521
3307
  const [, count] = rootList(traverser);
2522
3308
  const values32 = new Float32Array(memory.buffer, at, count);
2523
3309
  for (let i = 0; i < count; i++) result[i] = values32[i];
2524
3310
  return result;
2525
3311
  };
3312
+ const runThreaded = (mode, traverser, apply, positive, negative, sum, weight, clamp) => {
3313
+ const plan2 = pool.plan;
3314
+ exports.setShard(plan2.round, 0, 0);
3315
+ exports.setPhase(1, 0);
3316
+ exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);
3317
+ settings.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);
3318
+ Atomics.store(control, ENGINE_CONTROL.done, 0);
3319
+ Atomics.store(control, ENGINE_CONTROL.mode, mode);
3320
+ Atomics.store(control, ENGINE_CONTROL.traverser, traverser);
3321
+ Atomics.store(control, ENGINE_CONTROL.command, 0);
3322
+ Atomics.add(control, ENGINE_CONTROL.generation, 1);
3323
+ Atomics.notify(control, ENGINE_CONTROL.generation);
3324
+ const dispatched = performance.now();
3325
+ exports.setShard(plan2.round, plan2.bounds[0], plan2.bounds[1]);
3326
+ 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);
3332
+ }
3333
+ failure ??= awaitThreads(
3334
+ control,
3335
+ ENGINE_CONTROL.done,
3336
+ threads - 1,
3337
+ dispatched,
3338
+ pool.backstopFloorMs,
3339
+ () => failure !== null
3340
+ );
3341
+ const dead = failed();
3342
+ 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];
3346
+ }
3347
+ exports.setShard(plan2.round, 0, 0);
3348
+ exports.setPhase(2, apply);
3349
+ const at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;
3350
+ exports.setPhase(0, 1);
3351
+ exports.setShard(-1, 0, 0);
3352
+ return at;
3353
+ };
2526
3354
  return {
2527
3355
  regret,
2528
3356
  strategySum,
3357
+ regretScale: stored ? scaleView(stored.regretScale) : null,
3358
+ sumScale: stored ? scaleView(stored.sumScale) : null,
3359
+ compact: compactViews,
3360
+ sampling: samplingViews,
3361
+ discounted,
2529
3362
  threads,
2530
3363
  root(dcfr) {
2531
3364
  return (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);
@@ -2544,7 +3377,7 @@ function createEngine(input, pool) {
2544
3377
  var SIZE_TOLERANCE = 1.35;
2545
3378
  var REGRET_STEPS2 = 32767;
2546
3379
  var SUM_STEPS2 = 65535;
2547
- function matchNodes(to, from) {
3380
+ function matchNodes(to, from, tolerance = SIZE_TOLERANCE) {
2548
3381
  const match = new Int32Array(to.nodeCount).fill(-1);
2549
3382
  const walk2 = (a, b) => {
2550
3383
  if (to.kind[a] !== from.kind[b] || to.round[a] !== from.round[b]) return;
@@ -2556,14 +3389,14 @@ function matchNodes(to, from) {
2556
3389
  match[a] = b;
2557
3390
  for (let e = 0; e < to.numEdges[a]; e++) {
2558
3391
  const edge = to.firstEdge[a] + e;
2559
- const other = matchEdge(to, edge, a, from, b);
3392
+ const other = matchEdge(to, edge, a, from, b, tolerance);
2560
3393
  if (other >= 0) walk2(to.edgeChild[edge], from.edgeChild[other]);
2561
3394
  }
2562
3395
  };
2563
3396
  walk2(0, 0);
2564
3397
  return match;
2565
3398
  }
2566
- function matchEdge(to, edge, node, from, other) {
3399
+ function matchEdge(to, edge, node, from, other, tolerance) {
2567
3400
  const kind = to.edgeAction[edge];
2568
3401
  const sized = kind === ActionKind.Bet || kind === ActionKind.Raise;
2569
3402
  const size = to.edgeTarget[edge] / to.pot[node];
@@ -2579,7 +3412,7 @@ function matchEdge(to, edge, node, from, other) {
2579
3412
  best = candidate;
2580
3413
  }
2581
3414
  }
2582
- return bestGap <= Math.log(SIZE_TOLERANCE) ? best : -1;
3415
+ return bestGap <= Math.log(tolerance) ? best : -1;
2583
3416
  }
2584
3417
  function readBlock(store, scale, block, base, length, out) {
2585
3418
  const factor = scale ? scale[block] : 1;
@@ -2599,24 +3432,93 @@ function writeBlock(store, scale, steps, block, base, length, values) {
2599
3432
  for (let i = 0; i < length; i++) store[base + i] = Math.round(values[i] * step);
2600
3433
  scale[block] = largest / steps;
2601
3434
  }
3435
+ function readCompactBlock(ctx, node, listSlot, block, base, actions, count, regrets, sums) {
3436
+ const plan = ctx.compact;
3437
+ const chunk = ctx.layout.compactChunk[node];
3438
+ const q = ctx.compactRegret[chunk];
3439
+ const handBase = ctx.layout.handOffset[node] + ctx.layout.rowStart[listSlot];
3440
+ const shifts = plan.perHand ? ctx.handShift[chunk] : null;
3441
+ const blockScale = !plan.perHand && !plan.float ? ctx.compactScale[block] : 1;
3442
+ for (let i = 0; i < count; i++) {
3443
+ const scale = shifts ? SHIFT_SCALE[shifts[handBase + i]] : blockScale;
3444
+ if (regrets) for (let a = 0; a < actions; a++) regrets[a * count + i] = q[base + a * count + i] * scale;
3445
+ if (!plan.sums) continue;
3446
+ const sumScale = SHIFT_SCALE[ctx.sumShift[chunk][handBase + i]];
3447
+ const stored = ctx.compactSum[chunk];
3448
+ for (let a = 0; a < actions; a++) sums[a * count + i] = stored[base + a * count + i] * sumScale;
3449
+ }
3450
+ if (!plan.sums) regretMatch(q, base, actions, count, sums);
3451
+ }
3452
+ function writeCompactBlock(ctx, node, listSlot, block, base, actions, count, regrets, sums) {
3453
+ const plan = ctx.compact;
3454
+ const chunk = ctx.layout.compactChunk[node];
3455
+ const q = ctx.compactRegret[chunk];
3456
+ const handBase = ctx.layout.handOffset[node] + ctx.layout.rowStart[listSlot];
3457
+ const steps = plan.steps;
3458
+ const fit = (value, top, bottom) => {
3459
+ const rounded = Math.round(value);
3460
+ return rounded > top ? top : rounded < bottom ? bottom : rounded;
3461
+ };
3462
+ if (regrets && plan.float) {
3463
+ for (let k = 0; k < actions * count; k++) q[base + k] = regrets[k];
3464
+ } else if (regrets && !plan.perHand) {
3465
+ let largest = 0;
3466
+ for (let k = 0; k < actions * count; k++) largest = Math.max(largest, Math.abs(regrets[k]));
3467
+ const step = largest > 0 ? steps / largest : 0;
3468
+ for (let k = 0; k < actions * count; k++) q[base + k] = fit(regrets[k] * step, steps, -steps);
3469
+ ctx.compactScale[block] = largest / steps;
3470
+ } else if (regrets) {
3471
+ const shifts2 = ctx.handShift[chunk];
3472
+ for (let i = 0; i < count; i++) {
3473
+ let largest = 0;
3474
+ for (let a = 0; a < actions; a++) largest = Math.max(largest, Math.abs(regrets[a * count + i]));
3475
+ const exponent = scaleExponent(largest, steps);
3476
+ shifts2[handBase + i] = exponent;
3477
+ const inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];
3478
+ for (let a = 0; a < actions; a++) q[base + a * count + i] = fit(regrets[a * count + i] * inverse, steps, -steps);
3479
+ }
3480
+ }
3481
+ if (!sums || !plan.sums) return;
3482
+ const stored = ctx.compactSum[chunk];
3483
+ const shifts = ctx.sumShift[chunk];
3484
+ for (let i = 0; i < count; i++) {
3485
+ let largest = 0;
3486
+ for (let a = 0; a < actions; a++) largest = Math.max(largest, sums[a * count + i]);
3487
+ const exponent = scaleExponent(largest, COMPACT_SUM_STEPS);
3488
+ shifts[handBase + i] = exponent;
3489
+ const inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];
3490
+ for (let a = 0; a < actions; a++) stored[base + a * count + i] = fit(sums[a * count + i] * inverse, COMPACT_SUM_STEPS, 0);
3491
+ }
3492
+ }
2602
3493
  function realCards(runouts, round, board) {
2603
3494
  const width = runouts.width[round];
2604
3495
  return Array.from(runouts.cards[round].subarray(board * width, (board + 1) * width));
2605
3496
  }
2606
- function warmStart(to, from, averages) {
3497
+ function warmStart(to, from, averages, cards, tolerance = SIZE_TOLERANCE) {
3498
+ if (!(tolerance >= 1)) throw new Error(`warmStart: the size tolerance is a ratio of at least 1, not ${tolerance}`);
3499
+ if (to.layout.shared && !from.layout.shared) {
3500
+ throw new Error("A spot with shareHistories can only warm-start from a solve that shares histories too");
3501
+ }
2607
3502
  const a = to.runouts.initial;
2608
3503
  const b = from.runouts.initial;
2609
- if (a.length !== b.length || a.some((card, i) => card !== b[i])) {
2610
- throw new Error("A warm start must come from a solve of the same board");
3504
+ if (cards) checkRelabelling(cards, a, b);
3505
+ else if (a.length !== b.length || a.some((card, i) => card !== b[i])) {
3506
+ throw new Error("A warm start must come from a solve of the same board, unless `warmCards` relabels one onto the other");
2611
3507
  }
2612
- const match = matchNodes(to.tree, from.tree);
3508
+ const asSource = (real) => cards ? [...b, ...real.slice(a.length).map((card) => cards[card])] : real;
3509
+ const comboOf = new Uint16Array(COMBOS);
3510
+ for (let combo = 0; combo < COMBOS; combo++) {
3511
+ comboOf[combo] = cards ? comboIndex(cards[COMBO_CARDS[combo * 2]], cards[COMBO_CARDS[combo * 2 + 1]]) : combo;
3512
+ }
3513
+ const match = matchNodes(to.tree, from.tree, tolerance);
2613
3514
  const { tree } = to;
2614
3515
  const width = to.layout.maxActions * COMBOS;
2615
3516
  const oldRegret = new Float64Array(width);
2616
3517
  const oldSum = new Float64Array(width);
2617
3518
  const newRegret = new Float64Array(width);
2618
3519
  const newSum = new Float64Array(width);
2619
- const hasRegret = to.regret.length > 0 && from.regret.length > 0;
3520
+ const keepsRegrets = (ctx) => ctx.regret.length > 0 || (ctx.compactRegret ?? null) !== null;
3521
+ const hasRegret = keepsRegrets(to) && keepsRegrets(from);
2620
3522
  const position = new Int32Array(COMBOS).fill(-1);
2621
3523
  let matched = 0;
2622
3524
  for (const node of tree.decisionNodes) {
@@ -2629,20 +3531,24 @@ function warmStart(to, from, averages) {
2629
3531
  const oldActions = from.tree.numEdges[old];
2630
3532
  const actionOf = new Int32Array(actions).fill(-1);
2631
3533
  for (let e = 0; e < actions; e++) {
2632
- const other = matchEdge(tree, tree.firstEdge[node] + e, node, from.tree, old);
3534
+ const other = matchEdge(tree, tree.firstEdge[node] + e, node, from.tree, old, tolerance);
2633
3535
  if (other >= 0) actionOf[e] = other - from.tree.firstEdge[old];
2634
3536
  }
2635
3537
  for (let board = 0; board < to.runouts.counts[round]; board++) {
2636
- const resolved = resolveBoard(from.runouts, realCards(to.runouts, round, board));
3538
+ const resolved = resolveBoard(from.runouts, asSource(realCards(to.runouts, round, board)));
2637
3539
  const oldSlot = (from.active.roundBase[round] + resolved.board) * 2 + owner;
2638
3540
  const oldFrom = from.active.start[oldSlot];
2639
3541
  const oldCount = from.active.count[oldSlot];
2640
3542
  const oldBlock = from.layout.blockOffset[old] + resolved.board;
2641
3543
  const oldBase = from.layout.offset[old] + oldActions * from.layout.rowStart[oldSlot];
2642
3544
  const oldLength = oldActions * oldCount;
2643
- if (hasRegret) readBlock(from.regret, from.regretScale, oldBlock, oldBase, oldLength, oldRegret);
2644
- readBlock(from.strategySum, from.sumScale, oldBlock, oldBase, oldLength, oldSum);
2645
- for (let j = 0; j < oldCount; j++) position[from.active.list[oldFrom + j]] = j;
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);
2646
3552
  const newSlot = (to.active.roundBase[round] + board) * 2 + owner;
2647
3553
  const newFrom = to.active.start[newSlot];
2648
3554
  const count = to.active.count[newSlot];
@@ -2650,34 +3556,659 @@ function warmStart(to, from, averages) {
2650
3556
  newRegret.fill(0, 0, length);
2651
3557
  newSum.fill(0, 0, length);
2652
3558
  for (let i = 0; i < count; i++) {
2653
- const j = position[resolved.combos[to.active.list[newFrom + i]]];
2654
- if (j < 0) continue;
2655
- for (let e = 0; e < actions; e++) {
2656
- const action = actionOf[e];
2657
- if (action < 0) continue;
2658
- newRegret[e * count + i] = oldRegret[action * oldCount + j];
2659
- newSum[e * count + i] = oldSum[action * oldCount + j];
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;
3565
+ for (let e = 0; e < actions; e++) {
3566
+ const action = actionOf[e];
3567
+ if (action < 0) continue;
3568
+ newRegret[e * count + i] += share * oldRegret[action * oldCount + j];
3569
+ newSum[e * count + i] += share * oldSum[action * oldCount + j];
3570
+ }
2660
3571
  }
2661
3572
  }
2662
- for (let j = 0; j < oldCount; j++) position[from.active.list[oldFrom + j]] = -1;
3573
+ markMembers(from.active, oldFrom, oldCount, position, true);
2663
3574
  const block = to.layout.blockOffset[node] + board;
2664
3575
  const base = to.layout.offset[node] + actions * to.layout.rowStart[newSlot];
2665
- if (hasRegret) writeBlock(to.regret, to.regretScale, REGRET_STEPS2, block, base, length, newRegret);
2666
- if (averages) writeBlock(to.strategySum, to.sumScale, SUM_STEPS2, block, base, length, newSum);
2667
- tieBlock(to, node, board);
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
+ }
2668
3582
  }
2669
3583
  }
2670
3584
  return { matchedNodes: matched, decisionNodes: tree.decisionNodes.length, averages };
2671
3585
  }
3586
+ function checkRelabelling(cards, a, b) {
3587
+ const seen = new Uint8Array(DECK);
3588
+ if (cards.length !== DECK) throw new Error(`A card relabelling maps all ${DECK} cards; got ${cards.length}`);
3589
+ for (const card of cards) {
3590
+ if (card >= DECK || seen[card]) throw new Error("A card relabelling must be a permutation of the deck");
3591
+ seen[card] = 1;
3592
+ }
3593
+ const target = new Set(b);
3594
+ if (a.length !== b.length || a.some((card) => !target.has(cards[card]))) {
3595
+ throw new Error("The card relabelling must take the board onto the warm start's board");
3596
+ }
3597
+ }
2672
3598
 
2673
- // src/index.ts
3599
+ // src/settle.ts
3600
+ function rootPlayNodes(solution) {
3601
+ const { tree } = solution.spot;
3602
+ if (tree.kind[0] !== NodeKind.Decision) return [];
3603
+ const nodes = [0];
3604
+ for (let e = 0; e < tree.numEdges[0]; e++) {
3605
+ const edge = tree.firstEdge[0] + e;
3606
+ const child = tree.edgeChild[edge];
3607
+ if (tree.edgeAction[edge] === ActionKind.Check && tree.kind[child] === NodeKind.Decision) nodes.push(child);
3608
+ }
3609
+ return nodes;
3610
+ }
3611
+ function rootPlay(solution) {
3612
+ const views = rootPlayNodes(solution).map((node) => solution.strategyAt(node, 0));
3613
+ return { views, weights: views.map((view) => solution.spot.players[view.player].weights) };
3614
+ }
3615
+ function rootPlayMovement(before, after) {
3616
+ if (before.views.length !== after.views.length) throw new Error("Root plays of different spots cannot be compared");
3617
+ let worst = 0;
3618
+ for (let d = 0; d < after.views.length; d++) {
3619
+ const a = before.views[d];
3620
+ const b = after.views[d];
3621
+ const actions = b.actions.length;
3622
+ if (a.node !== b.node || a.actions.length !== actions || a.combos.length !== b.combos.length) {
3623
+ throw new Error("Root plays of different spots cannot be compared");
3624
+ }
3625
+ const weights = after.weights[d];
3626
+ let moved = 0;
3627
+ let mass = 0;
3628
+ for (let i = 0; i < b.combos.length; i++) {
3629
+ const w = weights[b.combos[i]];
3630
+ if (!(w > 0)) continue;
3631
+ let tv = 0;
3632
+ for (let k = 0; k < actions; k++) tv += Math.abs(b.probs[i * actions + k] - a.probs[i * actions + k]);
3633
+ moved += w * tv / 2;
3634
+ mass += w;
3635
+ }
3636
+ if (mass > 0) worst = Math.max(worst, moved / mass);
3637
+ }
3638
+ return worst;
3639
+ }
3640
+ function settlePlan(options) {
3641
+ const plan = {
3642
+ every: options.every ?? 20,
3643
+ tolerance: options.tolerance ?? 0.01,
3644
+ patience: options.patience ?? 2,
3645
+ minIterations: options.minIterations ?? 0
3646
+ };
3647
+ if (!(Number.isInteger(plan.every) && plan.every > 0)) throw new Error(`settle.every must be a positive whole number; got ${plan.every}`);
3648
+ if (!(plan.tolerance >= 0)) throw new Error(`settle.tolerance must be 0 or more; got ${plan.tolerance}`);
3649
+ if (!(Number.isInteger(plan.patience) && plan.patience > 0)) {
3650
+ throw new Error(`settle.patience must be a positive whole number; got ${plan.patience}`);
3651
+ }
3652
+ if (!(plan.minIterations >= 0)) throw new Error(`settle.minIterations must be 0 or more; got ${plan.minIterations}`);
3653
+ return plan;
3654
+ }
3655
+ function trackSettle(options = {}) {
3656
+ const plan = settlePlan(options);
3657
+ let previous = null;
3658
+ let still = 0;
3659
+ let movement = Number.NaN;
3660
+ let settled = false;
3661
+ return {
3662
+ check(solution, iterations) {
3663
+ const play = rootPlay(solution);
3664
+ movement = previous ? rootPlayMovement(previous, play) : Number.NaN;
3665
+ previous = play;
3666
+ still = iterations >= plan.minIterations && movement <= plan.tolerance ? still + 1 : 0;
3667
+ settled = still >= plan.patience;
3668
+ return settled;
3669
+ },
3670
+ get movement() {
3671
+ return movement;
3672
+ },
3673
+ get settled() {
3674
+ return settled;
3675
+ }
3676
+ };
3677
+ }
3678
+
3679
+ // src/history-merge.ts
3680
+ function interner() {
3681
+ const ids = /* @__PURE__ */ new Map();
3682
+ return (key) => {
3683
+ let id = ids.get(key);
3684
+ if (id === void 0) ids.set(key, id = ids.size);
3685
+ return id;
3686
+ };
3687
+ }
3688
+ function signatures(tree) {
3689
+ const exact = new Int32Array(tree.nodeCount);
3690
+ const exactId = interner();
3691
+ for (let node = tree.nodeCount - 1; node >= 0; node--) {
3692
+ let e = `${tree.kind[node]},${tree.player[node]},${tree.round[node]},${tree.pot[node]},${tree.payoff[node]}`;
3693
+ const first = tree.firstEdge[node];
3694
+ for (let i = 0; i < tree.numEdges[node]; i++) {
3695
+ const edge = first + i;
3696
+ e += `|${tree.edgeAction[edge]}:${tree.edgeTarget[edge]}:${exact[tree.edgeChild[edge]]}`;
3697
+ }
3698
+ exact[node] = exactId(e);
3699
+ }
3700
+ return exact;
3701
+ }
3702
+ function aliasHistories(tree, runouts, options = {}) {
3703
+ const exact = signatures(tree);
3704
+ const alias = new Int32Array(tree.nodeCount);
3705
+ for (let node = 0; node < tree.nodeCount; node++) alias[node] = node;
3706
+ const rootsByRound = Array.from({ length: runouts.rounds }, () => []);
3707
+ for (let node = 0; node < tree.nodeCount; node++) {
3708
+ if (tree.kind[node] !== NodeKind.Chance) continue;
3709
+ const child = tree.edgeChild[tree.firstEdge[node]];
3710
+ if (tree.kind[child] === NodeKind.Decision) rootsByRound[tree.round[child]].push(child);
3711
+ }
3712
+ const walk2 = (rep, member) => {
3713
+ alias[member] = rep;
3714
+ const a = tree.firstEdge[rep];
3715
+ const b = tree.firstEdge[member];
3716
+ for (let i = 0; i < tree.numEdges[rep]; i++) walk2(tree.edgeChild[a + i], tree.edgeChild[b + i]);
3717
+ };
3718
+ const roots = new Int32Array(runouts.rounds);
3719
+ const groups = new Int32Array(runouts.rounds);
3720
+ const last = runouts.rounds - 1;
3721
+ if (last >= 1) {
3722
+ const reps = /* @__PURE__ */ new Map();
3723
+ for (const root of rootsByRound[last]) {
3724
+ if (options.keep?.[root]) continue;
3725
+ const rep = reps.get(exact[root]);
3726
+ if (rep === void 0) reps.set(exact[root], root);
3727
+ else walk2(rep, root);
3728
+ }
3729
+ groups[last] = reps.size;
3730
+ }
3731
+ for (let round = 1; round < runouts.rounds; round++) roots[round] = rootsByRound[round].length;
3732
+ return { alias, roots, groups };
3733
+ }
3734
+
3735
+ // src/betting.ts
2674
3736
  var DEFAULT_CHIP_SCALE = 100;
3737
+ function betRows(config, rounds) {
3738
+ const rowsFor = (sizes, who) => {
3739
+ const expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;
3740
+ if (expanded.length !== rounds) {
3741
+ throw new Error(
3742
+ `${who}betSizes has ${sizes.length} rows but this board has ${rounds} betting rounds; give one row per round, or a single row for all of them`
3743
+ );
3744
+ }
3745
+ return expanded;
3746
+ };
3747
+ return isPerPlayer(config.betSizes) ? { oop: rowsFor(config.betSizes.oop, "oop "), ip: rowsFor(config.betSizes.ip, "ip ") } : rowsFor(config.betSizes, "");
3748
+ }
3749
+ function treeConfig(config, rows) {
3750
+ const chipScale = config.chipScale ?? DEFAULT_CHIP_SCALE;
3751
+ return {
3752
+ potUnits: Math.round(config.pot * chipScale),
3753
+ stackUnits: Math.round(config.stack * chipScale),
3754
+ betSizes: rows,
3755
+ raiseSizes: config.raiseSizes,
3756
+ maxRaises: config.maxRaises ?? 1,
3757
+ allowAllIn: config.allowAllIn ?? false,
3758
+ allInThreshold: config.allInThreshold,
3759
+ noDonk: config.noDonk,
3760
+ mergeSizes: config.mergeSizes,
3761
+ removeActions: config.removeActions,
3762
+ thinSizes: config.thinSizes,
3763
+ chipScale,
3764
+ minRaiseUnits: chipScale
3765
+ };
3766
+ }
3767
+ function bettingTree(config) {
3768
+ const rounds = 6 - parseCards(config.board).length;
3769
+ if (rounds < 1 || rounds > 3) throw new Error(`A postflop board has 3, 4 or 5 cards; got ${config.board}`);
3770
+ return buildTree(treeConfig(config, betRows(config, rounds)), { rounds });
3771
+ }
3772
+
3773
+ // src/resolve.ts
3774
+ function resolveSubgame(blueprint, node, board, options) {
3775
+ const { player } = options;
3776
+ const opponent = 1 - player;
3777
+ const iterations = options.iterations ?? 200;
3778
+ if (!(Number.isInteger(iterations) && iterations > 0)) {
3779
+ throw new Error(`iterations must be a positive whole number; got ${iterations}`);
3780
+ }
3781
+ const spot = defineSpot(blueprint.subgameAt(node, board, options.betting));
3782
+ const base = spot.players[opponent].weights;
3783
+ const mine = spot.players[player].weights;
3784
+ const open = options.measure === true ? openMass(mine) : null;
3785
+ const live = liveCombos(spot.players);
3786
+ const blueprintValues = open ? bestResponseAt(blueprint.solver.ctx, node, board, opponent, base, mine) : null;
3787
+ const run = createRun(spot, { ...options.solve });
3788
+ try {
3789
+ run.step(iterations);
3790
+ let alternative = null;
3791
+ let entered = null;
3792
+ if (open && blueprintValues) {
3793
+ const { ctx } = run.solver;
3794
+ const deals = ctx.runoutWeight[0];
3795
+ alternative = new Float64Array(COMBOS).fill(Number.NaN);
3796
+ for (const combo of live) {
3797
+ if (base[combo] > 0 && open[combo] > 0) alternative[combo] = blueprintValues[combo] / (open[combo] * deals);
3798
+ }
3799
+ const lists = ctx.active;
3800
+ const slot = lists.roundBase[0] * 2 + opponent;
3801
+ const from = lists.start[slot];
3802
+ const response = run.solver.root(Mode.BestResponse, opponent, 0);
3803
+ entered = new Float64Array(COMBOS).fill(Number.NaN);
3804
+ for (let i = 0; i < lists.count[slot]; i++) {
3805
+ const combo = lists.list[from + i];
3806
+ if (!Number.isFinite(alternative[combo])) continue;
3807
+ const chips = response[i] / (open[combo] * deals);
3808
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) entered[lists.memberCombo[m]] = chips;
3809
+ }
3810
+ }
3811
+ return { solution: run.snapshot(), player, alternative, entered, iterations };
3812
+ } finally {
3813
+ run.close();
3814
+ }
3815
+ }
3816
+ function bestResponseAt(ctx, node, board, traverser, reachMe, reachOpp) {
3817
+ const lists = ctx.active;
3818
+ const round = ctx.tree.round[node];
3819
+ const listOf = (player) => {
3820
+ const slot = (lists.roundBase[round] + board) * 2 + player;
3821
+ return [lists.start[slot], lists.count[slot]];
3822
+ };
3823
+ const gather = (source, player) => {
3824
+ const [from, count] = listOf(player);
3825
+ const into = new Float64Array(COMBOS);
3826
+ for (let i = 0; i < count; i++) into[i] = source[lists.list[from + i]];
3827
+ return into;
3828
+ };
3829
+ const opponent = 1 - traverser;
3830
+ const [oppFrom, oppCount] = listOf(opponent);
3831
+ for (let j = 0; j < oppCount; j++) {
3832
+ const own = reachOpp[lists.list[oppFrom + j]];
3833
+ for (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {
3834
+ if (reachOpp[lists.memberCombo[m]] !== own) throw new Error("Best-response values need reach that mirrored hands share");
3835
+ }
3836
+ }
3837
+ const expanded = ctx.expandOrbits;
3838
+ ctx.expandOrbits = true;
3839
+ try {
3840
+ const buffers = makeBuffers2(ctx.tree, ctx.layout.maxActions, ctx.simd);
3841
+ const value = traverse(ctx, buffers, Mode.BestResponse, traverser, 0, node, board, gather(reachMe, traverser), gather(reachOpp, opponent), 0);
3842
+ const result = new Float64Array(COMBOS);
3843
+ const [from, count] = listOf(traverser);
3844
+ for (let i = 0; i < count; i++) {
3845
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) result[lists.memberCombo[m]] = value[i];
3846
+ }
3847
+ return result;
3848
+ } finally {
3849
+ ctx.expandOrbits = expanded;
3850
+ }
3851
+ }
3852
+ function liveCombos(players) {
3853
+ const live = [];
3854
+ for (let combo = 0; combo < COMBOS; combo++) {
3855
+ if (players[0].weights[combo] > 0 || players[1].weights[combo] > 0) live.push(combo);
3856
+ }
3857
+ return Uint16Array.from(live);
3858
+ }
3859
+ function openMass(range) {
3860
+ const held = [];
3861
+ for (let h = 0; h < COMBOS; h++) if (range[h] > 0) held.push(h);
3862
+ const open = new Float64Array(COMBOS);
3863
+ for (let h = 0; h < COMBOS; h++) {
3864
+ const a = COMBO_CARDS[h * 2];
3865
+ const b = COMBO_CARDS[h * 2 + 1];
3866
+ let mass = 0;
3867
+ for (const other of held) {
3868
+ const c = COMBO_CARDS[other * 2];
3869
+ const d = COMBO_CARDS[other * 2 + 1];
3870
+ if (c !== a && c !== b && d !== a && d !== b) mass += range[other];
3871
+ }
3872
+ open[h] = mass;
3873
+ }
3874
+ return open;
3875
+ }
3876
+
3877
+ // src/hybrid.ts
3878
+ function turnLineReach(solution) {
3879
+ const { tree, players } = solution.spot;
3880
+ if (solution.spot.runouts.rounds < 2) return [];
3881
+ const rootMass = matchupMass(players[0].weights, players[1].weights);
3882
+ const lines = [];
3883
+ for (let node = 0; node < tree.nodeCount; node++) {
3884
+ if (tree.kind[node] !== NodeKind.Chance || tree.round[node] !== 0) continue;
3885
+ const child = tree.edgeChild[tree.firstEdge[node]];
3886
+ if (tree.kind[child] !== NodeKind.Decision) continue;
3887
+ const share = matchupMass(solution.reachAt(child, 0, 0), solution.reachAt(child, 0, 1)) / rootMass;
3888
+ lines.push({ line: solution.path(child), node: child, share });
3889
+ }
3890
+ return lines.sort((a, b) => b.share - a.share);
3891
+ }
3892
+ function linesWithin(solution, maxBytes, options = {}) {
3893
+ const config = options.config ?? solution.spot.source;
3894
+ const precision = options.precision ?? "f32";
3895
+ const asked = config.shareHistories;
3896
+ if (!asked) throw new Error("linesWithin picks lines to keep out of shareHistories; this spot shares nothing");
3897
+ const share = asked === true ? {} : asked;
3898
+ const ranked = turnLineReach(solution).map((l) => l.line);
3899
+ const lines = (count) => [.../* @__PURE__ */ new Set([...share.keepLines ?? [], ...ranked.slice(0, count)])];
3900
+ const bytes = (count) => storageCost(defineSpot({ ...config, maxBytes: Number.MAX_SAFE_INTEGER, shareHistories: { ...share, keepLines: lines(count) } }), precision);
3901
+ const least = bytes(0);
3902
+ if (least > maxBytes) {
3903
+ throw new Error(`linesWithin: the spot needs ${least} bytes keeping no more lines, over the budget of ${maxBytes}`);
3904
+ }
3905
+ let low = 0;
3906
+ let high2 = ranked.length;
3907
+ while (low < high2) {
3908
+ const mid = Math.ceil((low + high2) / 2);
3909
+ if (bytes(mid) <= maxBytes) low = mid;
3910
+ else high2 = mid - 1;
3911
+ }
3912
+ return lines(low);
3913
+ }
3914
+
3915
+ // src/presets.ts
3916
+ function sizesCut(caller, preset) {
3917
+ const from = bettingTree(caller);
3918
+ const to = bettingTree(preset);
3919
+ const rounds = 6 - parseCards(caller.board).length;
3920
+ const streets = ["flop", "turn", "river"].slice(3 - rounds);
3921
+ const groups = /* @__PURE__ */ new Map();
3922
+ const walk2 = (a, b, invested) => {
3923
+ const kind = from.kind[a];
3924
+ if (kind === NodeKind.Chance) {
3925
+ walk2(from.edgeChild[from.firstEdge[a]], to.edgeChild[to.firstEdge[b]], invested);
3926
+ return;
3927
+ }
3928
+ if (kind !== NodeKind.Decision) return;
3929
+ const me = from.player[a];
3930
+ const owed = Math.max(0, invested[1 - me] - invested[me]);
3931
+ const facing = owed > 0 ? "raise" : "bet";
3932
+ const key = `${from.round[a]} ${me} ${facing}`;
3933
+ const group = groups.get(key) ?? { cut: /* @__PURE__ */ new Map(), decisions: 0, of: 0 };
3934
+ groups.set(key, group);
3935
+ const theirs = edgesOf(to, b);
3936
+ let sized = false;
3937
+ let lost = false;
3938
+ for (let e = from.firstEdge[a]; e < from.firstEdge[a] + from.numEdges[a]; e++) {
3939
+ const action = from.edgeAction[e];
3940
+ const target = from.edgeTarget[e];
3941
+ const aggressive = action === ActionKind.Bet || action === ActionKind.Raise || action === ActionKind.AllIn;
3942
+ if (aggressive) sized = true;
3943
+ const match = theirs.get(`${action} ${target}`);
3944
+ if (match === void 0) {
3945
+ if (!aggressive) throw new Error(`sizesCut: the preset's tree lost a fold, check or call at node ${a}`);
3946
+ lost = true;
3947
+ const size = action === ActionKind.AllIn ? "allin" : fraction(from, a, target, invested, me, owed);
3948
+ group.cut.set(String(size), size);
3949
+ continue;
3950
+ }
3951
+ const next = [invested[0], invested[1]];
3952
+ next[me] = target;
3953
+ walk2(from.edgeChild[e], to.edgeChild[match], next);
3954
+ }
3955
+ if (sized) group.of++;
3956
+ if (lost) group.decisions++;
3957
+ };
3958
+ walk2(0, 0, [0, 0]);
3959
+ const out = [];
3960
+ for (const [key, group] of groups) {
3961
+ if (group.cut.size === 0) continue;
3962
+ const [round, player, facing] = key.split(" ");
3963
+ const sizes = [...group.cut.values()].sort((x, y) => x === "allin" ? 1 : y === "allin" ? -1 : x - y);
3964
+ out.push({
3965
+ street: streets[Number(round)],
3966
+ player: player === "0" ? "oop" : "ip",
3967
+ facing,
3968
+ sizes,
3969
+ decisions: group.decisions,
3970
+ of: group.of
3971
+ });
3972
+ }
3973
+ const order = (c) => streets.indexOf(c.street) * 4 + (c.player === "oop" ? 0 : 2) + (c.facing === "bet" ? 0 : 1);
3974
+ return out.sort((x, y) => order(x) - order(y));
3975
+ }
3976
+ function edgesOf(tree, node) {
3977
+ const out = /* @__PURE__ */ new Map();
3978
+ for (let e = tree.firstEdge[node]; e < tree.firstEdge[node] + tree.numEdges[node]; e++) {
3979
+ out.set(`${tree.edgeAction[e]} ${tree.edgeTarget[e]}`, e);
3980
+ }
3981
+ return out;
3982
+ }
3983
+ function fraction(tree, node, target, invested, me, owed) {
3984
+ const potAfterCall = tree.pot[node] + owed;
3985
+ return Math.round((target - invested[me] - owed) / potAfterCall * 100) / 100;
3986
+ }
3987
+ function presetChanges(caller, preset, settings, notes) {
3988
+ const cuts = sizesCut(caller, preset);
3989
+ const roundsSimplified = ["flop", "turn", "river"].filter((s) => cuts.some((c) => c.street === s));
3990
+ const sizeNotes = cuts.map((c) => {
3991
+ const sizes = c.sizes.map((s) => s === "allin" ? "all-in" : String(s)).join(", ");
3992
+ const who = c.player === "oop" ? "OOP" : "IP";
3993
+ const what = c.facing === "bet" ? "bet" : "raise";
3994
+ return `${c.street}: ${who} loses the ${what} size${c.sizes.length > 1 ? "s" : ""} ${sizes} at ${c.decisions} of the ${c.of} such decisions the preset keeps`;
3995
+ });
3996
+ return { sizesCut: cuts, roundsSimplified, settings, notes: [...sizeNotes, ...notes] };
3997
+ }
3998
+ function samplingNote(sampling) {
3999
+ const which = sampling.rounds ? `the deals of rounds ${sampling.rounds.join(", ")}` : "every later round's deals";
4000
+ return sampling.every ? `${which} walked once every ${sampling.every} iterations, in rotation` : `${which} sampled at p ${sampling.p ?? 0.35}`;
4001
+ }
4002
+
4003
+ // src/lite.ts
4004
+ function liteConfig(config, options = {}) {
4005
+ const target = options.laterSize ?? 0.75;
4006
+ if (!(target > 0)) throw new Error(`laterSize must be above 0; got ${target}`);
4007
+ const rounds = 6 - parseCards(config.board).length;
4008
+ if (!(rounds >= 1 && rounds <= 3)) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);
4009
+ const flopCap = options.flopMaxRaises;
4010
+ if (flopCap !== void 0 && !(Number.isInteger(flopCap) && flopCap >= 1)) {
4011
+ throw new Error(`flopMaxRaises must be a whole number of at least 1; got ${flopCap}`);
4012
+ }
4013
+ const betSizes = mapPlayers(
4014
+ config.betSizes,
4015
+ (rows) => perRound(rows, true, rounds, "betSizes").map((row, r) => r === 0 ? row : nearest(row, target))
4016
+ );
4017
+ const raiseSizes = config.raiseSizes === void 0 ? void 0 : mapPlayers(
4018
+ config.raiseSizes,
4019
+ (side) => side === void 0 ? void 0 : raiseRows(side, rounds).map((row, r) => r === 0 ? row : nearest(row, target))
4020
+ );
4021
+ const maxRaises = mapPlayers(
4022
+ config.maxRaises ?? 1,
4023
+ (side) => perRound(side, Array.isArray(side), rounds, "maxRaises").map(
4024
+ (n, r) => r === 0 ? flopCap === void 0 ? n : Math.min(n, flopCap) : Math.min(n, options.laterRaise ? 2 : 1)
4025
+ )
4026
+ );
4027
+ const allowAllIn = mapPlayers(
4028
+ config.allowAllIn ?? false,
4029
+ (side) => perRound(side, Array.isArray(side), rounds, "allowAllIn").map((on, r) => r === 0 ? on : false)
4030
+ );
4031
+ const aggressions = (line) => line.split(" ").filter((w) => w === "bet" || w === "raise" || w === "allin").length;
4032
+ const removeActions = config.removeActions?.filter(
4033
+ (line) => !line.includes("/") && (flopCap === void 0 || aggressions(line) <= flopCap)
4034
+ );
4035
+ const buckets = options.runoutBuckets ?? 3;
4036
+ const given = typeof config.runoutBuckets === "number" ? config.runoutBuckets : config.runoutBuckets ? 1 : 0;
4037
+ return {
4038
+ ...config,
4039
+ betSizes,
4040
+ ...raiseSizes === void 0 ? {} : { raiseSizes },
4041
+ maxRaises,
4042
+ allowAllIn,
4043
+ ...options.noDonk === void 0 ? {} : { noDonk: options.noDonk },
4044
+ ...removeActions === void 0 ? {} : { removeActions },
4045
+ runoutBuckets: Math.max(buckets, given),
4046
+ shareHistories: options.shareHistories ?? config.shareHistories ?? true
4047
+ };
4048
+ }
4049
+ function raiseRows(side, rounds) {
4050
+ return raisesPerRound(side) ? perRound(side, true, rounds, "raiseSizes") : Array.from({ length: rounds }, () => side);
4051
+ }
4052
+ function nearest(row, target) {
4053
+ let best;
4054
+ let gap = Infinity;
4055
+ for (const size of row) {
4056
+ if (typeof size !== "number") continue;
4057
+ const g = Math.abs(Math.log(size / target));
4058
+ if (g < gap) {
4059
+ gap = g;
4060
+ best = size;
4061
+ }
4062
+ }
4063
+ if (best === void 0 && row.length > 0) best = row[0];
4064
+ return best === void 0 ? [] : [best];
4065
+ }
4066
+ function solveLite(config, options = {}) {
4067
+ const preset = litePreset(config, options);
4068
+ const blueprint = preset.config;
4069
+ const share = blueprint.shareHistories;
4070
+ const kept = typeof share === "object" ? [...share.keepLines ?? []] : [];
4071
+ const solution = solve(defineSpot(blueprint), preset.options);
4072
+ const subgameSolve = pick(options, ["workers", "precision", "wasmStorage"]);
4073
+ const { tree } = solution.spot;
4074
+ const scale = solution.spot.chipScale;
4075
+ return {
4076
+ solution,
4077
+ blueprint,
4078
+ kept,
4079
+ source: config,
4080
+ changes: preset.changes,
4081
+ resolve(node, board, resolveOptions) {
4082
+ const round = tree.round[node];
4083
+ const prefix = `${solution.path(node)} `;
4084
+ const invested = (tree.pot[node] - solution.spot.potUnits) / 2;
4085
+ const removeActions = (config.removeActions ?? []).filter((line) => line.startsWith(prefix)).map(
4086
+ (line) => line.slice(prefix.length).split(" ").map((word) => /^-?[\d.]+$/.test(word) ? String((Math.round(Number(word) * scale) - invested) / scale) : word).join(" ")
4087
+ );
4088
+ return resolveSubgame(solution, node, board, {
4089
+ ...resolveOptions,
4090
+ betting: { ...bettingFrom(config, round), removeActions, ...resolveOptions.betting },
4091
+ solve: { ...subgameSolve, ...resolveOptions.solve }
4092
+ });
4093
+ }
4094
+ };
4095
+ }
4096
+ function litePreset(config, options = {}) {
4097
+ const blueprint = keepWithin(liteConfig(config, options), options);
4098
+ const sampling = options.sampling === void 0 ? {} : options.sampling;
4099
+ const settle = options.settle === void 0 ? {} : options.settle;
4100
+ const solveOptions = {
4101
+ iterations: options.iterations ?? 2e3,
4102
+ ...settle ? { settle } : {},
4103
+ ...sampling ? { approximations: { chanceSampling: sampling } } : {},
4104
+ ...pick(options, ["workers", "precision", "wasmStorage", "algorithm", "onProgress", "targetPercent"])
4105
+ };
4106
+ const settings = [];
4107
+ const notes = [];
4108
+ const change = (setting, from, to, note) => {
4109
+ settings.push({ setting, from, to });
4110
+ notes.push(`${setting}: ${note}`);
4111
+ };
4112
+ const rounds = 6 - parseCards(config.board).length;
4113
+ const streets = ["flop", "turn", "river"].slice(3 - rounds);
4114
+ const donks = (value) => perRound(value ?? false, Array.isArray(value), rounds, "noDonk");
4115
+ const [donkFrom, donkTo] = [donks(config.noDonk), donks(blueprint.noDonk)];
4116
+ if (donkFrom.join() !== donkTo.join()) {
4117
+ const on = streets.filter((_, r) => donkTo[r]);
4118
+ change("noDonk", config.noDonk, blueprint.noDonk, on.length ? `donk bets forbidden on the ${on.join(" and ")}, a speed trim that changes the game` : "donk bets allowed on every street");
4119
+ }
4120
+ const gap = (value) => value === true ? 1 : typeof value === "number" ? value : 0;
4121
+ if (gap(config.runoutBuckets) !== gap(blueprint.runoutBuckets)) {
4122
+ const to = gap(blueprint.runoutBuckets);
4123
+ change("runoutBuckets", config.runoutBuckets, blueprint.runoutBuckets, to > 0 ? `gap ${to}: turn and river cards that play alike are solved once (approximate; folds nothing on ranges with no rank symmetry)` : "off: every turn and river card solved");
4124
+ }
4125
+ const sharing = (value) => JSON.stringify(value === true ? {} : value || null);
4126
+ if (sharing(config.shareHistories) !== sharing(blueprint.shareHistories)) {
4127
+ const kept = typeof blueprint.shareHistories === "object" ? blueprint.shareHistories.keepLines?.length ?? 0 : 0;
4128
+ change("shareHistories", config.shareHistories, blueprint.shareHistories, blueprint.shareHistories ? `lines that meet share river storage${kept ? `, but for ${kept} line${kept > 1 ? "s" : ""} kept apart` : ""} (approximate: exploitability plateaus a few % of pot from equilibrium; read the root play)` : "off: every line stores its own river");
4129
+ }
4130
+ const dropped = (config.removeActions?.length ?? 0) - (blueprint.removeActions?.length ?? 0);
4131
+ if (dropped > 0) {
4132
+ 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
+ }
4134
+ 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");
4136
+ return { config: blueprint, options: solveOptions, changes: presetChanges(config, blueprint, settings, notes) };
4137
+ }
4138
+ function keepWithin(blueprint, options = {}) {
4139
+ const budget = options.keepBudget;
4140
+ if (budget === void 0) return blueprint;
4141
+ if (!(budget > 0)) throw new Error(`keepBudget must be a number of bytes above 0; got ${budget}`);
4142
+ const its = options.pickIterations ?? 80;
4143
+ if (!(Number.isInteger(its) && its >= 1)) throw new Error(`pickIterations must be a whole number of at least 1; got ${its}`);
4144
+ const asked = blueprint.shareHistories;
4145
+ if (!asked) throw new Error("keepBudget keeps lines out of shareHistories; this blueprint shares nothing");
4146
+ const cheap = defineSpot(checkedDown(blueprint));
4147
+ const picked = solve(cheap, {
4148
+ iterations: its,
4149
+ ...pickSampling(options.sampling === void 0 ? {} : options.sampling, cheap.runouts.rounds),
4150
+ ...pick(options, ["workers", "precision", "wasmStorage", "algorithm"])
4151
+ });
4152
+ const keepLines = linesWithin(picked, budget, { config: blueprint, precision: options.precision ?? "f32" });
4153
+ return { ...blueprint, shareHistories: { ...asked === true ? {} : asked, keepLines } };
4154
+ }
4155
+ function pickSampling(sampling, rounds) {
4156
+ if (!sampling) return {};
4157
+ const asked = sampling.rounds ?? Array.from({ length: rounds - 1 }, (_, i) => i + 1);
4158
+ const kept = asked.filter((r) => r < rounds - 1);
4159
+ return kept.length > 0 ? { approximations: { chanceSampling: { ...sampling, rounds: kept } } } : {};
4160
+ }
4161
+ function checkedDown(config) {
4162
+ const rounds = 6 - parseCards(config.board).length;
4163
+ if (!(rounds >= 1 && rounds <= 3)) throw new Error(`A board has 3, 4 or 5 cards; got ${config.board}`);
4164
+ const last = rounds - 1;
4165
+ const betSizes = mapPlayers(
4166
+ config.betSizes,
4167
+ (rows) => perRound(rows, true, rounds, "betSizes").map((row, r) => r === last ? [] : row)
4168
+ );
4169
+ const allowAllIn = mapPlayers(
4170
+ config.allowAllIn ?? false,
4171
+ (side) => perRound(side, Array.isArray(side), rounds, "allowAllIn").map((on, r) => r === last ? false : on)
4172
+ );
4173
+ const removeActions = config.removeActions?.filter((line) => line.split("/").length - 1 < last);
4174
+ const asked = config.shareHistories;
4175
+ const shareHistories2 = typeof asked === "object" ? (({ keepLines: _kept, ...rest }) => rest)(asked) : asked;
4176
+ return {
4177
+ ...config,
4178
+ betSizes,
4179
+ allowAllIn,
4180
+ ...removeActions === void 0 ? {} : { removeActions },
4181
+ ...shareHistories2 === void 0 ? {} : { shareHistories: shareHistories2 }
4182
+ };
4183
+ }
4184
+ function pick(from, keys) {
4185
+ const out = {};
4186
+ for (const key of keys) if (from[key] !== void 0) out[key] = from[key];
4187
+ return out;
4188
+ }
4189
+ function bettingFrom(config, round) {
4190
+ const rounds = 6 - parseCards(config.board).length;
4191
+ const from = (value, listed, name) => listed ? perRound(value, true, rounds, name).slice(round) : value;
4192
+ const each = (value, listed, name) => value === void 0 ? void 0 : mapPlayers(value, (side) => from(side, listed(side), name));
4193
+ const out = {
4194
+ betSizes: each(config.betSizes, () => true, "betSizes"),
4195
+ raiseSizes: each(config.raiseSizes, (side) => side !== void 0 && raisesPerRound(side), "raiseSizes"),
4196
+ maxRaises: each(config.maxRaises ?? 1, Array.isArray, "maxRaises"),
4197
+ allowAllIn: each(config.allowAllIn ?? false, Array.isArray, "allowAllIn"),
4198
+ allInThreshold: each(config.allInThreshold, Array.isArray, "allInThreshold"),
4199
+ // The blueprint may forbid donk bets where the caller did not.
4200
+ noDonk: from(config.noDonk ?? false, Array.isArray(config.noDonk), "noDonk")
4201
+ };
4202
+ return out;
4203
+ }
4204
+
4205
+ // src/index.ts
2675
4206
  var OPS_PER_SECOND = 2e8;
2676
4207
  var SpotTooLargeError = class extends Error {
2677
4208
  estimate;
2678
4209
  constructor(estimate, maxBytes) {
2679
4210
  super(
2680
- `This spot needs ~${formatBytes(estimate.compressedBytes)} even at 16-bit precision, but the limit is ${formatBytes(maxBytes)}.
4211
+ (estimate.compactBytes !== null ? `This spot needs ~${formatBytes(estimate.compactBytes)} even with compact storage, ` : `This spot needs ~${formatBytes(estimate.compressedBytes)} even at 16-bit precision, `) + `but the limit is ${formatBytes(maxBytes)}.
2681
4212
  ${estimate.decisionNodes} decision nodes x up to ${estimate.runouts.toLocaleString()} runouts x ${Math.max(...estimate.combos)} combos.
2682
4213
  ` + (estimate.suggestions.length ? `Try:
2683
4214
  ${estimate.suggestions.map((s) => ` - ${s}`).join("\n")}
@@ -2707,16 +4238,7 @@ function defineSpot(config) {
2707
4238
  const rounds = 6 - board.length;
2708
4239
  if (config.pot <= 0) throw new Error("pot must be positive");
2709
4240
  if (config.stack <= 0) throw new Error("stack must be positive");
2710
- const rowsFor = (sizes, who) => {
2711
- const expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;
2712
- if (expanded.length !== rounds) {
2713
- throw new Error(
2714
- `${who}betSizes has ${sizes.length} rows but this board has ${rounds} betting rounds; give one row per round, or a single row for all of them`
2715
- );
2716
- }
2717
- return expanded;
2718
- };
2719
- const rows = isPerPlayer(config.betSizes) ? { oop: rowsFor(config.betSizes.oop, "oop "), ip: rowsFor(config.betSizes.ip, "ip ") } : rowsFor(config.betSizes, "");
4241
+ const rows = betRows(config, rounds);
2720
4242
  const onBoard = new Set(board);
2721
4243
  const trim = (range, who) => {
2722
4244
  const weights = typeof range === "string" ? parseRange(range) : Float64Array.from(range);
@@ -2746,34 +4268,21 @@ function defineSpot(config) {
2746
4268
  buildPlayerIndex(trim(config.ip, "in-position"))
2747
4269
  ];
2748
4270
  const symmetries = config.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights]);
2749
- const runouts = enumerateRunouts(
2750
- board,
2751
- symmetries,
2752
- config.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config.runoutBuckets) : void 0
2753
- );
2754
- const tree = buildTree(
2755
- {
2756
- potUnits: Math.round(config.pot * chipScale),
2757
- stackUnits: Math.round(config.stack * chipScale),
2758
- betSizes: rows,
2759
- raiseSizes: config.raiseSizes,
2760
- maxRaises: config.maxRaises ?? 1,
2761
- allowAllIn: config.allowAllIn ?? false,
2762
- allInThreshold: config.allInThreshold,
2763
- noDonk: config.noDonk,
2764
- mergeSizes: config.mergeSizes,
2765
- chipScale,
2766
- minRaiseUnits: chipScale
2767
- },
2768
- runouts
2769
- );
2770
- const layout = buildLayout(tree, runouts, players, 4);
4271
+ 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);
4273
+ const tree = buildTree(treeConfig(config, rows), runouts);
4274
+ const historyAlias = config.shareHistories ? shareHistories(tree, runouts, config, chipScale) : void 0;
4275
+ const layout = buildLayout(tree, runouts, players, 4, historyAlias);
2771
4276
  const last = runouts.rounds - 1;
2772
4277
  const showdownBytes = runouts.counts[last] * (2 * COMBOS + COMBOS + 1) * 2;
2773
4278
  const bytes = layout.bytes + showdownBytes;
2774
- const compressedBytes = buildLayout(tree, runouts, players, 2).bytes + showdownBytes;
4279
+ const compressedBytes = buildLayout(tree, runouts, players, 2, historyAlias).bytes + showdownBytes;
4280
+ const walkedSlots = layout.walkedSlots;
4281
+ const compact = config.compactStorage ? compactPlan(config.compactStorage, runouts.rounds) : null;
4282
+ const compactBytes = compact ? buildLayout(tree, runouts, players, 4, historyAlias, compact).bytes + showdownBytes : null;
4283
+ const needed = compactBytes ?? compressedBytes;
2775
4284
  const suggestions = [];
2776
- if (compressedBytes > maxBytes) {
4285
+ if (needed > maxBytes) {
2777
4286
  const widest = Math.max(...[0, 1].flatMap((p) => forPlayer(rows, p).map((r) => r.length)));
2778
4287
  if (widest > 1) suggestions.push(`use fewer bet sizes (currently up to ${widest} per round)`);
2779
4288
  const raises = [0, 1].flatMap((p) => [forPlayer(config.maxRaises ?? 1, p)].flat());
@@ -2789,8 +4298,9 @@ function defineSpot(config) {
2789
4298
  totalSlots: layout.totalSlots,
2790
4299
  bytes,
2791
4300
  compressedBytes,
2792
- secondsPerThousandIterations: layout.totalSlots * 4 * 1e3 / OPS_PER_SECOND,
2793
- fits: compressedBytes <= maxBytes,
4301
+ compactBytes,
4302
+ secondsPerThousandIterations: walkedSlots * 4 * 1e3 / OPS_PER_SECOND,
4303
+ fits: needed <= maxBytes,
2794
4304
  suggestions
2795
4305
  };
2796
4306
  if (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);
@@ -2804,30 +4314,107 @@ function defineSpot(config) {
2804
4314
  potUnits: Math.round(config.pot * chipScale),
2805
4315
  stackUnits: Math.round(config.stack * chipScale),
2806
4316
  source: config,
4317
+ ...historyAlias ? { historyAlias } : {},
2807
4318
  resolveBoard(cards) {
2808
4319
  return resolveBoard(runouts, typeof cards === "string" ? parseCards(cards) : cards);
2809
4320
  }
2810
4321
  };
2811
4322
  }
4323
+ function shareHistories(tree, runouts, config, chipScale) {
4324
+ const asked = config.shareHistories === true ? {} : config.shareHistories || {};
4325
+ const keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : void 0;
4326
+ return aliasHistories(tree, runouts, { keep }).alias;
4327
+ }
4328
+ function keptNodes(tree, chipScale, lines) {
4329
+ const parent = new Int32Array(tree.nodeCount).fill(-1);
4330
+ const paths = new Array(tree.nodeCount);
4331
+ paths[0] = "(root)";
4332
+ for (let node = 0; node < tree.nodeCount; node++) {
4333
+ for (let e = 0; e < tree.numEdges[node]; e++) {
4334
+ const edge = tree.firstEdge[node] + e;
4335
+ const child = tree.edgeChild[edge];
4336
+ parent[child] = node;
4337
+ const step = tree.kind[node] === NodeKind.Decision ? actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], chipScale) : "/";
4338
+ paths[child] = node === 0 ? step : `${paths[node]} ${step}`;
4339
+ }
4340
+ }
4341
+ const listed = new Set(lines);
4342
+ const missing = new Set(lines);
4343
+ const marks = new Uint8Array(tree.nodeCount);
4344
+ for (let node = 0; node < tree.nodeCount; node++) {
4345
+ if (listed.has(paths[node])) {
4346
+ missing.delete(paths[node]);
4347
+ marks[node] = 1;
4348
+ } else if (parent[node] >= 0 && marks[parent[node]]) {
4349
+ marks[node] = 1;
4350
+ }
4351
+ }
4352
+ if (missing.size > 0) {
4353
+ throw new Error(`shareHistories.keepLines: no node of this tree has the path ${[...missing].map((l) => `"${l}"`).join(", ")}`);
4354
+ }
4355
+ for (let node = tree.nodeCount - 1; node > 0; node--) if (marks[node]) marks[parent[node]] = 1;
4356
+ return marks;
4357
+ }
2812
4358
  var PRECISION_BYTES = { f64: 8, f32: 4, i16: 2 };
4359
+ var TREE_SETTINGS = [
4360
+ "betSizes",
4361
+ "raiseSizes",
4362
+ "maxRaises",
4363
+ "allowAllIn",
4364
+ "allInThreshold",
4365
+ "noDonk",
4366
+ "mergeSizes",
4367
+ "thinSizes"
4368
+ ];
2813
4369
  function createRun(spot, options = {}) {
4370
+ if (options.analysisOnly && options.approximations?.currentProfileEv) {
4371
+ throw new Error("approximations.currentProfileEv needs regrets, and an analysisOnly run has none");
4372
+ }
2814
4373
  const maxBytes = spot.source.maxBytes ?? DEFAULT_MAX_BYTES;
2815
- const { totalSlots, bytes } = spot.estimate;
2816
- const precision = options.analysisOnly ? "f32" : options.precision ?? (bytes <= maxBytes ? "f32" : "i16");
4374
+ const { bytes } = spot.estimate;
4375
+ const compact = spot.source.compactStorage ? compactPlan(spot.source.compactStorage, spot.runouts.rounds) : null;
4376
+ if (compact) {
4377
+ const clashes = [
4378
+ // An analysis-only run loads float32 sums, which compact nodes do not have.
4379
+ [options.analysisOnly, "analysisOnly"]
4380
+ ];
4381
+ const clash = clashes.find(([set]) => set)?.[1];
4382
+ if (clash) throw new Error(`compactStorage does not combine with ${clash}`);
4383
+ }
4384
+ const precision = compact ? options.precision ?? "f32" : options.analysisOnly ? "f32" : options.precision ?? (bytes <= maxBytes ? "f32" : "i16");
4385
+ const coarsePlan = planCoarseStart(spot, options, precision, maxBytes);
2817
4386
  const relevant = new Uint8Array(COMBOS);
2818
4387
  for (const combo of spot.players[0].combos) relevant[combo] = 1;
2819
4388
  for (const combo of spot.players[1].combos) relevant[combo] = 1;
2820
4389
  const showdown = buildShowdownTable(spot.runouts, relevant);
2821
- const layout = buildLayout(spot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision]);
4390
+ const layout = buildLayout(
4391
+ spot.tree,
4392
+ spot.runouts,
4393
+ spot.players,
4394
+ PRECISION_BYTES[precision],
4395
+ spot.historyAlias,
4396
+ compact ?? void 0
4397
+ );
2822
4398
  const weights = runoutWeights(spot.runouts);
2823
- const requested = resolveWorkers(options);
2824
- const plan = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;
4399
+ const storageEngine = options.wasmStorage !== void 0 && precision !== "f64" && (precision === "i16" || compact !== null);
4400
+ const wantsEngine = options.engine !== "js" && !options.analysisOnly && options.simd !== false && (precision === "f32" && !compact || storageEngine);
4401
+ const samplingOptions = options.approximations?.chanceSampling;
4402
+ const requested = resolveWorkers(options, wantsEngine);
4403
+ const shards = requested > 1 ? planShards(spot.tree, spot.runouts, requested) : null;
4404
+ const plan = shards && samplingOptions && sampledRounds(samplingOptions, spot.runouts.rounds).some((r) => r < shards.round) ? null : shards;
2825
4405
  const allocate = (bytes2) => plan ? new SharedArrayBuffer(bytes2) : new ArrayBuffer(bytes2);
2826
4406
  const width = PRECISION_BYTES[precision];
2827
4407
  const quantised = precision === "i16";
2828
4408
  const active = buildActiveLists(spot.runouts, spot.players, showdown);
2829
4409
  const hands = buildHandSpace(spot.runouts, spot.players, active);
2830
- const engine = options.engine !== "js" && precision === "f32" && !options.analysisOnly && options.simd !== false ? createEngine(
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
+ const engine = wantsEngine ? createEngine(
2831
4418
  {
2832
4419
  tree: spot.tree,
2833
4420
  runouts: spot.runouts,
@@ -2836,10 +4423,13 @@ function createRun(spot, options = {}) {
2836
4423
  active,
2837
4424
  hands,
2838
4425
  runoutWeight: weights,
2839
- chipScale: spot.chipScale
4426
+ chipScale: spot.chipScale,
4427
+ sampling: samplingPlan,
4428
+ ...storageEngine ? { storage: { source: options.wasmStorage, quantised, compact } } : {}
2840
4429
  },
2841
4430
  plan ? { plan, threads: requested, spawn: spawnEngineWorker } : void 0
2842
4431
  ) : null;
4432
+ const engineCompact = engine?.compact ?? null;
2843
4433
  const ctx = {
2844
4434
  tree: spot.tree,
2845
4435
  runouts: spot.runouts,
@@ -2848,8 +4438,16 @@ function createRun(spot, options = {}) {
2848
4438
  showdown,
2849
4439
  regret: engine ? engine.regret : options.analysisOnly ? new Float32Array(0) : makeRegretStore(precision, allocate(layout.totalSlots * width)),
2850
4440
  strategySum: engine ? engine.strategySum : makeSumStore(precision, allocate(layout.totalSlots * width)),
2851
- regretScale: quantised ? new Float64Array(allocate(layout.blocks * 8)) : null,
2852
- sumScale: quantised ? new Float64Array(allocate(layout.blocks * 8)) : null,
4441
+ regretScale: !quantised ? null : engine ? engine.regretScale : new Float64Array(allocate(layout.blocks * 8)),
4442
+ sumScale: !quantised ? null : engine ? engine.sumScale : new Float64Array(allocate(layout.blocks * 8)),
4443
+ compact,
4444
+ compactRegret: !compact ? null : engineCompact ? engineCompact.regret : layout.chunkSlots.map(
4445
+ (slots) => compact.float ? new Float32Array(allocate(slots * 4)) : new Int8Array(allocate(slots))
4446
+ ),
4447
+ handShift: !compact?.perHand ? null : engineCompact ? engineCompact.handShift : layout.chunkHands.map((hands2) => new Uint8Array(allocate(hands2))),
4448
+ compactSum: !compact?.sums ? null : engineCompact ? engineCompact.sum : layout.chunkSlots.map((slots) => new Uint8Array(allocate(slots))),
4449
+ sumShift: !compact?.sums ? null : engineCompact ? engineCompact.sumShift : layout.chunkHands.map((hands2) => new Uint8Array(allocate(hands2))),
4450
+ compactScale: !compact || compact.perHand || compact.float ? null : engineCompact ? engineCompact.scale : new Float64Array(allocate(layout.blocks * 8)),
2853
4451
  scratch: makeTerminalScratch(),
2854
4452
  chipScale: spot.chipScale,
2855
4453
  active,
@@ -2871,15 +4469,37 @@ function createRun(spot, options = {}) {
2871
4469
  totalMass: matchupMass(spot.players[0].weights, spot.players[1].weights) * weights[0],
2872
4470
  dcfr: (options.algorithm ?? "dcfr") === "dcfr"
2873
4471
  };
4472
+ if (samplingPlan) ctx.sampling = makeSampling(samplingPlan, engine?.sampling ?? void 0, allocate);
4473
+ if (layout.shared) ctx.discounted = engine?.discounted ?? new Int32Array(layout.blocks);
2874
4474
  let warm = null;
2875
4475
  let offset = 0;
2876
- if (options.warmStart) {
2877
- const source = options.warmStart;
2878
- warm = warmStart(ctx, source.solver.ctx, sameSpot(spot.source, source.spot.source));
2879
- offset = options.warmIteration ?? source.totalIterations;
4476
+ let solver;
4477
+ let pool;
4478
+ try {
4479
+ if (options.warmCards && !options.warmStart) {
4480
+ throw new Error("`warmCards` relabels a warm start, so it needs `warmStart` too");
4481
+ }
4482
+ if (options.warmStart) {
4483
+ const source = options.warmStart;
4484
+ warm = options.warmCards ? warmStart(ctx, source.solver.ctx, false, options.warmCards) : warmStart(ctx, source.solver.ctx, sameSpot(spot.source, source.spot.source));
4485
+ offset = options.warmIteration ?? source.totalIterations;
4486
+ } else if (coarsePlan && coarsePlan.iterations > 0) {
4487
+ const coarse = solveCoarse(coarsePlan, options);
4488
+ try {
4489
+ warm = warmStart(ctx, coarse.solver.ctx, false);
4490
+ } finally {
4491
+ coarse.close();
4492
+ }
4493
+ offset = options.warmIteration ?? coarse.totalIterations;
4494
+ }
4495
+ if (warm) ctx.sampling?.lastUpdate.fill(offset);
4496
+ solver = makeSolver(ctx);
4497
+ 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;
4499
+ } catch (error) {
4500
+ engine?.close();
4501
+ throw error;
2880
4502
  }
2881
- const solver = makeSolver(ctx);
2882
- const pool = plan && !engine ? startPool(ctx, solver, plan, { config: spot.source, dcfr: ctx.dcfr, precision, approximations: options.approximations, simd: ctx.simd }, requested) : null;
2883
4503
  if (pool) solver.useRoot(pool.traverse);
2884
4504
  if (engine) solver.useRoot(engine.root(ctx.dcfr));
2885
4505
  const threadCount = pool ? pool.workers : engine ? engine.threads : 1;
@@ -2913,7 +4533,8 @@ function createRun(spot, options = {}) {
2913
4533
  if (!spot.runouts.approximate) return this.exploitabilityPercent();
2914
4534
  const real = createRun(defineSpot({ ...spot.source, runoutBuckets: false }), {
2915
4535
  workers: threadCount,
2916
- precision
4536
+ precision,
4537
+ wasmStorage: options.wasmStorage
2917
4538
  });
2918
4539
  try {
2919
4540
  warmStart(real.solver.ctx, ctx, true);
@@ -2923,13 +4544,118 @@ function createRun(spot, options = {}) {
2923
4544
  }
2924
4545
  },
2925
4546
  snapshot(history = [], stoppedAt = "iterations") {
2926
- return makeSolution(spot, ctx, solver, completed, offset + completed, [...history], stoppedAt, threadCount);
4547
+ return makeSolution(
4548
+ spot,
4549
+ solver,
4550
+ completed,
4551
+ offset + completed,
4552
+ [...history],
4553
+ stoppedAt,
4554
+ threadCount,
4555
+ options.approximations?.currentProfileEv === true
4556
+ );
2927
4557
  }
2928
4558
  };
2929
4559
  }
4560
+ function compactPlan(settings, rounds) {
4561
+ const from = settings.from ?? 0;
4562
+ if (!Number.isInteger(from) || from < 0 || from >= rounds) {
4563
+ throw new Error(`compactStorage.from must be a round of this spot, 0 to ${rounds - 1}; got ${from}`);
4564
+ }
4565
+ const chunkBytes = settings.chunkBytes ?? 2 ** 30;
4566
+ if (!Number.isInteger(chunkBytes) || chunkBytes < 1) {
4567
+ throw new Error(`compactStorage.chunkBytes must be a positive whole number of bytes; got ${chunkBytes}`);
4568
+ }
4569
+ const steps = settings.steps ?? 127;
4570
+ if (!Number.isInteger(steps) || steps < 1 || steps > 127) {
4571
+ throw new Error(`compactStorage.steps must be an integer from 1 to 127; got ${steps}`);
4572
+ }
4573
+ if (settings.sums !== false && (settings.blockScale || settings.float)) {
4574
+ throw new Error("compactStorage.sums keeps a scale per hand, so blockScale and float need sums: false");
4575
+ }
4576
+ return {
4577
+ from,
4578
+ steps,
4579
+ perHand: !settings.blockScale && !settings.float,
4580
+ stochastic: !settings.nearest,
4581
+ float: settings.float === true,
4582
+ chunkBytes,
4583
+ sums: settings.sums ?? true
4584
+ };
4585
+ }
4586
+ var DEFAULT_COARSE_GAP = 3;
4587
+ var coarseMs = /* @__PURE__ */ new WeakMap();
4588
+ function planCoarseStart(spot, options, precision, maxBytes) {
4589
+ const settings = options.approximations?.coarseStart;
4590
+ if (!settings) return null;
4591
+ const { iterations, runoutBuckets = DEFAULT_COARSE_GAP } = settings;
4592
+ if (!(Number.isInteger(iterations) && iterations >= 0)) {
4593
+ throw new Error(`coarseStart.iterations must be a whole number of iterations; got ${iterations}`);
4594
+ }
4595
+ if (!(Number.isInteger(runoutBuckets) && runoutBuckets >= 1)) {
4596
+ throw new Error(`coarseStart.runoutBuckets must be a rank gap of 1 or more; got ${runoutBuckets}`);
4597
+ }
4598
+ if (options.warmStart) throw new Error("coarseStart is a warm start of its own; give one or the other, not both");
4599
+ if (options.analysisOnly) throw new Error("coarseStart solves; an analysis-only run must never be stepped");
4600
+ const own = spot.source.runoutBuckets;
4601
+ const ownGap = own === true ? DEFAULT_BUCKET_GAP : own || 0;
4602
+ if (iterations === 0 || spot.board.length === 5 || runoutBuckets <= ownGap) return null;
4603
+ const coarseSpot = defineSpot({ ...spot.source, runoutBuckets });
4604
+ if (coarseSpot.runouts.counts.at(-1) >= spot.runouts.counts.at(-1)) return null;
4605
+ const used = storageCost(spot, precision);
4606
+ 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
+ }
4614
+ return { spot: coarseSpot, iterations, precision: coarsePrecision, elapsed: 0 };
4615
+ }
4616
+ function solveCoarse(plan, options) {
4617
+ const started = Date.now();
4618
+ const { coarseStart: _, ...rest } = options.approximations;
4619
+ const run = createRun(plan.spot, {
4620
+ workers: options.workers,
4621
+ precision: plan.precision,
4622
+ algorithm: options.algorithm,
4623
+ simd: options.simd,
4624
+ engine: options.engine,
4625
+ wasmStorage: options.wasmStorage,
4626
+ approximations: rest
4627
+ });
4628
+ try {
4629
+ run.step(plan.iterations);
4630
+ } catch (error) {
4631
+ run.close();
4632
+ throw error;
4633
+ }
4634
+ plan.elapsed = Date.now() - started;
4635
+ return run;
4636
+ }
4637
+ function storageCost(of, at) {
4638
+ if (of.estimate.compactBytes === null) {
4639
+ return at === "i16" ? of.estimate.compressedBytes : of.estimate.bytes * (at === "f64" ? 2 : 1);
4640
+ }
4641
+ const plan = compactPlan(of.source.compactStorage, of.runouts.rounds);
4642
+ const bytesAt = (width) => buildLayout(of.tree, of.runouts, of.players, width, of.historyAlias, plan).bytes;
4643
+ return of.estimate.compactBytes + bytesAt(PRECISION_BYTES[at]) - bytesAt(4);
4644
+ }
2930
4645
  function sameSpot(a, b) {
2931
4646
  const plain = ({ maxBytes: _bytes, maxCombos: _combos, isomorphism: _iso, ...game }) => JSON.stringify(game, (_, value) => value instanceof Float64Array ? Array.from(value) : value);
2932
- return plain(a) === plain(b);
4647
+ const kept = (config) => typeof config.shareHistories === "object" ? config.shareHistories.keepLines : void 0;
4648
+ if (kept(a) === void 0 && kept(b) === void 0) return plain(a) === plain(b);
4649
+ const mine = new Set(kept(a) ?? []);
4650
+ if (!(kept(b) ?? []).every((line) => mine.has(line))) return false;
4651
+ return plain(withoutKeptLines(a)) === plain(withoutKeptLines(b));
4652
+ }
4653
+ function withoutKeptLines(config) {
4654
+ const asked = config.shareHistories;
4655
+ if (!asked) return config;
4656
+ const { keepLines: _kept, ...rest } = asked === true ? {} : asked;
4657
+ const set = Object.entries(rest).filter(([, value]) => value !== void 0);
4658
+ return { ...config, shareHistories: set.length > 0 ? Object.fromEntries(set) : true };
2933
4659
  }
2934
4660
  var DEFAULT_BUCKET_GAP = 1;
2935
4661
  function rangeRankMerge(players, maxGap) {
@@ -2950,16 +4676,18 @@ function rangeRankMerge(players, maxGap) {
2950
4676
  }
2951
4677
  return { ranks: (a, b) => allowed[a * 13 + b] === 1, maxGap };
2952
4678
  }
2953
- var warnedThreads = false;
2954
- function resolveWorkers(options) {
4679
+ var threadWarnings = /* @__PURE__ */ new Set();
4680
+ function resolveWorkers(options, engine) {
2955
4681
  if (options.analysisOnly) return 1;
2956
4682
  const asked = options.workers === "auto" ? defaultWorkerCount() : options.workers ?? 1;
2957
- if (asked > 1 && !THREADS_AVAILABLE) {
2958
- if (!warnedThreads) {
2959
- warnedThreads = true;
2960
- console.warn(`poker-flopsolve: worker threads are Node-only; solving on one thread (${PLATFORM} build)`);
4683
+ const limit = threadLimit(engine);
4684
+ if (asked > limit) {
4685
+ const advice = threadAdvice(engine);
4686
+ if (!threadWarnings.has(advice)) {
4687
+ threadWarnings.add(advice);
4688
+ console.warn(`poker-flopsolve: ${asked} threads asked for, solving on ${limit} (${PLATFORM} build): ${advice}`);
2961
4689
  }
2962
- return 1;
4690
+ return limit;
2963
4691
  }
2964
4692
  return asked;
2965
4693
  }
@@ -2975,15 +4703,18 @@ function solve(spot, options = {}) {
2975
4703
  const iterations = options.iterations ?? 500;
2976
4704
  const target = options.targetPercent ?? 0;
2977
4705
  const fixed = options.exploitEvery ?? 0;
4706
+ const settle = options.settle ? settlePlan(options.settle) : null;
2978
4707
  const run = createRun(spot, options);
2979
4708
  const history = [];
2980
- const started = Date.now();
4709
+ const started = Date.now() - (coarseMs.get(run.solver) ?? 0);
4710
+ const before = coarseMs.has(run.solver) ? run.totalIterations : 0;
2981
4711
  try {
2982
4712
  return runAll();
2983
4713
  } finally {
2984
4714
  run.close();
2985
4715
  }
2986
4716
  function runAll() {
4717
+ if (settle) return runSettled(settle);
2987
4718
  if (fixed <= 0 && target <= 0) {
2988
4719
  run.step(iterations);
2989
4720
  return run.snapshot(history, "iterations");
@@ -3013,13 +4744,13 @@ function solve(spot, options = {}) {
3013
4744
  next = done + fixed;
3014
4745
  } else {
3015
4746
  const predicted = predictCrossing(
3016
- prevIteration,
4747
+ before + prevIteration,
3017
4748
  prevExploitability,
3018
- done,
4749
+ before + done,
3019
4750
  info.exploitability,
3020
4751
  target * spot.potUnits / (100 * spot.chipScale)
3021
4752
  );
3022
- const aim = predicted > 0 ? predicted * 0.95 : done * MAX_GROWTH;
4753
+ const aim = predicted > 0 ? predicted * 0.95 - before : done * MAX_GROWTH;
3023
4754
  const bounded = Math.min(Math.max(aim, done * MIN_GROWTH), done * MAX_GROWTH);
3024
4755
  next = Math.max(done + 1, Math.ceil(bounded));
3025
4756
  prevIteration = done;
@@ -3028,6 +4759,36 @@ function solve(spot, options = {}) {
3028
4759
  }
3029
4760
  return run.snapshot(history, stoppedAt);
3030
4761
  }
4762
+ function runSettled(plan) {
4763
+ const tracker = trackSettle(plan);
4764
+ let stoppedAt = "iterations";
4765
+ let done = 0;
4766
+ while (done < iterations) {
4767
+ const until = Math.min(done + plan.every, iterations);
4768
+ const full = until - done === plan.every;
4769
+ run.step(until - done);
4770
+ done = until;
4771
+ const measured = run.snapshot();
4772
+ const settled = full && tracker.check(measured, done);
4773
+ const info = {
4774
+ iteration: done,
4775
+ exploitability: target > 0 ? measured.exploitability() : Number.NaN,
4776
+ elapsedMs: Date.now() - started,
4777
+ movement: full ? tracker.movement : Number.NaN
4778
+ };
4779
+ history.push(info);
4780
+ options.onProgress?.(info);
4781
+ if (target > 0 && measured.exploitabilityPercent() <= target) {
4782
+ stoppedAt = "target";
4783
+ break;
4784
+ }
4785
+ if (settled) {
4786
+ stoppedAt = "settled";
4787
+ break;
4788
+ }
4789
+ }
4790
+ return run.snapshot(history, stoppedAt);
4791
+ }
3031
4792
  }
3032
4793
  var FIRST_CHECK = 10;
3033
4794
  var MIN_GROWTH = 1.1;
@@ -3039,7 +4800,7 @@ function predictCrossing(t1, e1, t2, e2, target) {
3039
4800
  const predicted = t2 * (e2 / target) ** (1 / p);
3040
4801
  return Number.isFinite(predicted) ? predicted : 0;
3041
4802
  }
3042
- function makeSolution(spot, ctx, solver, iterations, totalIterations, history, stoppedAt, workers) {
4803
+ function makeSolution(spot, solver, iterations, totalIterations, history, stoppedAt, workers, currentProfileEv) {
3043
4804
  const { tree } = spot;
3044
4805
  const parent = new Int32Array(tree.nodeCount).fill(-1);
3045
4806
  const viaEdge = new Int32Array(tree.nodeCount).fill(-1);
@@ -3050,10 +4811,16 @@ function makeSolution(spot, ctx, solver, iterations, totalIterations, history, s
3050
4811
  viaEdge[tree.edgeChild[edge]] = edge;
3051
4812
  }
3052
4813
  }
3053
- const label = (edge) => {
3054
- const kind = tree.edgeAction[edge];
3055
- const amount = tree.edgeTarget[edge] / spot.chipScale;
3056
- return kind >= ActionKind.Bet ? `${ACTION_LABELS[kind]} ${amount}` : ACTION_LABELS[kind];
4814
+ const label = (edge) => actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], spot.chipScale);
4815
+ const path = (node) => {
4816
+ const steps = [];
4817
+ let current = node;
4818
+ while (parent[current] >= 0) {
4819
+ const owner = parent[current];
4820
+ steps.push(tree.kind[owner] === NodeKind.Decision ? label(viaEdge[current]) : "/");
4821
+ current = owner;
4822
+ }
4823
+ return steps.reverse().join(" ") || "(root)";
3057
4824
  };
3058
4825
  const reachAt = (node, board, player) => {
3059
4826
  const index = spot.players[player];
@@ -3071,6 +4838,8 @@ function makeSolution(spot, ctx, solver, iterations, totalIterations, history, s
3071
4838
  return reach;
3072
4839
  };
3073
4840
  let cachedEv = null;
4841
+ const rootValues = () => cachedEv ??= solver.rootValues(currentProfileEv ? Mode.Current : Mode.Average);
4842
+ const cachedHands = [null, null];
3074
4843
  let cachedExploit = null;
3075
4844
  return {
3076
4845
  spot,
@@ -3081,8 +4850,11 @@ function makeSolution(spot, ctx, solver, iterations, totalIterations, history, s
3081
4850
  solver,
3082
4851
  history,
3083
4852
  ev(player) {
3084
- cachedEv ??= solver.expectedValue();
3085
- return cachedEv[player];
4853
+ return rootValues().totals[player];
4854
+ },
4855
+ handEvs(player) {
4856
+ cachedHands[player] ??= solver.handEvs(player, rootValues().values[player]);
4857
+ return cachedHands[player].slice();
3086
4858
  },
3087
4859
  exploitability() {
3088
4860
  cachedExploit ??= solver.exploitability();
@@ -3100,16 +4872,7 @@ function makeSolution(spot, ctx, solver, iterations, totalIterations, history, s
3100
4872
  for (let a = 0; a < actions; a++) names.push(label(tree.firstEdge[node] + a));
3101
4873
  return { node, board, player: owner, actions: names, combos: spot.players[owner].combos, probs };
3102
4874
  },
3103
- path(node) {
3104
- const steps = [];
3105
- let current = node;
3106
- while (parent[current] >= 0) {
3107
- const owner = parent[current];
3108
- steps.push(tree.kind[owner] === NodeKind.Decision ? label(viaEdge[current]) : "/");
3109
- current = owner;
3110
- }
3111
- return steps.reverse().join(" ") || "(root)";
3112
- },
4875
+ path,
3113
4876
  reachAt,
3114
4877
  subgameAt(node, board, betting = {}) {
3115
4878
  const opensRound = node === 0 || parent[node] >= 0 && tree.kind[parent[node]] === NodeKind.Chance;
@@ -3127,7 +4890,20 @@ function makeSolution(spot, ctx, solver, iterations, totalIterations, history, s
3127
4890
  const later = (value, listed) => listed && value.length > 1 ? value.slice(round) : value;
3128
4891
  const laterEach = (value, listed) => value === void 0 ? void 0 : mapPlayers(value, (side) => later(side, listed(side)));
3129
4892
  const rows = laterEach(source.betSizes, () => true);
3130
- const raiseRows = laterEach(source.raiseSizes, (side) => side !== void 0 && raisesPerRound(side));
4893
+ const raiseRows2 = laterEach(source.raiseSizes, (side) => side !== void 0 && raisesPerRound(side));
4894
+ const keeps = (key) => key === "thinSizes" ? !betting.thinSizes : betting[key] === void 0 && ["betSizes", "maxRaises", "allowAllIn"].includes(key);
4895
+ const reshaped = TREE_SETTINGS.some((key) => key in betting && !keeps(key));
4896
+ const prefix = node === 0 ? "" : `${path(node)} `;
4897
+ const rebase = (step) => {
4898
+ const [label2, chips] = step.split(" ");
4899
+ return chips === void 0 ? step : `${label2} ${(Math.round(Number(chips) * spot.chipScale) - invested) / spot.chipScale}`;
4900
+ };
4901
+ const cuts = source.removeActions?.filter((line) => line.startsWith(prefix)).map((line) => line.slice(prefix.length).split(" ").reduce((steps, word, i, words) => {
4902
+ if (/^-?[\d.]+$/.test(word)) steps[steps.length - 1] = rebase(`${words[i - 1]} ${word}`);
4903
+ else steps.push(word);
4904
+ return steps;
4905
+ }, []).join(" "));
4906
+ const removeActions = "removeActions" in betting ? betting.removeActions : reshaped || !cuts || cuts.length === 0 ? void 0 : cuts;
3131
4907
  return {
3132
4908
  board: formatCards(cards),
3133
4909
  pot: tree.pot[node] / spot.chipScale,
@@ -3135,17 +4911,21 @@ function makeSolution(spot, ctx, solver, iterations, totalIterations, history, s
3135
4911
  oop: reachAt(node, board, 0),
3136
4912
  ip: reachAt(node, board, 1),
3137
4913
  betSizes: betting.betSizes ?? rows,
3138
- raiseSizes: "raiseSizes" in betting ? betting.raiseSizes : raiseRows,
4914
+ raiseSizes: "raiseSizes" in betting ? betting.raiseSizes : raiseRows2,
3139
4915
  maxRaises: betting.maxRaises ?? laterEach(source.maxRaises, Array.isArray),
3140
4916
  allowAllIn: betting.allowAllIn ?? laterEach(source.allowAllIn, Array.isArray),
3141
4917
  allInThreshold: "allInThreshold" in betting ? betting.allInThreshold : laterEach(source.allInThreshold, Array.isArray),
3142
4918
  noDonk: "noDonk" in betting ? betting.noDonk : source.noDonk === void 0 ? void 0 : later(source.noDonk, Array.isArray(source.noDonk)),
3143
4919
  mergeSizes: "mergeSizes" in betting ? betting.mergeSizes : source.mergeSizes,
4920
+ ...removeActions ? { removeActions } : {},
4921
+ // The thinned shape is the whole tree's, so a subgame starts full.
4922
+ ...betting.thinSizes ? { thinSizes: true } : {},
3144
4923
  minWeight: source.minWeight,
3145
4924
  isomorphism: source.isomorphism,
3146
4925
  maxCombos: "maxCombos" in betting ? betting.maxCombos : source.maxCombos,
3147
4926
  maxBytes: "maxBytes" in betting ? betting.maxBytes : source.maxBytes,
3148
- chipScale: spot.chipScale
4927
+ chipScale: spot.chipScale,
4928
+ compactStorage: source.compactStorage
3149
4929
  };
3150
4930
  }
3151
4931
  };
@@ -3166,8 +4946,10 @@ export {
3166
4946
  SUITS,
3167
4947
  SpotTooLargeError,
3168
4948
  activeCombos,
4949
+ bettingFrom,
3169
4950
  cardOf,
3170
4951
  categoryOf,
4952
+ checkedDown,
3171
4953
  comboIndex,
3172
4954
  createRun,
3173
4955
  defineSpot,
@@ -3176,6 +4958,10 @@ export {
3176
4958
  formatCard,
3177
4959
  formatCards,
3178
4960
  formatCombo,
4961
+ keepWithin,
4962
+ linesWithin,
4963
+ liteConfig,
4964
+ litePreset,
3179
4965
  makeRegretStore,
3180
4966
  makeSumStore,
3181
4967
  parseCard,
@@ -3184,9 +4970,18 @@ export {
3184
4970
  predictCrossing,
3185
4971
  rangeWeight,
3186
4972
  rankOf,
4973
+ rankSwap,
4974
+ resolveSubgame,
4975
+ rootPlay,
4976
+ rootPlayMovement,
4977
+ rootPlayNodes,
3187
4978
  simdAvailable,
3188
4979
  solve,
4980
+ solveLite,
4981
+ storageCost,
3189
4982
  suitLanes,
3190
- suitOf
4983
+ suitOf,
4984
+ trackSettle,
4985
+ turnLineReach
3191
4986
  };
3192
4987
  //# sourceMappingURL=browser.js.map