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/worker.js CHANGED
@@ -31,12 +31,12 @@ function parseCard(name) {
31
31
  return cardOf(rank, suit);
32
32
  }
33
33
  function parseCards(text) {
34
- const compact = text.replace(/[\s,]+/g, "");
35
- if (compact.length % 2 !== 0) throw new Error(`"${text}" is not a whole number of cards`);
34
+ const compact2 = text.replace(/[\s,]+/g, "");
35
+ if (compact2.length % 2 !== 0) throw new Error(`"${text}" is not a whole number of cards`);
36
36
  const cards = [];
37
37
  const seen = /* @__PURE__ */ new Set();
38
- for (let i = 0; i < compact.length; i += 2) {
39
- const card = parseCard(compact.slice(i, i + 2));
38
+ for (let i = 0; i < compact2.length; i += 2) {
39
+ const card = parseCard(compact2.slice(i, i + 2));
40
40
  if (seen.has(card)) throw new Error(`"${formatCard(card)}" appears twice in "${text}"`);
41
41
  seen.add(card);
42
42
  cards.push(card);
@@ -260,6 +260,13 @@ function buildShowdownTable(runouts, relevant2) {
260
260
  }
261
261
 
262
262
  // src/hands.ts
263
+ function markMembers(lists, from, count, indexOf, clear) {
264
+ for (let i = 0; i < count; i++) {
265
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
266
+ indexOf[lists.memberCombo[m]] = clear ? -1 : i;
267
+ }
268
+ }
269
+ }
263
270
  function span(lists, round, board, player) {
264
271
  const slot = (lists.roundBase[round] + board) * 2 + player;
265
272
  return [lists.start[slot], lists.count[slot]];
@@ -276,7 +283,7 @@ function buildHandSpace(runouts, players, lists) {
276
283
  const parent = runouts.parent[round][child];
277
284
  for (let player = 0; player < 2; player++) {
278
285
  const [parentFrom, parentCount] = span(lists, round - 1, parent, player);
279
- for (let i = 0; i < parentCount; i++) indexOf[lists.list[parentFrom + i]] = i;
286
+ markMembers(lists, parentFrom, parentCount, indexOf, false);
280
287
  const [childFrom, childCount] = span(lists, round, child, player);
281
288
  for (let m = orbitStart[child]; m < orbitStart[child + 1]; m++) {
282
289
  const back = runouts.maps.combo[runouts.maps.inverse(runouts.orbitMap[round][m])];
@@ -288,7 +295,7 @@ function buildHandSpace(runouts, players, lists) {
288
295
  up.push(at);
289
296
  }
290
297
  }
291
- for (let i = 0; i < parentCount; i++) indexOf[lists.list[parentFrom + i]] = -1;
298
+ markMembers(lists, parentFrom, parentCount, indexOf, true);
292
299
  }
293
300
  }
294
301
  upStart.push(starts);
@@ -301,11 +308,11 @@ function buildHandSpace(runouts, players, lists) {
301
308
  for (let player = 0; player < 2; player++) {
302
309
  const slot = (lists.roundBase[round] + board) * 2 + player;
303
310
  const [otherFrom, otherCount] = span(lists, round, board, 1 - player);
304
- for (let j = 0; j < otherCount; j++) indexOf[lists.list[otherFrom + j]] = j;
311
+ markMembers(lists, otherFrom, otherCount, indexOf, false);
305
312
  const [from, count] = span(lists, round, board, player);
306
313
  sameStart[slot] = same.length;
307
314
  for (let i = 0; i < count; i++) same.push(indexOf[lists.list[from + i]]);
308
- for (let j = 0; j < otherCount; j++) indexOf[lists.list[otherFrom + j]] = -1;
315
+ markMembers(lists, otherFrom, otherCount, indexOf, true);
309
316
  }
310
317
  }
311
318
  }
@@ -357,6 +364,48 @@ function showdownValuesHands(oppReach, cardA, cardB, strength, oppFrom, oppCount
357
364
  }
358
365
  sums.fill(0, 0, DECK);
359
366
  }
367
+ function addMembers(reach, entry, memberStart, memberA, memberB, sums) {
368
+ const to = memberStart[entry + 1];
369
+ for (let m = memberStart[entry]; m < to; m++) {
370
+ sums[memberA[m]] += reach;
371
+ sums[memberB[m]] += reach;
372
+ }
373
+ return reach * (to - memberStart[entry]);
374
+ }
375
+ function foldValuesPacked(oppReach, cardA, cardB, memberStart, memberA, memberB, oppFrom, oppCount, myFrom, myCount, same, sameFrom, payoff, sums, out) {
376
+ let total = 0;
377
+ for (let j = 0; j < oppCount; j++) total += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);
378
+ for (let i = 0; i < myCount; i++) {
379
+ const twin = same[sameFrom + i];
380
+ const both = twin >= 0 ? oppReach[twin] : 0;
381
+ out[i] = payoff * (total - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]] - both));
382
+ }
383
+ sums.fill(0, 0, DECK);
384
+ }
385
+ function showdownValuesPacked(oppReach, cardA, cardB, memberStart, memberA, memberB, strength, oppFrom, oppCount, myFrom, myCount, payoff, sums, out) {
386
+ let running = 0;
387
+ let j = 0;
388
+ for (let i = 0; i < myCount; i++) {
389
+ const level = strength[myFrom + i];
390
+ while (j < oppCount && strength[oppFrom + j] < level) {
391
+ running += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);
392
+ j++;
393
+ }
394
+ out[i] = running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]]);
395
+ }
396
+ sums.fill(0, 0, DECK);
397
+ running = 0;
398
+ j = oppCount - 1;
399
+ for (let i = myCount - 1; i >= 0; i--) {
400
+ const level = strength[myFrom + i];
401
+ while (j >= 0 && strength[oppFrom + j] > level) {
402
+ running += addMembers(oppReach[j], oppFrom + j, memberStart, memberA, memberB, sums);
403
+ j--;
404
+ }
405
+ out[i] = payoff * (out[i] - (running - (sums[cardA[myFrom + i]] + sums[cardB[myFrom + i]])));
406
+ }
407
+ sums.fill(0, 0, DECK);
408
+ }
360
409
 
361
410
  // src/tree.ts
362
411
  function isPerPlayer(value) {
@@ -393,6 +442,7 @@ var ActionKind = {
393
442
  Raise: 4,
394
443
  AllIn: 5
395
444
  };
445
+ var ACTION_LABELS = ["fold", "check", "call", "bet", "raise", "allin"];
396
446
  function mergeBetSizes(sizes, distance) {
397
447
  if (!(distance > 0)) return [...sizes];
398
448
  const fractions = sizes.filter((size) => typeof size === "number").sort((a, b) => a - b);
@@ -411,6 +461,10 @@ function mergeBetSizes(sizes, distance) {
411
461
  flush();
412
462
  return [...merged, ...others];
413
463
  }
464
+ function actionLabel(action, target, chipScale) {
465
+ return action >= ActionKind.Bet ? `${ACTION_LABELS[action]} ${target / chipScale}` : ACTION_LABELS[action];
466
+ }
467
+ var THIN_BASE = 0.75;
414
468
  function buildTree(config2, runouts) {
415
469
  const kind = [];
416
470
  const player = [];
@@ -445,6 +499,27 @@ function buildTree(config2, runouts) {
445
499
  });
446
500
  const noDonk = perRound(config2.noDonk ?? false, Array.isArray(config2.noDonk), rounds, "noDonk");
447
501
  const half = Math.round(potUnits / 2);
502
+ const remove = config2.removeActions && config2.removeActions.length > 0 ? new Set(config2.removeActions) : null;
503
+ const removed = /* @__PURE__ */ new Set();
504
+ const extend = (path, step) => remove ? path ? `${path} ${step}` : step : "";
505
+ const thin = config2.thinSizes === true;
506
+ const thinned = (sized, state) => {
507
+ if (state.round === 0 && state.aggressions === 0 && state.acted === 0) return sized;
508
+ const me = state.toAct;
509
+ const mine = state.invested[me];
510
+ const owed = Math.max(0, state.invested[1 - me] - mine);
511
+ const potAfterCall = potUnits + state.invested[0] + state.invested[1] + owed;
512
+ const fraction = (target) => (target - mine - owed) / potAfterCall;
513
+ let nearest = -1;
514
+ sized.forEach((entry, i) => {
515
+ const distance = Math.abs(fraction(entry.target) - THIN_BASE);
516
+ if (nearest < 0 || distance < Math.abs(fraction(sized[nearest].target) - THIN_BASE)) nearest = i;
517
+ });
518
+ const big = rounds > 1 && state.round === rounds - 1 && owed === 0 && state.streetsBet > 0;
519
+ return sized.filter(
520
+ (entry, i) => i === nearest || big && (entry.action === ActionKind.AllIn || fraction(entry.target) > 1)
521
+ );
522
+ };
448
523
  const addNode = (nodeKind, nodePlayer, nodeRound, nodePot, nodePayoff) => {
449
524
  kind.push(nodeKind);
450
525
  player.push(nodePlayer);
@@ -455,7 +530,7 @@ function buildTree(config2, runouts) {
455
530
  payoff.push(nodePayoff);
456
531
  return kind.length - 1;
457
532
  };
458
- const closeRound = (state) => {
533
+ const closeRound = (state, path) => {
459
534
  const total = potUnits + state.invested[0] + state.invested[1];
460
535
  const allIn = state.invested[0] >= stackUnits || state.invested[1] >= stackUnits;
461
536
  if (state.round + 1 >= runouts.rounds) {
@@ -471,9 +546,10 @@ function buildTree(config2, runouts) {
471
546
  acted: 0,
472
547
  base: state.invested[0],
473
548
  aggressor: -1,
474
- previousAggressor: state.aggressor
549
+ previousAggressor: state.aggressor,
550
+ streetsBet: state.streetsBet + (state.aggressions > 0 ? 1 : 0)
475
551
  };
476
- const child = allIn ? closeRound(next) : buildDecision(next);
552
+ const child = allIn ? closeRound(next, extend(path, "/")) : buildDecision(next, extend(path, "/"));
477
553
  firstEdge[node] = edgeChild.length;
478
554
  numEdges[node] = 1;
479
555
  edgeAction.push(ActionKind.Check);
@@ -497,14 +573,10 @@ function buildTree(config2, runouts) {
497
573
  if (target <= theirs) return null;
498
574
  const raiseSize = target - theirs;
499
575
  const minimum = Math.max(state.lastRaise, minRaiseUnits);
500
- if (raiseSize < minimum) {
501
- const bumped = theirs + minimum;
502
- if (bumped > cap) return null;
503
- target = bumped;
504
- }
576
+ if (raiseSize < minimum) target = Math.min(theirs + minimum, cap);
505
577
  return target;
506
578
  };
507
- const buildDecision = (state) => {
579
+ const buildDecision = (state, path) => {
508
580
  const me = state.toAct;
509
581
  const opp = 1 - me;
510
582
  const mine = state.invested[me];
@@ -523,6 +595,7 @@ function buildTree(config2, runouts) {
523
595
  const donk = noDonk[state.round] && me === 0 && owed === 0 && state.aggressions === 0 && state.previousAggressor === 1;
524
596
  if (state.aggressions < maxRaises[me][state.round] && myRemaining > owed && !donk) {
525
597
  const seen = /* @__PURE__ */ new Set();
598
+ const sized = [];
526
599
  const myRaises = raiseSizes[me];
527
600
  const sizes = owed > 0 && myRaises ? [...myRaises[state.round]] : [...betSizes[me][state.round] ?? []].filter((size) => !(typeof size === "object" && "times" in size));
528
601
  if (allowAllIn[me][state.round]) sizes.push("allin");
@@ -534,10 +607,17 @@ function buildTree(config2, runouts) {
534
607
  if (target === null || seen.has(target)) continue;
535
608
  seen.add(target);
536
609
  const isShove = target >= stackUnits;
537
- actions.push({
538
- action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet,
539
- target
540
- });
610
+ sized.push({ action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet, target });
611
+ }
612
+ for (const entry of thin ? thinned(sized, state) : sized) {
613
+ if (remove) {
614
+ const line = extend(path, actionLabel(entry.action, entry.target, chipScale));
615
+ if (remove.has(line)) {
616
+ removed.add(line);
617
+ continue;
618
+ }
619
+ }
620
+ actions.push(entry);
541
621
  }
542
622
  }
543
623
  const base = edgeChild.length;
@@ -549,6 +629,7 @@ function buildTree(config2, runouts) {
549
629
  edgeChild.push(-1);
550
630
  }
551
631
  actions.forEach((entry, i) => {
632
+ const line = remove ? extend(path, actionLabel(entry.action, entry.target, chipScale)) : "";
552
633
  const invested = me === 0 ? [entry.target, theirs] : [theirs, entry.target];
553
634
  let child;
554
635
  if (entry.action === ActionKind.Fold) {
@@ -556,7 +637,7 @@ function buildTree(config2, runouts) {
556
637
  child = addNode(NodeKind.TerminalFold, -1, state.round, total, value);
557
638
  } else if (entry.action === ActionKind.Check || entry.action === ActionKind.Call) {
558
639
  const closed = invested[0] === invested[1] && state.acted + 1 >= 2;
559
- child = closed ? closeRound({ ...state, invested, acted: state.acted + 1 }) : buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 });
640
+ child = closed ? closeRound({ ...state, invested, acted: state.acted + 1 }, line) : buildDecision({ ...state, invested, toAct: opp, acted: state.acted + 1 }, line);
560
641
  } else {
561
642
  child = buildDecision({
562
643
  round: state.round,
@@ -567,8 +648,9 @@ function buildTree(config2, runouts) {
567
648
  acted: state.acted + 1,
568
649
  base: state.base,
569
650
  aggressor: me,
570
- previousAggressor: state.previousAggressor
571
- });
651
+ previousAggressor: state.previousAggressor,
652
+ streetsBet: state.streetsBet
653
+ }, line);
572
654
  }
573
655
  edgeChild[base + i] = child;
574
656
  });
@@ -583,8 +665,16 @@ function buildTree(config2, runouts) {
583
665
  acted: 0,
584
666
  base: 0,
585
667
  aggressor: -1,
586
- previousAggressor: -1
587
- });
668
+ previousAggressor: -1,
669
+ streetsBet: 0
670
+ }, "");
671
+ if (remove && removed.size < remove.size) {
672
+ const under = (line) => [...removed].some((cut) => line.startsWith(`${cut} `));
673
+ const missing = [...remove].filter((line) => !removed.has(line) && !under(line));
674
+ if (missing.length > 0) throw new Error(
675
+ `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`
676
+ );
677
+ }
588
678
  const decisionNodes = [];
589
679
  for (let i = 0; i < kind.length; i++) if (kind[i] === NodeKind.Decision) decisionNodes.push(i);
590
680
  return {
@@ -634,19 +724,20 @@ function makeBuffers(ctx2, width) {
634
724
  hands: make(() => new Uint16Array(width)),
635
725
  strategy: make(() => new Float64Array(actions * COMBOS)),
636
726
  rank: new Int32Array(COMBOS),
637
- position: new Int32Array(COMBOS)
727
+ position: new Int32Array(COMBOS).fill(-1),
728
+ at: make(() => new Int32Array(width))
638
729
  };
639
730
  }
640
- function pairValues(ctx2, node, board, traverser, hands, handReach, live, liveCount) {
641
- const result = new Float64Array(hands.length * COMBOS);
642
- if (hands.length === 0) return result;
643
- const width = Math.min(CHUNK, hands.length);
731
+ function pairValues(ctx2, node, board, traverser, hands2, handReach, live, liveCount) {
732
+ const result = new Float64Array(hands2.length * COMBOS);
733
+ if (hands2.length === 0) return result;
734
+ const width = Math.min(CHUNK, hands2.length);
644
735
  const buffers = makeBuffers(ctx2, width);
645
736
  const mine = new Uint16Array(liveCount);
646
737
  let mineCount = 0;
647
738
  for (let i = 0; i < liveCount; i++) if (ctx2.players[traverser].slot[live[i]] >= 0) mine[mineCount++] = live[i];
648
- for (let start = 0; start < hands.length; start += width) {
649
- const chunk = hands.subarray(start, Math.min(hands.length, start + width));
739
+ for (let start = 0; start < hands2.length; start += width) {
740
+ const chunk = hands2.subarray(start, Math.min(hands2.length, start + width));
650
741
  const colReach = buffers.colReach[0];
651
742
  const cols = buffers.cols[0];
652
743
  let count = 0;
@@ -663,7 +754,7 @@ function pairValues(ctx2, node, board, traverser, hands, handReach, live, liveCo
663
754
  }
664
755
  return result;
665
756
  }
666
- function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colCount, live, liveCount, depth) {
757
+ function walk(ctx2, buffers, traverser, hands2, node, board, colReach, cols, colCount, live, liveCount, depth) {
667
758
  const { tree, runouts } = ctx2;
668
759
  const out = buffers.value[depth];
669
760
  const kind = tree.kind[node];
@@ -678,8 +769,8 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
678
769
  const weight = signed * ctx2.runoutWeight[tree.round[node]] / ctx2.chipScale;
679
770
  for (let c = 0; c < colCount; c++) {
680
771
  const k = cols[c];
681
- const a = cards[hands[k] * 2];
682
- const b = cards[hands[k] * 2 + 1];
772
+ const a = cards[hands2[k] * 2];
773
+ const b = cards[hands2[k] * 2 + 1];
683
774
  const v = weight * colReach[k];
684
775
  const row = k * COMBOS;
685
776
  for (let i = 0; i < liveCount; i++) {
@@ -704,7 +795,7 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
704
795
  }
705
796
  for (let c = 0; c < colCount; c++) {
706
797
  const k = cols[c];
707
- const theirs = hands[k];
798
+ const theirs = hands2[k];
708
799
  const a = cards[theirs * 2];
709
800
  const b = cards[theirs * 2 + 1];
710
801
  const strength = rank[theirs];
@@ -731,28 +822,31 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
731
822
  const childLive = buffers.live[depth];
732
823
  const childCols2 = buffers.cols[depth + 1];
733
824
  const mappedHands = buffers.hands[depth];
734
- for (let childBoard = runouts.childStart[nextRound][board]; childBoard < runouts.childStart[nextRound][board + 1]; childBoard++) {
825
+ const starts = runouts.childStart[nextRound];
826
+ for (let childBoard = starts[board]; childBoard < starts[board + 1]; childBoard++) {
827
+ const stored = dealtCards[childBoard * width + width - 1];
735
828
  for (let m = orbitStart[childBoard]; m < orbitStart[childBoard + 1]; m++) {
736
- const dealt = m === orbitStart[childBoard] ? dealtCards[childBoard * width + width - 1] : runouts.orbitCard[nextRound][m];
829
+ const dealt = m === orbitStart[childBoard] ? stored : runouts.orbitCard[nextRound][m];
737
830
  const map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];
831
+ const blocked = (combo) => cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt;
738
832
  let childCount = 0;
739
833
  for (let i = 0; i < liveCount; i++) {
740
834
  const combo = live[i];
741
- if (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;
835
+ if (blocked(combo)) continue;
742
836
  childLive[childCount++] = map[combo];
743
837
  }
744
838
  let childColCount = 0;
745
839
  for (let c = 0; c < colCount; c++) {
746
840
  const k = cols[c];
747
- if (cards[hands[k] * 2] !== dealt && cards[hands[k] * 2 + 1] !== dealt) childCols2[childColCount++] = k;
841
+ if (!blocked(hands2[k])) childCols2[childColCount++] = k;
748
842
  }
749
843
  if (childColCount === 0) continue;
750
- for (let k = 0; k < hands.length; k++) mappedHands[k] = map[hands[k]];
844
+ for (let k = 0; k < hands2.length; k++) mappedHands[k] = map[hands2[k]];
751
845
  const value = walk(
752
846
  ctx2,
753
847
  buffers,
754
848
  traverser,
755
- mappedHands.subarray(0, hands.length),
849
+ mappedHands.subarray(0, hands2.length),
756
850
  child,
757
851
  childBoard,
758
852
  colReach,
@@ -766,7 +860,7 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
766
860
  const row = childCols2[c] * COMBOS;
767
861
  for (let i = 0; i < liveCount; i++) {
768
862
  const combo = live[i];
769
- if (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;
863
+ if (blocked(combo)) continue;
770
864
  out[row + combo] += value[row + map[combo]];
771
865
  }
772
866
  }
@@ -779,21 +873,19 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
779
873
  const owner = tree.player[node];
780
874
  const lists = ctx2.active;
781
875
  const listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;
782
- const active2 = lists.list;
783
876
  const activeFrom = lists.start[listSlot];
784
877
  const activeCount = lists.count[listSlot];
785
878
  const stride = activeCount;
786
879
  const slotBase = ctx2.layout.offset[node] + actions * ctx2.layout.rowStart[listSlot];
787
880
  const strategy = buffers.strategy[depth];
788
- averageStrategy(ctx2.strategySum, slotBase, actions, stride, strategy, ctx2.regret);
881
+ storedStrategy(ctx2, node, slotBase, actions, stride, strategy);
789
882
  if (owner === traverser) {
790
883
  for (let a = 0; a < actions; a++) {
791
- const offset = a * COMBOS;
792
884
  const value = walk(
793
885
  ctx2,
794
886
  buffers,
795
887
  traverser,
796
- hands,
888
+ hands2,
797
889
  tree.edgeChild[edgeBase + a],
798
890
  board,
799
891
  colReach,
@@ -806,8 +898,11 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
806
898
  for (let c = 0; c < colCount; c++) {
807
899
  const row = cols[c] * COMBOS;
808
900
  for (let i = 0; i < activeCount; i++) {
809
- const combo = active2[activeFrom + i];
810
- out[row + combo] += strategy[a * stride + i] * value[row + combo];
901
+ const share = strategy[a * stride + i];
902
+ for (let m = lists.memberStart[activeFrom + i]; m < lists.memberStart[activeFrom + i + 1]; m++) {
903
+ const combo = lists.memberCombo[m];
904
+ out[row + combo] += share * value[row + combo];
905
+ }
811
906
  }
812
907
  }
813
908
  }
@@ -816,13 +911,15 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
816
911
  const childReach = buffers.colReach[depth + 1];
817
912
  const childCols = buffers.cols[depth + 1];
818
913
  const position = buffers.position;
819
- for (let i = 0; i < activeCount; i++) position[active2[activeFrom + i]] = i;
914
+ markMembers(lists, activeFrom, activeCount, position, false);
915
+ const at = buffers.at[depth];
916
+ for (let c = 0; c < colCount; c++) at[cols[c]] = position[hands2[cols[c]]];
917
+ markMembers(lists, activeFrom, activeCount, position, true);
820
918
  for (let a = 0; a < actions; a++) {
821
- const offset = a * COMBOS;
822
919
  let childCount = 0;
823
920
  for (let c = 0; c < colCount; c++) {
824
921
  const k = cols[c];
825
- const r = colReach[k] * strategy[a * stride + position[hands[k]]];
922
+ const r = at[k] < 0 ? 0 : colReach[k] * strategy[a * stride + at[k]];
826
923
  childReach[k] = r;
827
924
  if (r !== 0) childCols[childCount++] = k;
828
925
  }
@@ -831,7 +928,7 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
831
928
  ctx2,
832
929
  buffers,
833
930
  traverser,
834
- hands,
931
+ hands2,
835
932
  tree.edgeChild[edgeBase + a],
836
933
  board,
837
934
  childReach,
@@ -911,58 +1008,243 @@ function buildPlayerIndex(weights2) {
911
1008
  }
912
1009
  return { combos: Uint16Array.from(combos), count: combos.length, slot, weights: weights2 };
913
1010
  }
914
- function buildLayout(tree, runouts, players, bytesPerElement) {
1011
+ function orbitLeader(runouts, round, board, combo) {
1012
+ const from = runouts.stabiliserStart[round][board];
1013
+ const to = runouts.stabiliserStart[round][board + 1];
1014
+ for (let k = from + 1; k < to; k++) {
1015
+ if (runouts.maps.combo[runouts.stabiliserMap[round][k]][combo] < combo) return false;
1016
+ }
1017
+ return true;
1018
+ }
1019
+ var INT32_MAX = 2 ** 31 - 1;
1020
+ function buildLayout(tree, runouts, players, bytesPerElement, alias, compact2) {
915
1021
  const roundBase = new Int32Array(runouts.rounds + 1);
916
1022
  for (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];
917
1023
  const rowStart = new Int32Array(roundBase[runouts.rounds] * 2);
918
1024
  const totals = new Int32Array(runouts.rounds * 2);
919
1025
  const onBoard = new Uint8Array(DECK);
920
1026
  for (let round = 0; round < runouts.rounds; round++) {
921
- const width = runouts.width[round];
1027
+ const width2 = runouts.width[round];
922
1028
  const cards = runouts.cards[round];
923
1029
  for (let board = 0; board < runouts.counts[round]; board++) {
924
1030
  onBoard.fill(0);
925
- for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1031
+ for (let i = 0; i < width2; i++) onBoard[cards[board * width2 + i]] = 1;
926
1032
  for (let player = 0; player < 2; player++) {
927
1033
  const index = players[player];
928
1034
  let live = 0;
929
1035
  for (let i = 0; i < index.count; i++) {
930
1036
  const combo = index.combos[i];
931
- if (!onBoard[COMBO_CARDS[combo * 2]] && !onBoard[COMBO_CARDS[combo * 2 + 1]]) live++;
1037
+ if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1038
+ if (!orbitLeader(runouts, round, board, combo)) continue;
1039
+ live++;
932
1040
  }
933
1041
  rowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];
934
1042
  totals[round * 2 + player] += live;
935
1043
  }
936
1044
  }
937
1045
  }
938
- const offset = new Int32Array(tree.nodeCount).fill(-1);
1046
+ const offset = new Float64Array(tree.nodeCount).fill(-1);
939
1047
  const blockOffset = new Int32Array(tree.nodeCount).fill(-1);
1048
+ const compactFrom = compact2 ? compact2.from : runouts.rounds;
1049
+ const handOffset = compact2 ? new Float64Array(tree.nodeCount).fill(-1) : null;
1050
+ const compactChunk = compact2 ? new Int32Array(tree.nodeCount).fill(-1) : null;
1051
+ const chunkSlots = [];
1052
+ const chunkHands = [];
1053
+ const chunkStart = [];
1054
+ const width = compact2?.float ? 4 : 1;
940
1055
  let total = 0;
1056
+ let compactSlots = 0;
1057
+ let compactHands = 0;
941
1058
  let blocks = 0;
942
1059
  let maxActions = 0;
1060
+ let shared = false;
1061
+ let walked = 0;
943
1062
  for (let i = 0; i < tree.decisionNodes.length; i++) {
944
1063
  const node = tree.decisionNodes[i];
945
1064
  const actions = tree.numEdges[node];
946
1065
  if (actions > maxActions) maxActions = actions;
947
- offset[node] = total;
1066
+ const hands2 = totals[tree.round[node] * 2 + tree.player[node]];
1067
+ walked += actions * hands2;
1068
+ if (alias !== void 0 && alias[node] !== node) {
1069
+ const owner = alias[node];
1070
+ if (owner > node) throw new Error("buildLayout: a storage owner must come before the nodes it owns");
1071
+ offset[node] = offset[owner];
1072
+ blockOffset[node] = blockOffset[owner];
1073
+ if (compact2) {
1074
+ handOffset[node] = handOffset[owner];
1075
+ compactChunk[node] = compactChunk[owner];
1076
+ }
1077
+ shared = true;
1078
+ continue;
1079
+ }
948
1080
  blockOffset[node] = blocks;
949
- total += actions * totals[tree.round[node] * 2 + tree.player[node]];
950
1081
  blocks += runouts.counts[tree.round[node]];
1082
+ if (tree.round[node] >= compactFrom) {
1083
+ const slots = actions * hands2;
1084
+ let chunk = chunkSlots.length - 1;
1085
+ if (slots * width > compact2.chunkBytes) {
1086
+ throw new Error(
1087
+ `compactStorage.chunkBytes is ${compact2.chunkBytes}, but one decision needs ${slots * width} bytes`
1088
+ );
1089
+ }
1090
+ if (chunk < 0 || (chunkSlots[chunk] + slots) * width > compact2.chunkBytes || chunkHands[chunk] + hands2 > compact2.chunkBytes) {
1091
+ chunk++;
1092
+ chunkSlots.push(0);
1093
+ chunkHands.push(0);
1094
+ chunkStart.push(compactSlots);
1095
+ }
1096
+ compactChunk[node] = chunk;
1097
+ offset[node] = chunkSlots[chunk];
1098
+ handOffset[node] = chunkHands[chunk];
1099
+ chunkSlots[chunk] += slots;
1100
+ chunkHands[chunk] += hands2;
1101
+ compactSlots += slots;
1102
+ compactHands += hands2;
1103
+ } else {
1104
+ offset[node] = total;
1105
+ total += actions * hands2;
1106
+ }
951
1107
  }
952
1108
  const scales = bytesPerElement === 2 ? blocks * 8 * 2 : 0;
1109
+ const compactBytes = !compact2 ? 0 : compact2.float ? compactSlots * 4 : (compactSlots + (compact2.perHand ? compactHands : blocks * 8)) * (compact2.sums ? 2 : 1);
953
1110
  return {
954
- offset,
1111
+ offset: Math.max(total, ...chunkSlots) <= INT32_MAX ? Int32Array.from(offset) : offset,
955
1112
  blockOffset,
956
1113
  blocks,
957
1114
  totalSlots: total,
1115
+ walkedSlots: walked,
958
1116
  maxActions,
959
1117
  rowStart,
960
1118
  roundBase,
961
- bytes: total * bytesPerElement * 2 + scales
1119
+ bytes: total * bytesPerElement * 2 + scales + compactBytes,
1120
+ shared,
1121
+ reachWeighted: shared ? sharedNodes(tree, alias) : null,
1122
+ compactFrom,
1123
+ compactSlots,
1124
+ handOffset,
1125
+ compactHands,
1126
+ compactChunk,
1127
+ chunkSlots,
1128
+ chunkHands,
1129
+ chunkStart
962
1130
  };
963
1131
  }
1132
+ function sharedNodes(tree, alias) {
1133
+ const marks = new Uint8Array(tree.nodeCount);
1134
+ for (let node = 0; node < tree.nodeCount; node++) {
1135
+ if (alias[node] !== node) marks[node] = marks[alias[node]] = 1;
1136
+ }
1137
+ return marks;
1138
+ }
964
1139
  var REGRET_STEPS = 32767;
965
1140
  var SUM_STEPS = 65535;
1141
+ function sampledRounds(options, rounds) {
1142
+ const asked = options.rounds ?? Array.from({ length: rounds }, (_, r) => r);
1143
+ return asked.filter((r) => r > 0 && r < rounds);
1144
+ }
1145
+ function planSampling(tree, runouts, active2, layout2, options) {
1146
+ const rounds = new Uint8Array(runouts.rounds);
1147
+ for (const r of sampledRounds(options, runouts.rounds)) rounds[r] = 1;
1148
+ const boardOffset = new Int32Array(active2.roundBase[runouts.rounds] * 2);
1149
+ const perNode = new Float64Array(runouts.rounds);
1150
+ for (let r = 1; r < runouts.rounds; r++) {
1151
+ if (!rounds[r]) continue;
1152
+ let total = 0;
1153
+ for (let b = 0; b < runouts.counts[r]; b++) {
1154
+ for (let p2 = 0; p2 < 2; p2++) {
1155
+ const slot = (active2.roundBase[r] + b) * 2 + p2;
1156
+ boardOffset[slot] = total;
1157
+ total += active2.count[slot];
1158
+ }
1159
+ }
1160
+ perNode[r] = total;
1161
+ }
1162
+ const baseOffset = new Int32Array(tree.nodeCount).fill(-1);
1163
+ const walkOffset = new Int32Array(tree.nodeCount).fill(-1);
1164
+ let values = 0;
1165
+ let walks = 0;
1166
+ for (let node = 0; node < tree.nodeCount; node++) {
1167
+ if (tree.kind[node] !== NodeKind.Chance) continue;
1168
+ const next = tree.round[node] + 1;
1169
+ if (next >= runouts.rounds || !rounds[next]) continue;
1170
+ baseOffset[node] = values;
1171
+ walkOffset[node] = walks;
1172
+ values += perNode[next];
1173
+ walks += runouts.counts[next] * 2;
1174
+ }
1175
+ if (values > 1073741823) throw new Error("chanceSampling: too many baseline values for this spot");
1176
+ const every = options.every ?? 0;
1177
+ const p = every > 0 ? 1 / every : options.p ?? 0.35;
1178
+ if (!(p > 0 && p <= 1)) throw new Error(`chanceSampling: p must be in (0, 1], got ${p}`);
1179
+ return {
1180
+ rounds,
1181
+ p,
1182
+ every,
1183
+ unbiased: (options.estimator ?? "unbiased") === "unbiased",
1184
+ catchUp: options.catchUp ?? true,
1185
+ baseOffset,
1186
+ boardOffset,
1187
+ walkOffset,
1188
+ values,
1189
+ walks,
1190
+ blocks: layout2.blocks
1191
+ };
1192
+ }
1193
+ function samplingBytes(plan) {
1194
+ return (plan.values + plan.walks + plan.blocks) * 4;
1195
+ }
1196
+ function makeSampling(plan, storage, allocate = (bytes) => new ArrayBuffer(bytes)) {
1197
+ return {
1198
+ ...plan,
1199
+ baseline: storage?.baseline ?? new Float32Array(allocate(plan.values * 4)),
1200
+ lastWalk: storage?.lastWalk ?? new Int32Array(allocate(plan.walks * 4)),
1201
+ lastUpdate: storage?.lastUpdate ?? new Int32Array(allocate(plan.blocks * 4)),
1202
+ bytes: samplingBytes(plan)
1203
+ };
1204
+ }
1205
+ function sampled(s, node, board, t) {
1206
+ let h = Math.imul(node ^ Math.imul(board, 2654435761), 2246822507);
1207
+ if (s.every > 0) {
1208
+ h ^= h >>> 13;
1209
+ h = Math.imul(h, 3266489909);
1210
+ h ^= h >>> 16;
1211
+ return ((h >>> 0) + t) % s.every === 0;
1212
+ }
1213
+ h ^= Math.imul(t, 668265263);
1214
+ h ^= h >>> 15;
1215
+ h = Math.imul(h, 3266489909);
1216
+ h ^= h >>> 13;
1217
+ h = Math.imul(h, 374761393);
1218
+ h ^= h >>> 16;
1219
+ return (h >>> 0) / 4294967296 < s.p;
1220
+ }
1221
+ var factorCache = [];
1222
+ function cachedFactors(t) {
1223
+ let f = factorCache[t];
1224
+ if (f === void 0) factorCache[t] = f = dcfrFactors(t);
1225
+ return f;
1226
+ }
1227
+ function blockFactors(ctx2, block, iterWeight) {
1228
+ let { keepPositive, keepNegative, keepSum } = cachedFactors(iterWeight);
1229
+ const discounted = ctx2.discounted;
1230
+ if (discounted !== void 0 && discounted !== null) {
1231
+ if (discounted[block] === iterWeight) keepPositive = keepNegative = keepSum = 1;
1232
+ discounted[block] = iterWeight;
1233
+ }
1234
+ const sampling = ctx2.sampling;
1235
+ if (sampling !== void 0 && sampling !== null) {
1236
+ if (sampling.catchUp) {
1237
+ for (let s = sampling.lastUpdate[block] + 1; s < iterWeight; s++) {
1238
+ const f = cachedFactors(s);
1239
+ keepPositive *= f.keepPositive;
1240
+ keepNegative *= f.keepNegative;
1241
+ keepSum *= f.keepSum;
1242
+ }
1243
+ }
1244
+ sampling.lastUpdate[block] = iterWeight;
1245
+ }
1246
+ return { keepPositive, keepNegative, keepSum };
1247
+ }
966
1248
  function runoutWeights(runouts) {
967
1249
  const weights2 = new Float64Array(runouts.rounds).fill(1);
968
1250
  for (let round = 0; round < runouts.rounds; round++) {
@@ -1001,15 +1283,22 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1001
1283
  const slots = roundBase[runouts.rounds] * 2;
1002
1284
  const start = new Int32Array(slots);
1003
1285
  const count = new Uint16Array(slots);
1286
+ const packedSlot = new Uint8Array(slots);
1004
1287
  const entries = [];
1005
1288
  const entrySlots = [];
1289
+ const memberStart = [];
1290
+ const members = [];
1006
1291
  const onBoard = new Uint8Array(DECK);
1292
+ const seen = new Uint8Array(COMBOS);
1007
1293
  for (let round = 0; round < runouts.rounds; round++) {
1008
1294
  const width = runouts.width[round];
1009
1295
  const cards = runouts.cards[round];
1296
+ const stabStart = runouts.stabiliserStart[round];
1297
+ const stabMap = runouts.stabiliserMap[round];
1010
1298
  for (let board = 0; board < runouts.counts[round]; board++) {
1011
1299
  onBoard.fill(0);
1012
1300
  for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1301
+ const symmetric = stabStart[board + 1] - stabStart[board] > 1;
1013
1302
  for (let player = 0; player < 2; player++) {
1014
1303
  const index = players[player];
1015
1304
  const slot = (roundBase[round] + board) * 2 + player;
@@ -1018,6 +1307,7 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1018
1307
  for (let i = 0; i < index.count; i++) {
1019
1308
  const combo = index.combos[i];
1020
1309
  if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1310
+ if (symmetric && !orbitLeader(runouts, round, board, combo)) continue;
1021
1311
  here.push(i);
1022
1312
  }
1023
1313
  if (showdown2 !== null && round === runouts.rounds - 1) {
@@ -1025,47 +1315,42 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1025
1315
  here.sort((x, y) => group[index.combos[x]] - group[index.combos[y]] || x - y);
1026
1316
  }
1027
1317
  for (const i of here) {
1028
- entries.push(index.combos[i]);
1318
+ const combo = index.combos[i];
1319
+ entries.push(combo);
1029
1320
  entrySlots.push(i);
1030
- }
1031
- count[slot] = entries.length - start[slot];
1032
- }
1033
- }
1034
- }
1035
- const tieStart = new Int32Array(slots + 1);
1036
- const ties = [];
1037
- for (let round = 0; round < runouts.rounds; round++) {
1038
- const stabStart = runouts.stabiliserStart[round];
1039
- const stabMap = runouts.stabiliserMap[round];
1040
- for (let board = 0; board < runouts.counts[round]; board++) {
1041
- for (let player = 0; player < 2; player++) {
1042
- const slot = (roundBase[round] + board) * 2 + player;
1043
- tieStart[slot] = ties.length;
1044
- if (stabStart[board + 1] - stabStart[board] < 2) continue;
1045
- const position = /* @__PURE__ */ new Map();
1046
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) position.set(entries[e], e - start[slot]);
1047
- const seen = new Uint8Array(count[slot]);
1048
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) {
1049
- if (seen[e - start[slot]]) continue;
1050
- const members = [];
1051
- for (let k = stabStart[board]; k < stabStart[board + 1]; k++) {
1052
- const image = position.get(runouts.maps.combo[stabMap[k]][entries[e]]);
1053
- if (image === void 0 || seen[image]) continue;
1321
+ memberStart.push(members.length);
1322
+ members.push(combo);
1323
+ if (!symmetric) continue;
1324
+ seen[combo] = 1;
1325
+ for (let k = stabStart[board] + 1; k < stabStart[board + 1]; k++) {
1326
+ const image = runouts.maps.combo[stabMap[k]][combo];
1327
+ if (seen[image]) continue;
1054
1328
  seen[image] = 1;
1055
1329
  members.push(image);
1330
+ packedSlot[slot] = 1;
1056
1331
  }
1057
- if (members.length > 1) ties.push(members.length, ...members);
1332
+ for (let m = memberStart[memberStart.length - 1]; m < members.length; m++) seen[members[m]] = 0;
1058
1333
  }
1334
+ count[slot] = entries.length - start[slot];
1059
1335
  }
1060
1336
  }
1061
1337
  }
1062
- tieStart[slots] = ties.length;
1338
+ memberStart.push(members.length);
1063
1339
  const list = Uint16Array.from(entries);
1064
1340
  const cardA = new Uint8Array(list.length);
1065
1341
  const cardB = new Uint8Array(list.length);
1342
+ const multiplicity = new Float64Array(list.length);
1066
1343
  for (let e = 0; e < list.length; e++) {
1067
1344
  cardA[e] = COMBO_CARDS[list[e] * 2];
1068
1345
  cardB[e] = COMBO_CARDS[list[e] * 2 + 1];
1346
+ multiplicity[e] = memberStart[e + 1] - memberStart[e];
1347
+ }
1348
+ const memberCombo = Uint16Array.from(members);
1349
+ const memberA = new Uint8Array(members.length);
1350
+ const memberB = new Uint8Array(members.length);
1351
+ for (let m = 0; m < members.length; m++) {
1352
+ memberA[m] = COMBO_CARDS[members[m] * 2];
1353
+ memberB[m] = COMBO_CARDS[members[m] * 2 + 1];
1069
1354
  }
1070
1355
  const strength = new Int32Array(list.length);
1071
1356
  if (showdown2 !== null) {
@@ -1084,11 +1369,15 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1084
1369
  list,
1085
1370
  slot: Uint16Array.from(entrySlots),
1086
1371
  roundBase,
1087
- tieStart,
1088
- ties: Int32Array.from(ties),
1089
1372
  cardA,
1090
1373
  cardB,
1091
- strength
1374
+ strength,
1375
+ packed: packedSlot,
1376
+ multiplicity,
1377
+ memberStart: Int32Array.from(memberStart),
1378
+ memberCombo,
1379
+ memberA,
1380
+ memberB
1092
1381
  };
1093
1382
  }
1094
1383
  var strengthScratch = new Int32Array(COMBOS);
@@ -1102,20 +1391,6 @@ function strengthOn(table, board) {
1102
1391
  }
1103
1392
  return strengthScratch;
1104
1393
  }
1105
- function tieMirrors(store, slotBase, actions, stride, ties, from, to, integer) {
1106
- for (let a = 0; a < actions; a++) {
1107
- const row = slotBase + a * stride;
1108
- for (let k = from; k < to; ) {
1109
- const size = ties[k];
1110
- let sum = 0;
1111
- for (let j = 1; j <= size; j++) sum += store[row + ties[k + j]];
1112
- let mean = sum / size;
1113
- if (integer) mean = Math.round(mean);
1114
- for (let j = 1; j <= size; j++) store[row + ties[k + j]] = mean;
1115
- k += size + 1;
1116
- }
1117
- }
1118
- }
1119
1394
  function makeBuffers2(tree, maxActions, simd2) {
1120
1395
  const depth = treeDepth2(tree) + 2;
1121
1396
  const make = (factory) => Array.from({ length: depth }, factory);
@@ -1161,7 +1436,7 @@ function dcfrFactors(t) {
1161
1436
  keepSum: ((t - 1) / t) ** DCFR_GAMMA
1162
1437
  };
1163
1438
  }
1164
- var Mode = { Train: 0, BestResponse: 1, Average: 2 };
1439
+ var Mode = { Train: 0, BestResponse: 1, Average: 2, Current: 3 };
1165
1440
  function normalise(source, base, actions, count, strategy) {
1166
1441
  const uniform = 1 / actions;
1167
1442
  for (let i = 0; i < count; i++) {
@@ -1180,6 +1455,20 @@ function normalise(source, base, actions, count, strategy) {
1180
1455
  }
1181
1456
  }
1182
1457
  }
1458
+ var TIE_TOLERANCE = 2 ** -20;
1459
+ function snapTies(actionValues, out, actions, count) {
1460
+ for (let a = 0; a < actions; a++) {
1461
+ const offset = a * count;
1462
+ for (let i = 0; i < count; i++) {
1463
+ const v = actionValues[offset + i];
1464
+ const value = out[i];
1465
+ const gap = v < value ? value - v : v - value;
1466
+ const size = v < 0 ? -v : v;
1467
+ const valueSize = value < 0 ? -value : value;
1468
+ if (gap <= TIE_TOLERANCE * (size > valueSize ? size : valueSize)) actionValues[offset + i] = value;
1469
+ }
1470
+ }
1471
+ }
1183
1472
  function regretMatch(regret, base, actions, count, strategy) {
1184
1473
  normalise(regret, base, actions, count, strategy);
1185
1474
  }
@@ -1229,7 +1518,27 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1229
1518
  if (kind === NodeKind.TerminalFold) {
1230
1519
  const signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];
1231
1520
  const weight = ctx2.runoutWeight[round] / ctx2.chipScale;
1232
- const hands = ctx2.hands;
1521
+ const hands2 = ctx2.hands;
1522
+ if (lists.packed[oppSlot]) {
1523
+ foldValuesPacked(
1524
+ reachOpp2,
1525
+ lists.cardA,
1526
+ lists.cardB,
1527
+ lists.memberStart,
1528
+ lists.memberA,
1529
+ lists.memberB,
1530
+ oppFrom,
1531
+ oppCount,
1532
+ myFrom,
1533
+ myCount,
1534
+ hands2.same,
1535
+ hands2.sameStart[mySlot],
1536
+ signed * weight,
1537
+ buffers.cardSums,
1538
+ out
1539
+ );
1540
+ return out;
1541
+ }
1233
1542
  foldValuesHands(
1234
1543
  reachOpp2,
1235
1544
  lists.cardA,
@@ -1238,8 +1547,8 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1238
1547
  oppCount,
1239
1548
  myFrom,
1240
1549
  myCount,
1241
- hands.same,
1242
- hands.sameStart[mySlot],
1550
+ hands2.same,
1551
+ hands2.sameStart[mySlot],
1243
1552
  signed * weight,
1244
1553
  buffers.cardSums,
1245
1554
  out
@@ -1248,6 +1557,25 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1248
1557
  }
1249
1558
  if (kind === NodeKind.TerminalShowdown) {
1250
1559
  const weight = ctx2.runoutWeight[round] / ctx2.chipScale;
1560
+ if (lists.packed[oppSlot]) {
1561
+ showdownValuesPacked(
1562
+ reachOpp2,
1563
+ lists.cardA,
1564
+ lists.cardB,
1565
+ lists.memberStart,
1566
+ lists.memberA,
1567
+ lists.memberB,
1568
+ lists.strength,
1569
+ oppFrom,
1570
+ oppCount,
1571
+ myFrom,
1572
+ myCount,
1573
+ tree.payoff[node] * weight,
1574
+ buffers.cardSums,
1575
+ out
1576
+ );
1577
+ return out;
1578
+ }
1251
1579
  showdownValuesHands(
1252
1580
  reachOpp2,
1253
1581
  lists.cardA,
@@ -1287,10 +1615,13 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1287
1615
  const childMe = buffers.reachFor[traverser][depth];
1288
1616
  const childOpp = buffers.reachFor[opponent][depth];
1289
1617
  const sharded = nextRound === ctx2.shardRound;
1290
- const first = runouts.childStart[nextRound][board];
1291
- const last = runouts.childStart[nextRound][board + 1];
1618
+ const starts = runouts.childStart[nextRound];
1619
+ const first = starts[board];
1620
+ const last = starts[board + 1];
1292
1621
  const from = sharded && ctx2.shardStart > first ? ctx2.shardStart : first;
1293
1622
  const to = sharded && ctx2.shardEnd < last ? ctx2.shardEnd : last;
1623
+ const sampling = ctx2.sampling ?? null;
1624
+ const sampleHere = sampling !== null && mode === Mode.Train && ctx2.applyUpdates && !ctx2.expandOrbits && sampling.rounds[nextRound] === 1;
1294
1625
  for (let childBoard = from; childBoard < to; childBoard++) {
1295
1626
  const childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;
1296
1627
  const childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;
@@ -1301,15 +1632,40 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1301
1632
  let value = null;
1302
1633
  for (let m = firstMember; m < membersEnd; m++) {
1303
1634
  const upMe = upStart[m * 2 + traverser];
1304
- if (value === null || ctx2.expandOrbits) {
1635
+ if (sampleHere && value === null) {
1636
+ value = sampledValue(
1637
+ ctx2,
1638
+ sampling,
1639
+ buffers,
1640
+ traverser,
1641
+ iterWeight,
1642
+ node,
1643
+ child,
1644
+ nextRound,
1645
+ childBoard,
1646
+ reachMe2,
1647
+ reachOpp2,
1648
+ childMe,
1649
+ childOpp,
1650
+ depth
1651
+ );
1652
+ } else if (value === null || ctx2.expandOrbits) {
1305
1653
  const upOpp = upStart[m * 2 + opponent];
1306
1654
  for (let k = 0; k < nMe; k++) childMe[k] = reachMe2[up[upMe + k]];
1307
1655
  for (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp2[up[upOpp + k]];
1308
1656
  value = traverse(ctx2, buffers, mode, traverser, iterWeight, child, childBoard, childMe, childOpp, depth + 1);
1309
1657
  }
1310
- for (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];
1658
+ if (lists.packed[childMySlot]) {
1659
+ const childFrom = lists.start[childMySlot];
1660
+ for (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k] * lists.multiplicity[childFrom + k];
1661
+ } else {
1662
+ for (let k = 0; k < nMe; k++) out[up[upMe + k]] += value[k];
1663
+ }
1311
1664
  }
1312
1665
  }
1666
+ if (lists.packed[mySlot]) {
1667
+ for (let i = 0; i < myCount; i++) out[i] /= lists.multiplicity[myFrom + i];
1668
+ }
1313
1669
  return out;
1314
1670
  }
1315
1671
  const actions = tree.numEdges[node];
@@ -1322,12 +1678,19 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1322
1678
  const slotBase = ctx2.layout.offset[node] + actions * ctx2.layout.rowStart[listSlot];
1323
1679
  const strategy = buffers.strategy[depth];
1324
1680
  const length = actions * stride;
1325
- if (mode === Mode.Train && buffers.kernels !== null) {
1681
+ const compactNode = round >= ctx2.layout.compactFrom;
1682
+ const chunk = compactNode ? ctx2.layout.compactChunk[node] : 0;
1683
+ const regrets = compactNode ? ctx2.compactRegret[chunk] : ctx2.regret;
1684
+ const compactSums = compactNode && ctx2.compact.sums;
1685
+ const current = mode === Mode.Train || mode === Mode.Current || compactNode && !compactSums;
1686
+ if (current && buffers.kernels !== null) {
1326
1687
  const kernels = buffers.kernels;
1327
- kernels.input.set(ctx2.regret.subarray(slotBase, slotBase + length));
1688
+ kernels.input.set(regrets.subarray(slotBase, slotBase + length));
1328
1689
  kernels.regretMatch(strategy, actions, stride);
1329
- } else if (mode === Mode.Train) {
1330
- regretMatch(ctx2.regret, slotBase, actions, stride, strategy);
1690
+ } else if (current) {
1691
+ regretMatch(regrets, slotBase, actions, stride, strategy);
1692
+ } else if (compactSums) {
1693
+ averageStrategy(ctx2.compactSum[chunk], slotBase, actions, stride, strategy, regrets);
1331
1694
  } else if (buffers.kernels !== null) {
1332
1695
  const kernels = buffers.kernels;
1333
1696
  kernels.input.set(ctx2.strategySum.subarray(slotBase, slotBase + length));
@@ -1388,9 +1751,36 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1388
1751
  for (let i = 0; i < myCount; i++) out[i] += value[i];
1389
1752
  }
1390
1753
  }
1391
- if (isTraverser && mode === Mode.Train && ctx2.applyUpdates && ctx2.regretScale !== null) {
1754
+ if (isTraverser && mode === Mode.Train && ctx2.applyUpdates) snapTies(actionValues, out, actions, myCount);
1755
+ const weighted = ctx2.layout.reachWeighted;
1756
+ if (weighted !== null && weighted[node] && isTraverser && mode === Mode.Train && ctx2.applyUpdates) {
1757
+ for (let a = 0; a < actions; a++) {
1758
+ const offset = a * myCount;
1759
+ for (let i = 0; i < myCount; i++) {
1760
+ actionValues[offset + i] = out[i] + reachMe2[i] * (actionValues[offset + i] - out[i]);
1761
+ }
1762
+ }
1763
+ }
1764
+ if (isTraverser && mode === Mode.Train && ctx2.applyUpdates && compactNode) {
1765
+ updateCompact(
1766
+ ctx2,
1767
+ node,
1768
+ chunk,
1769
+ ctx2.layout.blockOffset[node] + board,
1770
+ slotBase,
1771
+ ctx2.layout.handOffset[node] + ctx2.layout.rowStart[listSlot],
1772
+ actions,
1773
+ stride,
1774
+ iterWeight,
1775
+ reachMe2,
1776
+ strategy,
1777
+ actionValues,
1778
+ out
1779
+ );
1780
+ } else if (isTraverser && mode === Mode.Train && ctx2.applyUpdates && ctx2.regretScale !== null) {
1392
1781
  updateQuantised(
1393
1782
  ctx2,
1783
+ node,
1394
1784
  ctx2.layout.blockOffset[node] + board,
1395
1785
  slotBase,
1396
1786
  actions,
@@ -1402,7 +1792,7 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1402
1792
  out
1403
1793
  );
1404
1794
  } else if (isTraverser && mode === Mode.Train && ctx2.applyUpdates && ctx2.dcfr) {
1405
- const { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);
1795
+ const { keepPositive, keepNegative, keepSum } = blockFactors(ctx2, ctx2.layout.blockOffset[node] + board, iterWeight);
1406
1796
  const regret = ctx2.regret;
1407
1797
  const strategySum = ctx2.strategySum;
1408
1798
  for (let a = 0; a < actions; a++) {
@@ -1413,7 +1803,7 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1413
1803
  const at = slotRow + i;
1414
1804
  const accumulated = regret[at];
1415
1805
  regret[at] = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + i] - out[i];
1416
- strategySum[at] = strategySum[at] * keepSum + reachMe2[i] * strategy[row + i];
1806
+ strategySum[at] = strategySum[at] * keepSum + strategy[row + i];
1417
1807
  }
1418
1808
  }
1419
1809
  } else if (isTraverser && mode === Mode.Train && ctx2.applyUpdates) {
@@ -1431,18 +1821,39 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1431
1821
  }
1432
1822
  }
1433
1823
  }
1434
- if (isTraverser && mode === Mode.Train && ctx2.applyUpdates) {
1435
- const tieFrom = lists.tieStart[listSlot];
1436
- const tieTo = lists.tieStart[listSlot + 1];
1437
- if (tieFrom < tieTo) {
1438
- const integer = ctx2.regretScale !== null;
1439
- tieMirrors(ctx2.regret, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);
1440
- tieMirrors(ctx2.strategySum, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);
1441
- }
1442
- }
1443
1824
  return out;
1444
1825
  }
1445
- function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reachMe2, strategy, actionValues, out) {
1826
+ function sampledValue(ctx2, s, buffers, traverser, t, node, child, nextRound, childBoard, reachMe2, reachOpp2, childMe, childOpp, depth) {
1827
+ const lists = ctx2.active;
1828
+ const opponent = 1 - traverser;
1829
+ const childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;
1830
+ const nMe = lists.count[childMySlot];
1831
+ const at = s.baseOffset[node] + s.boardOffset[childMySlot];
1832
+ const walkAt = s.walkOffset[node] + childBoard * 2 + traverser;
1833
+ const fresh = s.lastWalk[walkAt] === 0;
1834
+ if (!fresh && !sampled(s, node, childBoard, t)) return s.baseline.subarray(at, at + nMe);
1835
+ const childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;
1836
+ const nOpp = lists.count[childOppSlot];
1837
+ const member = ctx2.runouts.orbitStart[nextRound][childBoard];
1838
+ const upStart = ctx2.hands.upStart[nextRound];
1839
+ const up = ctx2.hands.up;
1840
+ const upMe = upStart[member * 2 + traverser];
1841
+ const upOpp = upStart[member * 2 + opponent];
1842
+ for (let k = 0; k < nMe; k++) childMe[k] = reachMe2[up[upMe + k]];
1843
+ for (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp2[up[upOpp + k]];
1844
+ const value = traverse(ctx2, buffers, Mode.Train, traverser, t, child, childBoard, childMe, childOpp, depth + 1);
1845
+ const weight = s.unbiased ? 1 / s.p : 1;
1846
+ const baseline = s.baseline;
1847
+ for (let k = 0; k < nMe; k++) {
1848
+ const v = value[k];
1849
+ const b = baseline[at + k];
1850
+ baseline[at + k] = v;
1851
+ if (!fresh) value[k] = v + (weight - 1) * (v - b);
1852
+ }
1853
+ s.lastWalk[walkAt] = t;
1854
+ return value;
1855
+ }
1856
+ function updateQuantised(ctx2, node, block, slotBase, actions, count, iterWeight, reachMe2, strategy, actionValues, out) {
1446
1857
  const regret = ctx2.regret;
1447
1858
  const strategySum = ctx2.strategySum;
1448
1859
  const regretScale = ctx2.regretScale;
@@ -1455,7 +1866,7 @@ function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reac
1455
1866
  let weight = iterWeight;
1456
1867
  const clamp = !ctx2.dcfr;
1457
1868
  if (ctx2.dcfr) {
1458
- ({ keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight));
1869
+ ({ keepPositive, keepNegative, keepSum } = blockFactors(ctx2, block, iterWeight));
1459
1870
  weight = 1;
1460
1871
  }
1461
1872
  let largestRegret = 0;
@@ -1471,13 +1882,15 @@ function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reac
1471
1882
  const magnitude = updated < 0 ? -updated : updated;
1472
1883
  if (magnitude > largestRegret) largestRegret = magnitude;
1473
1884
  actionValues[offset + i] = updated;
1474
- const sum = strategySum[at] * oldSum * keepSum + weight * reachMe2[i] * strategy[a * count + i];
1885
+ const added = clamp ? weight * reachMe2[i] * strategy[a * count + i] : weight * strategy[a * count + i];
1886
+ const sum = strategySum[at] * oldSum * keepSum + added;
1475
1887
  if (sum > largestSum) largestSum = sum;
1476
1888
  strategy[a * count + i] = sum;
1477
1889
  }
1478
1890
  }
1479
1891
  const regretStep = largestRegret > 0 ? REGRET_STEPS / largestRegret : 0;
1480
1892
  const sumStep = largestSum > 0 ? SUM_STEPS / largestSum : 0;
1893
+ const salt = ctx2.layout.shared ? node : 0;
1481
1894
  for (let a = 0; a < actions; a++) {
1482
1895
  const offset = a * count;
1483
1896
  const slotRow = slotBase + a * count;
@@ -1485,15 +1898,157 @@ function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reac
1485
1898
  const at = slotRow + i;
1486
1899
  const r = actionValues[offset + i] * regretStep;
1487
1900
  regret[at] = r < 0 ? r - 0.5 : r + 0.5;
1488
- const s = strategy[a * count + i] * sumStep + dither(at, iterWeight);
1901
+ const s = strategy[a * count + i] * sumStep + dither(at, iterWeight, salt);
1489
1902
  strategySum[at] = s < SUM_STEPS ? s : SUM_STEPS;
1490
1903
  }
1491
1904
  }
1492
1905
  regretScale[block] = largestRegret / REGRET_STEPS;
1493
1906
  sumScale[block] = largestSum / SUM_STEPS;
1494
1907
  }
1495
- function dither(slot, iteration) {
1496
- let h = Math.imul(slot ^ Math.imul(iteration, 2654435761), 2246822507);
1908
+ var SHIFT_BIAS = 160;
1909
+ var SHIFT_SCALE = Float64Array.from({ length: 256 }, (_, e) => e === 0 ? 0 : 2 ** (e - SHIFT_BIAS));
1910
+ function updateCompact(ctx2, node, chunk, block, slotBase, handBase, actions, count, iterWeight, reachMe2, strategy, actionValues, out) {
1911
+ const plan = ctx2.compact;
1912
+ const q = ctx2.compactRegret[chunk];
1913
+ const hashBase = ctx2.layout.chunkStart[chunk] + slotBase;
1914
+ const salt = ctx2.layout.shared ? node : 0;
1915
+ const steps = plan.steps;
1916
+ let keepPositive = 1;
1917
+ let keepNegative = 0;
1918
+ let keepSum = 1;
1919
+ let weight = iterWeight;
1920
+ const clamp = !ctx2.dcfr;
1921
+ if (ctx2.dcfr) {
1922
+ ({ keepPositive, keepNegative, keepSum } = blockFactors(ctx2, block, iterWeight));
1923
+ weight = 1;
1924
+ }
1925
+ if (plan.float) {
1926
+ for (let k = 0; k < actions * count; k++) {
1927
+ const accumulated = q[slotBase + k];
1928
+ const updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[k % count];
1929
+ q[slotBase + k] = clamp && updated < 0 ? 0 : updated;
1930
+ }
1931
+ return;
1932
+ }
1933
+ if (!plan.perHand) {
1934
+ const scales = ctx2.compactScale;
1935
+ const old = scales[block];
1936
+ let largest = 0;
1937
+ for (let a = 0; a < actions; a++) {
1938
+ const row = a * count;
1939
+ for (let i = 0; i < count; i++) {
1940
+ const accumulated = q[slotBase + row + i] * old;
1941
+ let updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[row + i] - out[i];
1942
+ if (clamp && updated < 0) updated = 0;
1943
+ actionValues[row + i] = updated;
1944
+ const magnitude = updated < 0 ? -updated : updated;
1945
+ if (magnitude > largest) largest = magnitude;
1946
+ }
1947
+ }
1948
+ const step = largest > 0 ? steps / largest : 0;
1949
+ const stochastic2 = plan.stochastic;
1950
+ for (let a = 0; a < actions; a++) {
1951
+ const row = a * count;
1952
+ let h = stochastic2 ? streamSeed(hashBase + row, iterWeight, salt) : 0;
1953
+ for (let i = 0; i < count; i++) {
1954
+ const value = actionValues[row + i] * step;
1955
+ let rounded;
1956
+ if (stochastic2) {
1957
+ h = nextState(h);
1958
+ rounded = Math.floor(value + (h >>> 0) / 4294967296);
1959
+ } else {
1960
+ rounded = Math.round(value);
1961
+ }
1962
+ q[slotBase + row + i] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;
1963
+ }
1964
+ }
1965
+ scales[block] = largest / steps;
1966
+ return;
1967
+ }
1968
+ const shifts = ctx2.handShift[chunk];
1969
+ const stochastic = plan.stochastic;
1970
+ const sums = plan.sums ? ctx2.compactSum[chunk] : null;
1971
+ const sumShifts = plan.sums ? ctx2.sumShift[chunk] : null;
1972
+ for (let i = 0; i < count; i++) {
1973
+ const scale = SHIFT_SCALE[shifts[handBase + i]];
1974
+ let largest = 0;
1975
+ for (let a = 0; a < actions; a++) {
1976
+ const k = a * count + i;
1977
+ const accumulated = q[slotBase + k] * scale;
1978
+ let updated = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[k] - out[i];
1979
+ if (clamp && updated < 0) updated = 0;
1980
+ actionValues[k] = updated;
1981
+ const magnitude = updated < 0 ? -updated : updated;
1982
+ if (magnitude > largest) largest = magnitude;
1983
+ }
1984
+ const exponent = scaleExponent(largest, steps);
1985
+ shifts[handBase + i] = exponent;
1986
+ const inverse = exponent === 0 ? 0 : 1 / SHIFT_SCALE[exponent];
1987
+ let h = stochastic || sums !== null ? streamSeed(hashBase + i, iterWeight, salt) : 0;
1988
+ for (let a = 0; a < actions; a++) {
1989
+ const k = a * count + i;
1990
+ const value = actionValues[k] * inverse;
1991
+ let rounded;
1992
+ if (stochastic) {
1993
+ h = nextState(h);
1994
+ rounded = Math.floor(value + (h >>> 0) / 4294967296);
1995
+ } else {
1996
+ rounded = Math.round(value);
1997
+ }
1998
+ q[slotBase + k] = rounded > steps ? steps : rounded < -steps ? -steps : rounded;
1999
+ }
2000
+ if (sums === null) continue;
2001
+ const sumScale = SHIFT_SCALE[sumShifts[handBase + i]];
2002
+ let largestSum = 0;
2003
+ for (let a = 0; a < actions; a++) {
2004
+ const k = a * count + i;
2005
+ const added = clamp ? weight * reachMe2[i] * strategy[k] : weight * strategy[k];
2006
+ const sum = sums[slotBase + k] * sumScale * keepSum + added;
2007
+ strategy[k] = sum;
2008
+ if (sum > largestSum) largestSum = sum;
2009
+ }
2010
+ const sumExponent = scaleExponent(largestSum, COMPACT_SUM_STEPS);
2011
+ sumShifts[handBase + i] = sumExponent;
2012
+ const sumInverse = sumExponent === 0 ? 0 : 1 / SHIFT_SCALE[sumExponent];
2013
+ for (let a = 0; a < actions; a++) {
2014
+ const k = a * count + i;
2015
+ h = nextState(h);
2016
+ const rounded = Math.floor(strategy[k] * sumInverse + (h >>> 0) / 4294967296);
2017
+ sums[slotBase + k] = rounded < COMPACT_SUM_STEPS ? rounded : COMPACT_SUM_STEPS;
2018
+ }
2019
+ }
2020
+ }
2021
+ var COMPACT_SUM_STEPS = 255;
2022
+ function scaleExponent(largest, steps) {
2023
+ if (!(largest > 0)) return 0;
2024
+ EXPONENT_FLOAT[0] = largest / steps;
2025
+ const high2 = EXPONENT_BITS[1];
2026
+ let exponent = (high2 >>> 20 & 2047) - 1023 + SHIFT_BIAS;
2027
+ if ((high2 & 1048575) !== 0 || EXPONENT_BITS[0] !== 0) exponent++;
2028
+ return exponent < 1 ? 0 : exponent > 255 ? 255 : exponent;
2029
+ }
2030
+ function streamSeed(slot, iteration, salt) {
2031
+ return Math.imul(slot ^ Math.imul(iteration, 2654435761) ^ Math.imul(salt, 2146121005) ^ 1540483477, 2246822507) | 1;
2032
+ }
2033
+ function nextState(h) {
2034
+ h ^= h >>> 15;
2035
+ h = Math.imul(h, 739982445);
2036
+ return h ^ h >>> 12;
2037
+ }
2038
+ var EXPONENT_FLOAT = new Float64Array(1);
2039
+ var EXPONENT_BITS = new Uint32Array(EXPONENT_FLOAT.buffer);
2040
+ function storedStrategy(ctx2, node, base, actions, count, strategy) {
2041
+ if (ctx2.tree.round[node] >= ctx2.layout.compactFrom && ctx2.compact.sums) {
2042
+ const chunk = ctx2.layout.compactChunk[node];
2043
+ averageStrategy(ctx2.compactSum[chunk], base, actions, count, strategy, ctx2.compactRegret[chunk]);
2044
+ } else if (ctx2.tree.round[node] >= ctx2.layout.compactFrom) {
2045
+ regretMatch(ctx2.compactRegret[ctx2.layout.compactChunk[node]], base, actions, count, strategy);
2046
+ } else {
2047
+ averageStrategy(ctx2.strategySum, base, actions, count, strategy, ctx2.regret);
2048
+ }
2049
+ }
2050
+ function dither(slot, iteration, salt = 0) {
2051
+ let h = Math.imul(slot ^ Math.imul(iteration, 2654435761) ^ Math.imul(salt, 668265263), 2246822507);
1497
2052
  h ^= h >>> 13;
1498
2053
  h = Math.imul(h, 3266489909);
1499
2054
  h ^= h >>> 16;
@@ -1535,7 +2090,7 @@ function makeSolver(ctx2) {
1535
2090
  const weights2 = ctx2.players[traverser].weights;
1536
2091
  const [from, count] = listOf(0, 0, traverser);
1537
2092
  let sum = 0;
1538
- for (let i = 0; i < count; i++) sum += weights2[lists.list[from + i]] * values[i];
2093
+ for (let i = 0; i < count; i++) sum += weights2[lists.list[from + i]] * lists.multiplicity[from + i] * values[i];
1539
2094
  return sum / ctx2.totalMass;
1540
2095
  };
1541
2096
  return {
@@ -1545,6 +2100,9 @@ function makeSolver(ctx2) {
1545
2100
  return rootCount;
1546
2101
  },
1547
2102
  traverseRoot: run,
2103
+ get root() {
2104
+ return root;
2105
+ },
1548
2106
  useRoot(next) {
1549
2107
  root = next ?? run;
1550
2108
  },
@@ -1561,17 +2119,79 @@ function makeSolver(ctx2) {
1561
2119
  expectedValue() {
1562
2120
  return [total(root(Mode.Average, 0, 0), 0), total(root(Mode.Average, 1, 0), 1)];
1563
2121
  },
2122
+ rootValues(mode) {
2123
+ if (mode === Mode.Current && ctx2.regret.length === 0 && !ctx2.compactRegret) {
2124
+ throw new Error("The current profile needs regrets, and an analysis-only run has none");
2125
+ }
2126
+ const one = (player) => {
2127
+ const values = root(mode, player, 0);
2128
+ return [total(values, player), values.slice(0, listOf(0, 0, player)[1])];
2129
+ };
2130
+ const [total0, values0] = one(0);
2131
+ const [total1, values1] = one(1);
2132
+ return { totals: [total0, total1], values: [values0, values1] };
2133
+ },
2134
+ handEvs(player, values) {
2135
+ const opponent = ctx2.players[1 - player];
2136
+ const evs = new Float64Array(COMBOS);
2137
+ const [from, count] = listOf(0, 0, player);
2138
+ if (values.length !== count) {
2139
+ throw new Error(`Player ${player} has ${count} root hands, but ${values.length} values were given`);
2140
+ }
2141
+ const scale = ctx2.runoutWeight[0];
2142
+ for (let i = 0; i < count; i++) {
2143
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
2144
+ const combo = lists.memberCombo[m];
2145
+ const a = COMBO_CARDS[combo * 2];
2146
+ const b = COMBO_CARDS[combo * 2 + 1];
2147
+ let mass = 0;
2148
+ for (let j = 0; j < opponent.count; j++) {
2149
+ const other = opponent.combos[j];
2150
+ const c = COMBO_CARDS[other * 2];
2151
+ const d = COMBO_CARDS[other * 2 + 1];
2152
+ if (c !== a && c !== b && d !== a && d !== b) mass += opponent.weights[other];
2153
+ }
2154
+ evs[combo] = mass > 0 ? values[i] / (mass * scale) : 0;
2155
+ }
2156
+ }
2157
+ return evs;
2158
+ },
1564
2159
  exploitability() {
1565
2160
  const br0 = total(root(Mode.BestResponse, 0, 0), 0);
1566
2161
  const br1 = total(root(Mode.BestResponse, 1, 0), 1);
1567
2162
  return (br0 + br1) / 2;
1568
2163
  },
1569
2164
  valuesAt(node, board, traverser, reachMe2, reachOpp2, live, liveCount) {
2165
+ void live;
2166
+ void liveCount;
2167
+ const round = ctx2.tree.round[node];
2168
+ const opponent = 1 - traverser;
2169
+ const [oppFrom, oppCount] = listOf(round, board, opponent);
2170
+ let symmetric = true;
2171
+ for (let j = 0; j < oppCount && symmetric; j++) {
2172
+ const own = reachOpp2[lists.list[oppFrom + j]];
2173
+ for (let m = lists.memberStart[oppFrom + j] + 1; m < lists.memberStart[oppFrom + j + 1]; m++) {
2174
+ if (reachOpp2[lists.memberCombo[m]] !== own) symmetric = false;
2175
+ }
2176
+ }
2177
+ const members = (player) => {
2178
+ const [from, count] = listOf(round, board, player);
2179
+ return lists.memberCombo.slice(lists.memberStart[from], lists.memberStart[from + count]);
2180
+ };
2181
+ if (!symmetric) {
2182
+ const theirs = members(opponent).filter((combo) => reachOpp2[combo] !== 0);
2183
+ const mine = members(traverser);
2184
+ const handReach = Float64Array.from(theirs, (combo) => reachOpp2[combo]);
2185
+ const rows = pairValues(ctx2, node, board, traverser, theirs, handReach, mine, mine.length);
2186
+ const result = new Float64Array(COMBOS);
2187
+ for (let k = 0; k < theirs.length; k++) {
2188
+ for (const combo of mine) result[combo] += rows[k * COMBOS + combo];
2189
+ }
2190
+ return result;
2191
+ }
1570
2192
  const expanded = ctx2.expandOrbits;
1571
2193
  ctx2.expandOrbits = true;
1572
2194
  try {
1573
- const round = ctx2.tree.round[node];
1574
- const opponent = 1 - traverser;
1575
2195
  const me = new Float64Array(COMBOS);
1576
2196
  const opp = new Float64Array(COMBOS);
1577
2197
  gather(reachMe2, round, board, traverser, me);
@@ -1579,16 +2199,18 @@ function makeSolver(ctx2) {
1579
2199
  const value = traverse(ctx2, buffers, Mode.Average, traverser, 0, node, board, me, opp, 0);
1580
2200
  const result = new Float64Array(COMBOS);
1581
2201
  const [from, count] = listOf(round, board, traverser);
1582
- for (let i = 0; i < count; i++) result[lists.list[from + i]] = value[i];
1583
- void live;
1584
- void liveCount;
2202
+ for (let i = 0; i < count; i++) {
2203
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
2204
+ result[lists.memberCombo[m]] = value[i];
2205
+ }
2206
+ }
1585
2207
  return result;
1586
2208
  } finally {
1587
2209
  ctx2.expandOrbits = expanded;
1588
2210
  }
1589
2211
  },
1590
- pairValuesAt(node, board, traverser, hands, handReach, live, liveCount) {
1591
- return pairValues(ctx2, node, board, traverser, hands, handReach, live, liveCount);
2212
+ pairValuesAt(node, board, traverser, hands2, handReach, live, liveCount) {
2213
+ return pairValues(ctx2, node, board, traverser, hands2, handReach, live, liveCount);
1592
2214
  },
1593
2215
  averageStrategyAt(node, board) {
1594
2216
  const owner = ctx2.tree.player[node];
@@ -1599,11 +2221,13 @@ function makeSolver(ctx2) {
1599
2221
  const count = lists.count[slot];
1600
2222
  const base = ctx2.layout.offset[node] + actions * ctx2.layout.rowStart[slot];
1601
2223
  const strategy = new Float64Array(actions * count);
1602
- averageStrategy(ctx2.strategySum, base, actions, count, strategy, ctx2.regret);
2224
+ storedStrategy(ctx2, node, base, actions, count, strategy);
1603
2225
  const probs = new Float64Array(index.count * actions).fill(1 / actions);
1604
2226
  for (let i = 0; i < count; i++) {
1605
- const at = lists.slot[from + i];
1606
- for (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];
2227
+ for (let m = lists.memberStart[from + i]; m < lists.memberStart[from + i + 1]; m++) {
2228
+ const at = index.slot[lists.memberCombo[m]];
2229
+ for (let a = 0; a < actions; a++) probs[at * actions + a] = strategy[a * count + i];
2230
+ }
1607
2231
  }
1608
2232
  return { actions, probs };
1609
2233
  }
@@ -1729,8 +2353,6 @@ function enumerateRunouts(board, symmetries, merge) {
1729
2353
  stabiliserMap.push(Int32Array.from(flat));
1730
2354
  };
1731
2355
  recordStabilisers(stabilisers);
1732
- const used = new Uint8Array(DECK);
1733
- const seen = new Uint8Array(DECK);
1734
2356
  for (let round = 1; round < rounds; round++) {
1735
2357
  const previousWidth = width[round - 1];
1736
2358
  const previousCount = counts[round - 1];
@@ -1745,49 +2367,9 @@ function enumerateRunouts(board, symmetries, merge) {
1745
2367
  const nextStabilisers = [];
1746
2368
  for (let p = 0; p < previousCount; p++) {
1747
2369
  starts[p] = parents.length;
1748
- used.fill(0);
1749
- seen.fill(0);
1750
2370
  const base = p * previousWidth;
1751
- for (let i = 0; i < previousWidth; i++) used[previousCards[base + i]] = 1;
1752
- const stabiliser = stabilisers[p];
1753
- const children = [];
1754
- for (let card = 0; card < DECK; card++) {
1755
- if (used[card] || seen[card]) continue;
1756
- const child = { card, maps: [], cards: [], fixing: [], merged: false };
1757
- for (const sigma of stabiliser) {
1758
- const image = maps.card[sigma][card];
1759
- if (image === card) child.fixing.push(sigma);
1760
- if (seen[image]) continue;
1761
- seen[image] = 1;
1762
- child.maps.push(image === card ? 0 : maps.inverse(sigma));
1763
- child.cards.push(image);
1764
- }
1765
- children.push(child);
1766
- }
1767
- if (merge) {
1768
- const boardRanks = /* @__PURE__ */ new Set();
1769
- for (let i = 0; i < previousWidth; i++) boardRanks.add(previousCards[base + i] >> 2);
1770
- for (let j = 0; j < children.length; j++) {
1771
- const later = children[j];
1772
- const rankJ = later.card >> 2;
1773
- if (boardRanks.has(rankJ)) continue;
1774
- for (let i = 0; i < j; i++) {
1775
- const earlier = children[i];
1776
- if (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;
1777
- const rankI = earlier.card >> 2;
1778
- if (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;
1779
- if (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;
1780
- const swap = maps.add(rankSwap(rankI, rankJ));
1781
- for (let m = 0; m < later.maps.length; m++) {
1782
- earlier.maps.push(maps.then(later.maps[m], swap));
1783
- earlier.cards.push(later.cards[m]);
1784
- }
1785
- later.merged = true;
1786
- approximate = true;
1787
- break;
1788
- }
1789
- }
1790
- }
2371
+ const children = dealChildren(maps, previousCards, base, previousWidth, stabilisers[p], merge);
2372
+ for (const child of children) if (child.merged) approximate = true;
1791
2373
  for (const child of children) {
1792
2374
  if (child.merged) continue;
1793
2375
  for (let i = 0; i < previousWidth; i++) level.push(previousCards[base + i]);
@@ -1830,6 +2412,53 @@ function enumerateRunouts(board, symmetries, merge) {
1830
2412
  initial: [...board]
1831
2413
  };
1832
2414
  }
2415
+ var usedScratch = new Uint8Array(DECK);
2416
+ var seenScratch = new Uint8Array(DECK);
2417
+ function dealChildren(maps, cards, base, width, stabiliser, merge) {
2418
+ const used = usedScratch;
2419
+ const seen = seenScratch;
2420
+ used.fill(0);
2421
+ seen.fill(0);
2422
+ for (let i = 0; i < width; i++) used[cards[base + i]] = 1;
2423
+ const children = [];
2424
+ for (let card = 0; card < DECK; card++) {
2425
+ if (used[card] || seen[card]) continue;
2426
+ const child = { card, maps: [], cards: [], fixing: [], merged: false };
2427
+ for (const sigma of stabiliser) {
2428
+ const image = maps.card[sigma][card];
2429
+ if (image === card) child.fixing.push(sigma);
2430
+ if (seen[image]) continue;
2431
+ seen[image] = 1;
2432
+ child.maps.push(image === card ? 0 : maps.inverse(sigma));
2433
+ child.cards.push(image);
2434
+ }
2435
+ children.push(child);
2436
+ }
2437
+ if (merge) {
2438
+ const boardRanks = /* @__PURE__ */ new Set();
2439
+ for (let i = 0; i < width; i++) boardRanks.add(cards[base + i] >> 2);
2440
+ for (let j = 0; j < children.length; j++) {
2441
+ const later = children[j];
2442
+ const rankJ = later.card >> 2;
2443
+ if (boardRanks.has(rankJ)) continue;
2444
+ for (let i = 0; i < j; i++) {
2445
+ const earlier = children[i];
2446
+ if (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;
2447
+ const rankI = earlier.card >> 2;
2448
+ if (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;
2449
+ if (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;
2450
+ const swap = maps.add(rankSwap(rankI, rankJ));
2451
+ for (let m = 0; m < later.maps.length; m++) {
2452
+ earlier.maps.push(maps.then(later.maps[m], swap));
2453
+ earlier.cards.push(later.cards[m]);
2454
+ }
2455
+ later.merged = true;
2456
+ break;
2457
+ }
2458
+ }
2459
+ }
2460
+ return children;
2461
+ }
1833
2462
  function rankSwap(a, b) {
1834
2463
  const out = new Uint8Array(DECK);
1835
2464
  for (let card = 0; card < DECK; card++) {
@@ -1867,11 +2496,13 @@ function resolveBoard(runouts, board) {
1867
2496
  const round = i - start + 1;
1868
2497
  const dealt = runouts.maps.card[map][board[i]];
1869
2498
  let found = -1;
1870
- for (let child = runouts.childStart[round][index]; child < runouts.childStart[round][index + 1] && found < 0; child++) {
2499
+ const children = runouts.childStart[round];
2500
+ const relabel = runouts.orbitMap[round];
2501
+ for (let child = children[index]; child < children[index + 1] && found < 0; child++) {
1871
2502
  for (let m = runouts.orbitStart[round][child]; m < runouts.orbitStart[round][child + 1]; m++) {
1872
2503
  if (runouts.orbitCard[round][m] !== dealt) continue;
1873
2504
  found = child;
1874
- map = runouts.maps.then(map, runouts.orbitMap[round][m]);
2505
+ map = runouts.maps.then(map, relabel[m]);
1875
2506
  break;
1876
2507
  }
1877
2508
  }
@@ -2032,18 +2663,108 @@ var CONTROL = {
2032
2663
  iterWeight: 4,
2033
2664
  ready: 5,
2034
2665
  mode: 6,
2666
+ /** Set, never cleared, once any thread's part of a step threw; see src/worker.ts. */
2667
+ failed: 7,
2035
2668
  size: 8
2036
2669
  };
2037
2670
  var COMMAND = { work: 0, exit: 1 };
2038
2671
 
2039
- // src/index.ts
2672
+ // src/history-merge.ts
2673
+ function interner() {
2674
+ const ids = /* @__PURE__ */ new Map();
2675
+ return (key) => {
2676
+ let id = ids.get(key);
2677
+ if (id === void 0) ids.set(key, id = ids.size);
2678
+ return id;
2679
+ };
2680
+ }
2681
+ function signatures(tree) {
2682
+ const exact = new Int32Array(tree.nodeCount);
2683
+ const exactId = interner();
2684
+ for (let node = tree.nodeCount - 1; node >= 0; node--) {
2685
+ let e = `${tree.kind[node]},${tree.player[node]},${tree.round[node]},${tree.pot[node]},${tree.payoff[node]}`;
2686
+ const first = tree.firstEdge[node];
2687
+ for (let i = 0; i < tree.numEdges[node]; i++) {
2688
+ const edge = first + i;
2689
+ e += `|${tree.edgeAction[edge]}:${tree.edgeTarget[edge]}:${exact[tree.edgeChild[edge]]}`;
2690
+ }
2691
+ exact[node] = exactId(e);
2692
+ }
2693
+ return exact;
2694
+ }
2695
+ function aliasHistories(tree, runouts, options = {}) {
2696
+ const exact = signatures(tree);
2697
+ const alias = new Int32Array(tree.nodeCount);
2698
+ for (let node = 0; node < tree.nodeCount; node++) alias[node] = node;
2699
+ const rootsByRound = Array.from({ length: runouts.rounds }, () => []);
2700
+ for (let node = 0; node < tree.nodeCount; node++) {
2701
+ if (tree.kind[node] !== NodeKind.Chance) continue;
2702
+ const child = tree.edgeChild[tree.firstEdge[node]];
2703
+ if (tree.kind[child] === NodeKind.Decision) rootsByRound[tree.round[child]].push(child);
2704
+ }
2705
+ const walk2 = (rep, member) => {
2706
+ alias[member] = rep;
2707
+ const a = tree.firstEdge[rep];
2708
+ const b = tree.firstEdge[member];
2709
+ for (let i = 0; i < tree.numEdges[rep]; i++) walk2(tree.edgeChild[a + i], tree.edgeChild[b + i]);
2710
+ };
2711
+ const roots = new Int32Array(runouts.rounds);
2712
+ const groups = new Int32Array(runouts.rounds);
2713
+ const last = runouts.rounds - 1;
2714
+ if (last >= 1) {
2715
+ const reps = /* @__PURE__ */ new Map();
2716
+ for (const root of rootsByRound[last]) {
2717
+ if (options.keep?.[root]) continue;
2718
+ const rep = reps.get(exact[root]);
2719
+ if (rep === void 0) reps.set(exact[root], root);
2720
+ else walk2(rep, root);
2721
+ }
2722
+ groups[last] = reps.size;
2723
+ }
2724
+ for (let round = 1; round < runouts.rounds; round++) roots[round] = rootsByRound[round].length;
2725
+ return { alias, roots, groups };
2726
+ }
2727
+
2728
+ // src/betting.ts
2040
2729
  var DEFAULT_CHIP_SCALE = 100;
2730
+ function betRows(config2, rounds) {
2731
+ const rowsFor = (sizes, who) => {
2732
+ const expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;
2733
+ if (expanded.length !== rounds) {
2734
+ throw new Error(
2735
+ `${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`
2736
+ );
2737
+ }
2738
+ return expanded;
2739
+ };
2740
+ return isPerPlayer(config2.betSizes) ? { oop: rowsFor(config2.betSizes.oop, "oop "), ip: rowsFor(config2.betSizes.ip, "ip ") } : rowsFor(config2.betSizes, "");
2741
+ }
2742
+ function treeConfig(config2, rows) {
2743
+ const chipScale = config2.chipScale ?? DEFAULT_CHIP_SCALE;
2744
+ return {
2745
+ potUnits: Math.round(config2.pot * chipScale),
2746
+ stackUnits: Math.round(config2.stack * chipScale),
2747
+ betSizes: rows,
2748
+ raiseSizes: config2.raiseSizes,
2749
+ maxRaises: config2.maxRaises ?? 1,
2750
+ allowAllIn: config2.allowAllIn ?? false,
2751
+ allInThreshold: config2.allInThreshold,
2752
+ noDonk: config2.noDonk,
2753
+ mergeSizes: config2.mergeSizes,
2754
+ removeActions: config2.removeActions,
2755
+ thinSizes: config2.thinSizes,
2756
+ chipScale,
2757
+ minRaiseUnits: chipScale
2758
+ };
2759
+ }
2760
+
2761
+ // src/index.ts
2041
2762
  var OPS_PER_SECOND = 2e8;
2042
2763
  var SpotTooLargeError = class extends Error {
2043
2764
  estimate;
2044
2765
  constructor(estimate, maxBytes) {
2045
2766
  super(
2046
- `This spot needs ~${formatBytes(estimate.compressedBytes)} even at 16-bit precision, but the limit is ${formatBytes(maxBytes)}.
2767
+ (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)}.
2047
2768
  ${estimate.decisionNodes} decision nodes x up to ${estimate.runouts.toLocaleString()} runouts x ${Math.max(...estimate.combos)} combos.
2048
2769
  ` + (estimate.suggestions.length ? `Try:
2049
2770
  ${estimate.suggestions.map((s) => ` - ${s}`).join("\n")}
@@ -2073,16 +2794,7 @@ function defineSpot(config2) {
2073
2794
  const rounds = 6 - board.length;
2074
2795
  if (config2.pot <= 0) throw new Error("pot must be positive");
2075
2796
  if (config2.stack <= 0) throw new Error("stack must be positive");
2076
- const rowsFor = (sizes, who) => {
2077
- const expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;
2078
- if (expanded.length !== rounds) {
2079
- throw new Error(
2080
- `${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`
2081
- );
2082
- }
2083
- return expanded;
2084
- };
2085
- const rows = isPerPlayer(config2.betSizes) ? { oop: rowsFor(config2.betSizes.oop, "oop "), ip: rowsFor(config2.betSizes.ip, "ip ") } : rowsFor(config2.betSizes, "");
2797
+ const rows = betRows(config2, rounds);
2086
2798
  const onBoard = new Set(board);
2087
2799
  const trim = (range, who) => {
2088
2800
  const weights2 = typeof range === "string" ? parseRange(range) : Float64Array.from(range);
@@ -2112,34 +2824,21 @@ function defineSpot(config2) {
2112
2824
  buildPlayerIndex(trim(config2.ip, "in-position"))
2113
2825
  ];
2114
2826
  const symmetries = config2.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights]);
2115
- const runouts = enumerateRunouts(
2116
- board,
2117
- symmetries,
2118
- config2.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config2.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config2.runoutBuckets) : void 0
2119
- );
2120
- const tree = buildTree(
2121
- {
2122
- potUnits: Math.round(config2.pot * chipScale),
2123
- stackUnits: Math.round(config2.stack * chipScale),
2124
- betSizes: rows,
2125
- raiseSizes: config2.raiseSizes,
2126
- maxRaises: config2.maxRaises ?? 1,
2127
- allowAllIn: config2.allowAllIn ?? false,
2128
- allInThreshold: config2.allInThreshold,
2129
- noDonk: config2.noDonk,
2130
- mergeSizes: config2.mergeSizes,
2131
- chipScale,
2132
- minRaiseUnits: chipScale
2133
- },
2134
- runouts
2135
- );
2136
- const layout2 = buildLayout(tree, runouts, players, 4);
2827
+ const merge = config2.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config2.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config2.runoutBuckets) : void 0;
2828
+ const runouts = enumerateRunouts(board, symmetries, merge);
2829
+ const tree = buildTree(treeConfig(config2, rows), runouts);
2830
+ const historyAlias = config2.shareHistories ? shareHistories(tree, runouts, config2, chipScale) : void 0;
2831
+ const layout2 = buildLayout(tree, runouts, players, 4, historyAlias);
2137
2832
  const last = runouts.rounds - 1;
2138
2833
  const showdownBytes = runouts.counts[last] * (2 * COMBOS + COMBOS + 1) * 2;
2139
2834
  const bytes = layout2.bytes + showdownBytes;
2140
- const compressedBytes = buildLayout(tree, runouts, players, 2).bytes + showdownBytes;
2835
+ const compressedBytes = buildLayout(tree, runouts, players, 2, historyAlias).bytes + showdownBytes;
2836
+ const walkedSlots = layout2.walkedSlots;
2837
+ const compact2 = config2.compactStorage ? compactPlan(config2.compactStorage, runouts.rounds) : null;
2838
+ const compactBytes = compact2 ? buildLayout(tree, runouts, players, 4, historyAlias, compact2).bytes + showdownBytes : null;
2839
+ const needed = compactBytes ?? compressedBytes;
2141
2840
  const suggestions = [];
2142
- if (compressedBytes > maxBytes) {
2841
+ if (needed > maxBytes) {
2143
2842
  const widest = Math.max(...[0, 1].flatMap((p) => forPlayer(rows, p).map((r) => r.length)));
2144
2843
  if (widest > 1) suggestions.push(`use fewer bet sizes (currently up to ${widest} per round)`);
2145
2844
  const raises = [0, 1].flatMap((p) => [forPlayer(config2.maxRaises ?? 1, p)].flat());
@@ -2155,8 +2854,9 @@ function defineSpot(config2) {
2155
2854
  totalSlots: layout2.totalSlots,
2156
2855
  bytes,
2157
2856
  compressedBytes,
2158
- secondsPerThousandIterations: layout2.totalSlots * 4 * 1e3 / OPS_PER_SECOND,
2159
- fits: compressedBytes <= maxBytes,
2857
+ compactBytes,
2858
+ secondsPerThousandIterations: walkedSlots * 4 * 1e3 / OPS_PER_SECOND,
2859
+ fits: needed <= maxBytes,
2160
2860
  suggestions
2161
2861
  };
2162
2862
  if (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);
@@ -2170,12 +2870,74 @@ function defineSpot(config2) {
2170
2870
  potUnits: Math.round(config2.pot * chipScale),
2171
2871
  stackUnits: Math.round(config2.stack * chipScale),
2172
2872
  source: config2,
2873
+ ...historyAlias ? { historyAlias } : {},
2173
2874
  resolveBoard(cards) {
2174
2875
  return resolveBoard(runouts, typeof cards === "string" ? parseCards(cards) : cards);
2175
2876
  }
2176
2877
  };
2177
2878
  }
2879
+ function shareHistories(tree, runouts, config2, chipScale) {
2880
+ const asked = config2.shareHistories === true ? {} : config2.shareHistories || {};
2881
+ const keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : void 0;
2882
+ return aliasHistories(tree, runouts, { keep }).alias;
2883
+ }
2884
+ function keptNodes(tree, chipScale, lines) {
2885
+ const parent = new Int32Array(tree.nodeCount).fill(-1);
2886
+ const paths = new Array(tree.nodeCount);
2887
+ paths[0] = "(root)";
2888
+ for (let node = 0; node < tree.nodeCount; node++) {
2889
+ for (let e = 0; e < tree.numEdges[node]; e++) {
2890
+ const edge = tree.firstEdge[node] + e;
2891
+ const child = tree.edgeChild[edge];
2892
+ parent[child] = node;
2893
+ const step = tree.kind[node] === NodeKind.Decision ? actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], chipScale) : "/";
2894
+ paths[child] = node === 0 ? step : `${paths[node]} ${step}`;
2895
+ }
2896
+ }
2897
+ const listed = new Set(lines);
2898
+ const missing = new Set(lines);
2899
+ const marks = new Uint8Array(tree.nodeCount);
2900
+ for (let node = 0; node < tree.nodeCount; node++) {
2901
+ if (listed.has(paths[node])) {
2902
+ missing.delete(paths[node]);
2903
+ marks[node] = 1;
2904
+ } else if (parent[node] >= 0 && marks[parent[node]]) {
2905
+ marks[node] = 1;
2906
+ }
2907
+ }
2908
+ if (missing.size > 0) {
2909
+ throw new Error(`shareHistories.keepLines: no node of this tree has the path ${[...missing].map((l) => `"${l}"`).join(", ")}`);
2910
+ }
2911
+ for (let node = tree.nodeCount - 1; node > 0; node--) if (marks[node]) marks[parent[node]] = 1;
2912
+ return marks;
2913
+ }
2178
2914
  var PRECISION_BYTES = { f64: 8, f32: 4, i16: 2 };
2915
+ function compactPlan(settings, rounds) {
2916
+ const from = settings.from ?? 0;
2917
+ if (!Number.isInteger(from) || from < 0 || from >= rounds) {
2918
+ throw new Error(`compactStorage.from must be a round of this spot, 0 to ${rounds - 1}; got ${from}`);
2919
+ }
2920
+ const chunkBytes = settings.chunkBytes ?? 2 ** 30;
2921
+ if (!Number.isInteger(chunkBytes) || chunkBytes < 1) {
2922
+ throw new Error(`compactStorage.chunkBytes must be a positive whole number of bytes; got ${chunkBytes}`);
2923
+ }
2924
+ const steps = settings.steps ?? 127;
2925
+ if (!Number.isInteger(steps) || steps < 1 || steps > 127) {
2926
+ throw new Error(`compactStorage.steps must be an integer from 1 to 127; got ${steps}`);
2927
+ }
2928
+ if (settings.sums !== false && (settings.blockScale || settings.float)) {
2929
+ throw new Error("compactStorage.sums keeps a scale per hand, so blockScale and float need sums: false");
2930
+ }
2931
+ return {
2932
+ from,
2933
+ steps,
2934
+ perHand: !settings.blockScale && !settings.float,
2935
+ stochastic: !settings.nearest,
2936
+ float: settings.float === true,
2937
+ chunkBytes,
2938
+ sums: settings.sums ?? true
2939
+ };
2940
+ }
2179
2941
  var DEFAULT_BUCKET_GAP = 1;
2180
2942
  function rangeRankMerge(players, maxGap) {
2181
2943
  const allowed = new Uint8Array(13 * 13);
@@ -2206,15 +2968,23 @@ function makeSumStore(precision2, buffer) {
2206
2968
 
2207
2969
  // src/worker.ts
2208
2970
  var setup = workerData;
2209
- var { config, dcfr, precision, simd } = setup.payload;
2971
+ var { config, dcfr, precision, simd, compact, approximations } = setup.payload;
2210
2972
  var spot = defineSpot(config);
2211
2973
  var relevant = new Uint8Array(COMBOS);
2212
2974
  for (const combo of spot.players[0].combos) relevant[combo] = 1;
2213
2975
  for (const combo of spot.players[1].combos) relevant[combo] = 1;
2214
2976
  var weights = runoutWeights(spot.runouts);
2215
- var layout = buildLayout(spot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision]);
2977
+ var layout = buildLayout(
2978
+ spot.tree,
2979
+ spot.runouts,
2980
+ spot.players,
2981
+ PRECISION_BYTES[precision],
2982
+ spot.historyAlias,
2983
+ compact ?? void 0
2984
+ );
2216
2985
  var showdown = buildShowdownTable(spot.runouts, relevant);
2217
2986
  var active = buildActiveLists(spot.runouts, spot.players, showdown);
2987
+ var hands = buildHandSpace(spot.runouts, spot.players, active);
2218
2988
  var ctx = {
2219
2989
  tree: spot.tree,
2220
2990
  runouts: spot.runouts,
@@ -2225,10 +2995,16 @@ var ctx = {
2225
2995
  strategySum: makeSumStore(precision, setup.strategySum),
2226
2996
  regretScale: setup.regretScale ? new Float64Array(setup.regretScale) : null,
2227
2997
  sumScale: setup.sumScale ? new Float64Array(setup.sumScale) : null,
2998
+ compact,
2999
+ compactRegret: setup.compactRegret?.map((chunk) => compact?.float ? new Float32Array(chunk) : new Int8Array(chunk)) ?? null,
3000
+ handShift: setup.handShift?.map((chunk) => new Uint8Array(chunk)) ?? null,
3001
+ compactSum: setup.compactSum?.map((chunk) => new Uint8Array(chunk)) ?? null,
3002
+ sumShift: setup.sumShift?.map((chunk) => new Uint8Array(chunk)) ?? null,
3003
+ compactScale: setup.compactScale ? new Float64Array(setup.compactScale) : null,
2228
3004
  scratch: makeTerminalScratch(),
2229
3005
  chipScale: spot.chipScale,
2230
3006
  active,
2231
- hands: buildHandSpace(spot.runouts, spot.players, active),
3007
+ hands,
2232
3008
  runoutWeight: weights,
2233
3009
  totalMass: matchupMass(spot.players[0].weights, spot.players[1].weights) * weights[0],
2234
3010
  dcfr,
@@ -2240,8 +3016,19 @@ var ctx = {
2240
3016
  chanceOverride: null,
2241
3017
  entryIndexOf: null,
2242
3018
  expandOrbits: false,
2243
- simd
3019
+ simd,
3020
+ // This worker's runouts are its own, so are their blocks and the marks on them.
3021
+ discounted: layout.shared ? new Int32Array(layout.blocks) : null
2244
3022
  };
3023
+ var samplingOptions = approximations?.chanceSampling;
3024
+ if (samplingOptions && setup.sampling) {
3025
+ const [baseline, lastWalk, lastUpdate] = setup.sampling;
3026
+ ctx.sampling = makeSampling(planSampling(spot.tree, spot.runouts, active, layout, samplingOptions), {
3027
+ baseline: new Float32Array(baseline),
3028
+ lastWalk: new Int32Array(lastWalk),
3029
+ lastUpdate: new Int32Array(lastUpdate)
3030
+ });
3031
+ }
2245
3032
  var solver = makeSolver(ctx);
2246
3033
  var control = new Int32Array(setup.control);
2247
3034
  var exchange = new Float64Array(setup.exchange);
@@ -2259,17 +3046,23 @@ for (; ; ) {
2259
3046
  const mode = Atomics.load(control, CONTROL.mode);
2260
3047
  const traverser = Atomics.load(control, CONTROL.traverser);
2261
3048
  const iterWeight = Atomics.load(control, CONTROL.iterWeight);
2262
- for (let entry = 0; entry < setup.plan.entryNodes.length; entry++) {
2263
- const node = setup.plan.entryNodes[entry];
2264
- for (let i = 0; i < COMBOS; i++) {
2265
- reachMe[i] = exchange[entry * 2 * COMBOS + i];
2266
- reachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];
3049
+ try {
3050
+ for (let entry = 0; entry < setup.plan.entryNodes.length; entry++) {
3051
+ const node = setup.plan.entryNodes[entry];
3052
+ for (let i = 0; i < COMBOS; i++) {
3053
+ reachMe[i] = exchange[entry * 2 * COMBOS + i];
3054
+ reachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];
3055
+ }
3056
+ const value = solver.traverseChance(mode, traverser, iterWeight, node, reachMe, reachOpp);
3057
+ for (let i = 0; i < COMBOS; i++) exchange[partialBase + entry * COMBOS + i] = value[i];
2267
3058
  }
2268
- const value = solver.traverseChance(mode, traverser, iterWeight, node, reachMe, reachOpp);
2269
- for (let i = 0; i < COMBOS; i++) exchange[partialBase + entry * COMBOS + i] = value[i];
3059
+ } catch (error) {
3060
+ Atomics.store(control, CONTROL.failed, 1);
3061
+ throw error;
3062
+ } finally {
3063
+ Atomics.add(control, CONTROL.done, 1);
3064
+ Atomics.notify(control, CONTROL.done);
2270
3065
  }
2271
- Atomics.add(control, CONTROL.done, 1);
2272
- Atomics.notify(control, CONTROL.done);
2273
3066
  }
2274
3067
  parentPort?.close();
2275
3068
  //# sourceMappingURL=worker.js.map