poker-flopsolve 0.4.1 → 0.5.0-beta.1

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);
@@ -500,7 +576,7 @@ function buildTree(config2, runouts) {
500
576
  if (raiseSize < minimum) target = Math.min(theirs + minimum, cap);
501
577
  return target;
502
578
  };
503
- const buildDecision = (state) => {
579
+ const buildDecision = (state, path) => {
504
580
  const me = state.toAct;
505
581
  const opp = 1 - me;
506
582
  const mine = state.invested[me];
@@ -519,6 +595,7 @@ function buildTree(config2, runouts) {
519
595
  const donk = noDonk[state.round] && me === 0 && owed === 0 && state.aggressions === 0 && state.previousAggressor === 1;
520
596
  if (state.aggressions < maxRaises[me][state.round] && myRemaining > owed && !donk) {
521
597
  const seen = /* @__PURE__ */ new Set();
598
+ const sized = [];
522
599
  const myRaises = raiseSizes[me];
523
600
  const sizes = owed > 0 && myRaises ? [...myRaises[state.round]] : [...betSizes[me][state.round] ?? []].filter((size) => !(typeof size === "object" && "times" in size));
524
601
  if (allowAllIn[me][state.round]) sizes.push("allin");
@@ -530,10 +607,17 @@ function buildTree(config2, runouts) {
530
607
  if (target === null || seen.has(target)) continue;
531
608
  seen.add(target);
532
609
  const isShove = target >= stackUnits;
533
- actions.push({
534
- action: isShove ? ActionKind.AllIn : owed > 0 ? ActionKind.Raise : ActionKind.Bet,
535
- target
536
- });
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);
537
621
  }
538
622
  }
539
623
  const base = edgeChild.length;
@@ -545,6 +629,7 @@ function buildTree(config2, runouts) {
545
629
  edgeChild.push(-1);
546
630
  }
547
631
  actions.forEach((entry, i) => {
632
+ const line = remove ? extend(path, actionLabel(entry.action, entry.target, chipScale)) : "";
548
633
  const invested = me === 0 ? [entry.target, theirs] : [theirs, entry.target];
549
634
  let child;
550
635
  if (entry.action === ActionKind.Fold) {
@@ -552,7 +637,7 @@ function buildTree(config2, runouts) {
552
637
  child = addNode(NodeKind.TerminalFold, -1, state.round, total, value);
553
638
  } else if (entry.action === ActionKind.Check || entry.action === ActionKind.Call) {
554
639
  const closed = invested[0] === invested[1] && state.acted + 1 >= 2;
555
- 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);
556
641
  } else {
557
642
  child = buildDecision({
558
643
  round: state.round,
@@ -563,8 +648,9 @@ function buildTree(config2, runouts) {
563
648
  acted: state.acted + 1,
564
649
  base: state.base,
565
650
  aggressor: me,
566
- previousAggressor: state.previousAggressor
567
- });
651
+ previousAggressor: state.previousAggressor,
652
+ streetsBet: state.streetsBet
653
+ }, line);
568
654
  }
569
655
  edgeChild[base + i] = child;
570
656
  });
@@ -579,8 +665,16 @@ function buildTree(config2, runouts) {
579
665
  acted: 0,
580
666
  base: 0,
581
667
  aggressor: -1,
582
- previousAggressor: -1
583
- });
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
+ }
584
678
  const decisionNodes = [];
585
679
  for (let i = 0; i < kind.length; i++) if (kind[i] === NodeKind.Decision) decisionNodes.push(i);
586
680
  return {
@@ -630,19 +724,20 @@ function makeBuffers(ctx2, width) {
630
724
  hands: make(() => new Uint16Array(width)),
631
725
  strategy: make(() => new Float64Array(actions * COMBOS)),
632
726
  rank: new Int32Array(COMBOS),
633
- position: new Int32Array(COMBOS)
727
+ position: new Int32Array(COMBOS).fill(-1),
728
+ at: make(() => new Int32Array(width))
634
729
  };
635
730
  }
636
- function pairValues(ctx2, node, board, traverser, hands, handReach, live, liveCount) {
637
- const result = new Float64Array(hands.length * COMBOS);
638
- if (hands.length === 0) return result;
639
- 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);
640
735
  const buffers = makeBuffers(ctx2, width);
641
736
  const mine = new Uint16Array(liveCount);
642
737
  let mineCount = 0;
643
738
  for (let i = 0; i < liveCount; i++) if (ctx2.players[traverser].slot[live[i]] >= 0) mine[mineCount++] = live[i];
644
- for (let start = 0; start < hands.length; start += width) {
645
- 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));
646
741
  const colReach = buffers.colReach[0];
647
742
  const cols = buffers.cols[0];
648
743
  let count = 0;
@@ -659,7 +754,7 @@ function pairValues(ctx2, node, board, traverser, hands, handReach, live, liveCo
659
754
  }
660
755
  return result;
661
756
  }
662
- 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) {
663
758
  const { tree, runouts } = ctx2;
664
759
  const out = buffers.value[depth];
665
760
  const kind = tree.kind[node];
@@ -674,8 +769,8 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
674
769
  const weight = signed * ctx2.runoutWeight[tree.round[node]] / ctx2.chipScale;
675
770
  for (let c = 0; c < colCount; c++) {
676
771
  const k = cols[c];
677
- const a = cards[hands[k] * 2];
678
- const b = cards[hands[k] * 2 + 1];
772
+ const a = cards[hands2[k] * 2];
773
+ const b = cards[hands2[k] * 2 + 1];
679
774
  const v = weight * colReach[k];
680
775
  const row = k * COMBOS;
681
776
  for (let i = 0; i < liveCount; i++) {
@@ -700,7 +795,7 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
700
795
  }
701
796
  for (let c = 0; c < colCount; c++) {
702
797
  const k = cols[c];
703
- const theirs = hands[k];
798
+ const theirs = hands2[k];
704
799
  const a = cards[theirs * 2];
705
800
  const b = cards[theirs * 2 + 1];
706
801
  const strength = rank[theirs];
@@ -727,28 +822,31 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
727
822
  const childLive = buffers.live[depth];
728
823
  const childCols2 = buffers.cols[depth + 1];
729
824
  const mappedHands = buffers.hands[depth];
730
- 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];
731
828
  for (let m = orbitStart[childBoard]; m < orbitStart[childBoard + 1]; m++) {
732
- 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];
733
830
  const map = runouts.maps.combo[runouts.orbitMap[nextRound][m]];
831
+ const blocked = (combo) => cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt;
734
832
  let childCount = 0;
735
833
  for (let i = 0; i < liveCount; i++) {
736
834
  const combo = live[i];
737
- if (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;
835
+ if (blocked(combo)) continue;
738
836
  childLive[childCount++] = map[combo];
739
837
  }
740
838
  let childColCount = 0;
741
839
  for (let c = 0; c < colCount; c++) {
742
840
  const k = cols[c];
743
- if (cards[hands[k] * 2] !== dealt && cards[hands[k] * 2 + 1] !== dealt) childCols2[childColCount++] = k;
841
+ if (!blocked(hands2[k])) childCols2[childColCount++] = k;
744
842
  }
745
843
  if (childColCount === 0) continue;
746
- 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]];
747
845
  const value = walk(
748
846
  ctx2,
749
847
  buffers,
750
848
  traverser,
751
- mappedHands.subarray(0, hands.length),
849
+ mappedHands.subarray(0, hands2.length),
752
850
  child,
753
851
  childBoard,
754
852
  colReach,
@@ -762,7 +860,7 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
762
860
  const row = childCols2[c] * COMBOS;
763
861
  for (let i = 0; i < liveCount; i++) {
764
862
  const combo = live[i];
765
- if (cards[combo * 2] === dealt || cards[combo * 2 + 1] === dealt) continue;
863
+ if (blocked(combo)) continue;
766
864
  out[row + combo] += value[row + map[combo]];
767
865
  }
768
866
  }
@@ -775,21 +873,19 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
775
873
  const owner = tree.player[node];
776
874
  const lists = ctx2.active;
777
875
  const listSlot = (lists.roundBase[tree.round[node]] + board) * 2 + owner;
778
- const active2 = lists.list;
779
876
  const activeFrom = lists.start[listSlot];
780
877
  const activeCount = lists.count[listSlot];
781
878
  const stride = activeCount;
782
879
  const slotBase = ctx2.layout.offset[node] + actions * ctx2.layout.rowStart[listSlot];
783
880
  const strategy = buffers.strategy[depth];
784
- averageStrategy(ctx2.strategySum, slotBase, actions, stride, strategy, ctx2.regret);
881
+ storedStrategy(ctx2, node, slotBase, actions, stride, strategy);
785
882
  if (owner === traverser) {
786
883
  for (let a = 0; a < actions; a++) {
787
- const offset = a * COMBOS;
788
884
  const value = walk(
789
885
  ctx2,
790
886
  buffers,
791
887
  traverser,
792
- hands,
888
+ hands2,
793
889
  tree.edgeChild[edgeBase + a],
794
890
  board,
795
891
  colReach,
@@ -802,8 +898,11 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
802
898
  for (let c = 0; c < colCount; c++) {
803
899
  const row = cols[c] * COMBOS;
804
900
  for (let i = 0; i < activeCount; i++) {
805
- const combo = active2[activeFrom + i];
806
- 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
+ }
807
906
  }
808
907
  }
809
908
  }
@@ -812,13 +911,15 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
812
911
  const childReach = buffers.colReach[depth + 1];
813
912
  const childCols = buffers.cols[depth + 1];
814
913
  const position = buffers.position;
815
- 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);
816
918
  for (let a = 0; a < actions; a++) {
817
- const offset = a * COMBOS;
818
919
  let childCount = 0;
819
920
  for (let c = 0; c < colCount; c++) {
820
921
  const k = cols[c];
821
- const r = colReach[k] * strategy[a * stride + position[hands[k]]];
922
+ const r = at[k] < 0 ? 0 : colReach[k] * strategy[a * stride + at[k]];
822
923
  childReach[k] = r;
823
924
  if (r !== 0) childCols[childCount++] = k;
824
925
  }
@@ -827,7 +928,7 @@ function walk(ctx2, buffers, traverser, hands, node, board, colReach, cols, colC
827
928
  ctx2,
828
929
  buffers,
829
930
  traverser,
830
- hands,
931
+ hands2,
831
932
  tree.edgeChild[edgeBase + a],
832
933
  board,
833
934
  childReach,
@@ -907,58 +1008,243 @@ function buildPlayerIndex(weights2) {
907
1008
  }
908
1009
  return { combos: Uint16Array.from(combos), count: combos.length, slot, weights: weights2 };
909
1010
  }
910
- 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) {
911
1021
  const roundBase = new Int32Array(runouts.rounds + 1);
912
1022
  for (let round = 0; round < runouts.rounds; round++) roundBase[round + 1] = roundBase[round] + runouts.counts[round];
913
1023
  const rowStart = new Int32Array(roundBase[runouts.rounds] * 2);
914
1024
  const totals = new Int32Array(runouts.rounds * 2);
915
1025
  const onBoard = new Uint8Array(DECK);
916
1026
  for (let round = 0; round < runouts.rounds; round++) {
917
- const width = runouts.width[round];
1027
+ const width2 = runouts.width[round];
918
1028
  const cards = runouts.cards[round];
919
1029
  for (let board = 0; board < runouts.counts[round]; board++) {
920
1030
  onBoard.fill(0);
921
- 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;
922
1032
  for (let player = 0; player < 2; player++) {
923
1033
  const index = players[player];
924
1034
  let live = 0;
925
1035
  for (let i = 0; i < index.count; i++) {
926
1036
  const combo = index.combos[i];
927
- 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++;
928
1040
  }
929
1041
  rowStart[(roundBase[round] + board) * 2 + player] = totals[round * 2 + player];
930
1042
  totals[round * 2 + player] += live;
931
1043
  }
932
1044
  }
933
1045
  }
934
- const offset = new Int32Array(tree.nodeCount).fill(-1);
1046
+ const offset = new Float64Array(tree.nodeCount).fill(-1);
935
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;
936
1055
  let total = 0;
1056
+ let compactSlots = 0;
1057
+ let compactHands = 0;
937
1058
  let blocks = 0;
938
1059
  let maxActions = 0;
1060
+ let shared = false;
1061
+ let walked = 0;
939
1062
  for (let i = 0; i < tree.decisionNodes.length; i++) {
940
1063
  const node = tree.decisionNodes[i];
941
1064
  const actions = tree.numEdges[node];
942
1065
  if (actions > maxActions) maxActions = actions;
943
- 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
+ }
944
1080
  blockOffset[node] = blocks;
945
- total += actions * totals[tree.round[node] * 2 + tree.player[node]];
946
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
+ }
947
1107
  }
948
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);
949
1110
  return {
950
- offset,
1111
+ offset: Math.max(total, ...chunkSlots) <= INT32_MAX ? Int32Array.from(offset) : offset,
951
1112
  blockOffset,
952
1113
  blocks,
953
1114
  totalSlots: total,
1115
+ walkedSlots: walked,
954
1116
  maxActions,
955
1117
  rowStart,
956
1118
  roundBase,
957
- 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
958
1130
  };
959
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
+ }
960
1139
  var REGRET_STEPS = 32767;
961
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
+ }
962
1248
  function runoutWeights(runouts) {
963
1249
  const weights2 = new Float64Array(runouts.rounds).fill(1);
964
1250
  for (let round = 0; round < runouts.rounds; round++) {
@@ -997,15 +1283,22 @@ function buildActiveLists(runouts, players, showdown2 = null) {
997
1283
  const slots = roundBase[runouts.rounds] * 2;
998
1284
  const start = new Int32Array(slots);
999
1285
  const count = new Uint16Array(slots);
1286
+ const packedSlot = new Uint8Array(slots);
1000
1287
  const entries = [];
1001
1288
  const entrySlots = [];
1289
+ const memberStart = [];
1290
+ const members = [];
1002
1291
  const onBoard = new Uint8Array(DECK);
1292
+ const seen = new Uint8Array(COMBOS);
1003
1293
  for (let round = 0; round < runouts.rounds; round++) {
1004
1294
  const width = runouts.width[round];
1005
1295
  const cards = runouts.cards[round];
1296
+ const stabStart = runouts.stabiliserStart[round];
1297
+ const stabMap = runouts.stabiliserMap[round];
1006
1298
  for (let board = 0; board < runouts.counts[round]; board++) {
1007
1299
  onBoard.fill(0);
1008
1300
  for (let i = 0; i < width; i++) onBoard[cards[board * width + i]] = 1;
1301
+ const symmetric = stabStart[board + 1] - stabStart[board] > 1;
1009
1302
  for (let player = 0; player < 2; player++) {
1010
1303
  const index = players[player];
1011
1304
  const slot = (roundBase[round] + board) * 2 + player;
@@ -1014,6 +1307,7 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1014
1307
  for (let i = 0; i < index.count; i++) {
1015
1308
  const combo = index.combos[i];
1016
1309
  if (onBoard[COMBO_CARDS[combo * 2]] || onBoard[COMBO_CARDS[combo * 2 + 1]]) continue;
1310
+ if (symmetric && !orbitLeader(runouts, round, board, combo)) continue;
1017
1311
  here.push(i);
1018
1312
  }
1019
1313
  if (showdown2 !== null && round === runouts.rounds - 1) {
@@ -1021,47 +1315,42 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1021
1315
  here.sort((x, y) => group[index.combos[x]] - group[index.combos[y]] || x - y);
1022
1316
  }
1023
1317
  for (const i of here) {
1024
- entries.push(index.combos[i]);
1318
+ const combo = index.combos[i];
1319
+ entries.push(combo);
1025
1320
  entrySlots.push(i);
1026
- }
1027
- count[slot] = entries.length - start[slot];
1028
- }
1029
- }
1030
- }
1031
- const tieStart = new Int32Array(slots + 1);
1032
- const ties = [];
1033
- for (let round = 0; round < runouts.rounds; round++) {
1034
- const stabStart = runouts.stabiliserStart[round];
1035
- const stabMap = runouts.stabiliserMap[round];
1036
- for (let board = 0; board < runouts.counts[round]; board++) {
1037
- for (let player = 0; player < 2; player++) {
1038
- const slot = (roundBase[round] + board) * 2 + player;
1039
- tieStart[slot] = ties.length;
1040
- if (stabStart[board + 1] - stabStart[board] < 2) continue;
1041
- const position = /* @__PURE__ */ new Map();
1042
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) position.set(entries[e], e - start[slot]);
1043
- const seen = new Uint8Array(count[slot]);
1044
- for (let e = start[slot]; e < start[slot] + count[slot]; e++) {
1045
- if (seen[e - start[slot]]) continue;
1046
- const members = [];
1047
- for (let k = stabStart[board]; k < stabStart[board + 1]; k++) {
1048
- const image = position.get(runouts.maps.combo[stabMap[k]][entries[e]]);
1049
- 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;
1050
1328
  seen[image] = 1;
1051
1329
  members.push(image);
1330
+ packedSlot[slot] = 1;
1052
1331
  }
1053
- 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;
1054
1333
  }
1334
+ count[slot] = entries.length - start[slot];
1055
1335
  }
1056
1336
  }
1057
1337
  }
1058
- tieStart[slots] = ties.length;
1338
+ memberStart.push(members.length);
1059
1339
  const list = Uint16Array.from(entries);
1060
1340
  const cardA = new Uint8Array(list.length);
1061
1341
  const cardB = new Uint8Array(list.length);
1342
+ const multiplicity = new Float64Array(list.length);
1062
1343
  for (let e = 0; e < list.length; e++) {
1063
1344
  cardA[e] = COMBO_CARDS[list[e] * 2];
1064
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];
1065
1354
  }
1066
1355
  const strength = new Int32Array(list.length);
1067
1356
  if (showdown2 !== null) {
@@ -1080,11 +1369,15 @@ function buildActiveLists(runouts, players, showdown2 = null) {
1080
1369
  list,
1081
1370
  slot: Uint16Array.from(entrySlots),
1082
1371
  roundBase,
1083
- tieStart,
1084
- ties: Int32Array.from(ties),
1085
1372
  cardA,
1086
1373
  cardB,
1087
- strength
1374
+ strength,
1375
+ packed: packedSlot,
1376
+ multiplicity,
1377
+ memberStart: Int32Array.from(memberStart),
1378
+ memberCombo,
1379
+ memberA,
1380
+ memberB
1088
1381
  };
1089
1382
  }
1090
1383
  var strengthScratch = new Int32Array(COMBOS);
@@ -1098,20 +1391,6 @@ function strengthOn(table, board) {
1098
1391
  }
1099
1392
  return strengthScratch;
1100
1393
  }
1101
- function tieMirrors(store, slotBase, actions, stride, ties, from, to, integer) {
1102
- for (let a = 0; a < actions; a++) {
1103
- const row = slotBase + a * stride;
1104
- for (let k = from; k < to; ) {
1105
- const size = ties[k];
1106
- let sum = 0;
1107
- for (let j = 1; j <= size; j++) sum += store[row + ties[k + j]];
1108
- let mean = sum / size;
1109
- if (integer) mean = Math.round(mean);
1110
- for (let j = 1; j <= size; j++) store[row + ties[k + j]] = mean;
1111
- k += size + 1;
1112
- }
1113
- }
1114
- }
1115
1394
  function makeBuffers2(tree, maxActions, simd2) {
1116
1395
  const depth = treeDepth2(tree) + 2;
1117
1396
  const make = (factory) => Array.from({ length: depth }, factory);
@@ -1157,7 +1436,7 @@ function dcfrFactors(t) {
1157
1436
  keepSum: ((t - 1) / t) ** DCFR_GAMMA
1158
1437
  };
1159
1438
  }
1160
- var Mode = { Train: 0, BestResponse: 1, Average: 2 };
1439
+ var Mode = { Train: 0, BestResponse: 1, Average: 2, Current: 3 };
1161
1440
  function normalise(source, base, actions, count, strategy) {
1162
1441
  const uniform = 1 / actions;
1163
1442
  for (let i = 0; i < count; i++) {
@@ -1176,6 +1455,20 @@ function normalise(source, base, actions, count, strategy) {
1176
1455
  }
1177
1456
  }
1178
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
+ }
1179
1472
  function regretMatch(regret, base, actions, count, strategy) {
1180
1473
  normalise(regret, base, actions, count, strategy);
1181
1474
  }
@@ -1225,7 +1518,27 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1225
1518
  if (kind === NodeKind.TerminalFold) {
1226
1519
  const signed = traverser === 0 ? tree.payoff[node] : -tree.payoff[node];
1227
1520
  const weight = ctx2.runoutWeight[round] / ctx2.chipScale;
1228
- 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
+ }
1229
1542
  foldValuesHands(
1230
1543
  reachOpp2,
1231
1544
  lists.cardA,
@@ -1234,8 +1547,8 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1234
1547
  oppCount,
1235
1548
  myFrom,
1236
1549
  myCount,
1237
- hands.same,
1238
- hands.sameStart[mySlot],
1550
+ hands2.same,
1551
+ hands2.sameStart[mySlot],
1239
1552
  signed * weight,
1240
1553
  buffers.cardSums,
1241
1554
  out
@@ -1244,6 +1557,25 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1244
1557
  }
1245
1558
  if (kind === NodeKind.TerminalShowdown) {
1246
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
+ }
1247
1579
  showdownValuesHands(
1248
1580
  reachOpp2,
1249
1581
  lists.cardA,
@@ -1283,10 +1615,13 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1283
1615
  const childMe = buffers.reachFor[traverser][depth];
1284
1616
  const childOpp = buffers.reachFor[opponent][depth];
1285
1617
  const sharded = nextRound === ctx2.shardRound;
1286
- const first = runouts.childStart[nextRound][board];
1287
- const last = runouts.childStart[nextRound][board + 1];
1618
+ const starts = runouts.childStart[nextRound];
1619
+ const first = starts[board];
1620
+ const last = starts[board + 1];
1288
1621
  const from = sharded && ctx2.shardStart > first ? ctx2.shardStart : first;
1289
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;
1290
1625
  for (let childBoard = from; childBoard < to; childBoard++) {
1291
1626
  const childMySlot = (lists.roundBase[nextRound] + childBoard) * 2 + traverser;
1292
1627
  const childOppSlot = (lists.roundBase[nextRound] + childBoard) * 2 + opponent;
@@ -1297,15 +1632,40 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1297
1632
  let value = null;
1298
1633
  for (let m = firstMember; m < membersEnd; m++) {
1299
1634
  const upMe = upStart[m * 2 + traverser];
1300
- 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) {
1301
1653
  const upOpp = upStart[m * 2 + opponent];
1302
1654
  for (let k = 0; k < nMe; k++) childMe[k] = reachMe2[up[upMe + k]];
1303
1655
  for (let k = 0; k < nOpp; k++) childOpp[k] = reachOpp2[up[upOpp + k]];
1304
1656
  value = traverse(ctx2, buffers, mode, traverser, iterWeight, child, childBoard, childMe, childOpp, depth + 1);
1305
1657
  }
1306
- 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
+ }
1307
1664
  }
1308
1665
  }
1666
+ if (lists.packed[mySlot]) {
1667
+ for (let i = 0; i < myCount; i++) out[i] /= lists.multiplicity[myFrom + i];
1668
+ }
1309
1669
  return out;
1310
1670
  }
1311
1671
  const actions = tree.numEdges[node];
@@ -1318,12 +1678,19 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1318
1678
  const slotBase = ctx2.layout.offset[node] + actions * ctx2.layout.rowStart[listSlot];
1319
1679
  const strategy = buffers.strategy[depth];
1320
1680
  const length = actions * stride;
1321
- 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) {
1322
1687
  const kernels = buffers.kernels;
1323
- kernels.input.set(ctx2.regret.subarray(slotBase, slotBase + length));
1688
+ kernels.input.set(regrets.subarray(slotBase, slotBase + length));
1324
1689
  kernels.regretMatch(strategy, actions, stride);
1325
- } else if (mode === Mode.Train) {
1326
- 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);
1327
1694
  } else if (buffers.kernels !== null) {
1328
1695
  const kernels = buffers.kernels;
1329
1696
  kernels.input.set(ctx2.strategySum.subarray(slotBase, slotBase + length));
@@ -1384,9 +1751,36 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1384
1751
  for (let i = 0; i < myCount; i++) out[i] += value[i];
1385
1752
  }
1386
1753
  }
1387
- 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) {
1388
1781
  updateQuantised(
1389
1782
  ctx2,
1783
+ node,
1390
1784
  ctx2.layout.blockOffset[node] + board,
1391
1785
  slotBase,
1392
1786
  actions,
@@ -1398,7 +1792,7 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1398
1792
  out
1399
1793
  );
1400
1794
  } else if (isTraverser && mode === Mode.Train && ctx2.applyUpdates && ctx2.dcfr) {
1401
- const { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);
1795
+ const { keepPositive, keepNegative, keepSum } = blockFactors(ctx2, ctx2.layout.blockOffset[node] + board, iterWeight);
1402
1796
  const regret = ctx2.regret;
1403
1797
  const strategySum = ctx2.strategySum;
1404
1798
  for (let a = 0; a < actions; a++) {
@@ -1409,7 +1803,7 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1409
1803
  const at = slotRow + i;
1410
1804
  const accumulated = regret[at];
1411
1805
  regret[at] = accumulated * (accumulated > 0 ? keepPositive : keepNegative) + actionValues[offset + i] - out[i];
1412
- strategySum[at] = strategySum[at] * keepSum + reachMe2[i] * strategy[row + i];
1806
+ strategySum[at] = strategySum[at] * keepSum + strategy[row + i];
1413
1807
  }
1414
1808
  }
1415
1809
  } else if (isTraverser && mode === Mode.Train && ctx2.applyUpdates) {
@@ -1427,18 +1821,39 @@ function traverse(ctx2, buffers, mode, traverser, iterWeight, node, board, reach
1427
1821
  }
1428
1822
  }
1429
1823
  }
1430
- if (isTraverser && mode === Mode.Train && ctx2.applyUpdates) {
1431
- const tieFrom = lists.tieStart[listSlot];
1432
- const tieTo = lists.tieStart[listSlot + 1];
1433
- if (tieFrom < tieTo) {
1434
- const integer = ctx2.regretScale !== null;
1435
- tieMirrors(ctx2.regret, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);
1436
- tieMirrors(ctx2.strategySum, slotBase, actions, stride, lists.ties, tieFrom, tieTo, integer);
1437
- }
1438
- }
1439
1824
  return out;
1440
1825
  }
1441
- 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) {
1442
1857
  const regret = ctx2.regret;
1443
1858
  const strategySum = ctx2.strategySum;
1444
1859
  const regretScale = ctx2.regretScale;
@@ -1451,7 +1866,7 @@ function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reac
1451
1866
  let weight = iterWeight;
1452
1867
  const clamp = !ctx2.dcfr;
1453
1868
  if (ctx2.dcfr) {
1454
- ({ keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight));
1869
+ ({ keepPositive, keepNegative, keepSum } = blockFactors(ctx2, block, iterWeight));
1455
1870
  weight = 1;
1456
1871
  }
1457
1872
  let largestRegret = 0;
@@ -1467,13 +1882,15 @@ function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reac
1467
1882
  const magnitude = updated < 0 ? -updated : updated;
1468
1883
  if (magnitude > largestRegret) largestRegret = magnitude;
1469
1884
  actionValues[offset + i] = updated;
1470
- 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;
1471
1887
  if (sum > largestSum) largestSum = sum;
1472
1888
  strategy[a * count + i] = sum;
1473
1889
  }
1474
1890
  }
1475
1891
  const regretStep = largestRegret > 0 ? REGRET_STEPS / largestRegret : 0;
1476
1892
  const sumStep = largestSum > 0 ? SUM_STEPS / largestSum : 0;
1893
+ const salt = ctx2.layout.shared ? node : 0;
1477
1894
  for (let a = 0; a < actions; a++) {
1478
1895
  const offset = a * count;
1479
1896
  const slotRow = slotBase + a * count;
@@ -1481,15 +1898,157 @@ function updateQuantised(ctx2, block, slotBase, actions, count, iterWeight, reac
1481
1898
  const at = slotRow + i;
1482
1899
  const r = actionValues[offset + i] * regretStep;
1483
1900
  regret[at] = r < 0 ? r - 0.5 : r + 0.5;
1484
- const s = strategy[a * count + i] * sumStep + dither(at, iterWeight);
1901
+ const s = strategy[a * count + i] * sumStep + dither(at, iterWeight, salt);
1485
1902
  strategySum[at] = s < SUM_STEPS ? s : SUM_STEPS;
1486
1903
  }
1487
1904
  }
1488
1905
  regretScale[block] = largestRegret / REGRET_STEPS;
1489
1906
  sumScale[block] = largestSum / SUM_STEPS;
1490
1907
  }
1491
- function dither(slot, iteration) {
1492
- 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);
1493
2052
  h ^= h >>> 13;
1494
2053
  h = Math.imul(h, 3266489909);
1495
2054
  h ^= h >>> 16;
@@ -1531,7 +2090,7 @@ function makeSolver(ctx2) {
1531
2090
  const weights2 = ctx2.players[traverser].weights;
1532
2091
  const [from, count] = listOf(0, 0, traverser);
1533
2092
  let sum = 0;
1534
- 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];
1535
2094
  return sum / ctx2.totalMass;
1536
2095
  };
1537
2096
  return {
@@ -1541,6 +2100,9 @@ function makeSolver(ctx2) {
1541
2100
  return rootCount;
1542
2101
  },
1543
2102
  traverseRoot: run,
2103
+ get root() {
2104
+ return root;
2105
+ },
1544
2106
  useRoot(next) {
1545
2107
  root = next ?? run;
1546
2108
  },
@@ -1557,17 +2119,79 @@ function makeSolver(ctx2) {
1557
2119
  expectedValue() {
1558
2120
  return [total(root(Mode.Average, 0, 0), 0), total(root(Mode.Average, 1, 0), 1)];
1559
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, unit = (chips) => chips) {
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 ? unit(values[i] / (mass * scale)) : 0;
2155
+ }
2156
+ }
2157
+ return evs;
2158
+ },
1560
2159
  exploitability() {
1561
2160
  const br0 = total(root(Mode.BestResponse, 0, 0), 0);
1562
2161
  const br1 = total(root(Mode.BestResponse, 1, 0), 1);
1563
2162
  return (br0 + br1) / 2;
1564
2163
  },
1565
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
+ }
1566
2192
  const expanded = ctx2.expandOrbits;
1567
2193
  ctx2.expandOrbits = true;
1568
2194
  try {
1569
- const round = ctx2.tree.round[node];
1570
- const opponent = 1 - traverser;
1571
2195
  const me = new Float64Array(COMBOS);
1572
2196
  const opp = new Float64Array(COMBOS);
1573
2197
  gather(reachMe2, round, board, traverser, me);
@@ -1575,16 +2199,18 @@ function makeSolver(ctx2) {
1575
2199
  const value = traverse(ctx2, buffers, Mode.Average, traverser, 0, node, board, me, opp, 0);
1576
2200
  const result = new Float64Array(COMBOS);
1577
2201
  const [from, count] = listOf(round, board, traverser);
1578
- for (let i = 0; i < count; i++) result[lists.list[from + i]] = value[i];
1579
- void live;
1580
- 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
+ }
1581
2207
  return result;
1582
2208
  } finally {
1583
2209
  ctx2.expandOrbits = expanded;
1584
2210
  }
1585
2211
  },
1586
- pairValuesAt(node, board, traverser, hands, handReach, live, liveCount) {
1587
- 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);
1588
2214
  },
1589
2215
  averageStrategyAt(node, board) {
1590
2216
  const owner = ctx2.tree.player[node];
@@ -1595,11 +2221,13 @@ function makeSolver(ctx2) {
1595
2221
  const count = lists.count[slot];
1596
2222
  const base = ctx2.layout.offset[node] + actions * ctx2.layout.rowStart[slot];
1597
2223
  const strategy = new Float64Array(actions * count);
1598
- averageStrategy(ctx2.strategySum, base, actions, count, strategy, ctx2.regret);
2224
+ storedStrategy(ctx2, node, base, actions, count, strategy);
1599
2225
  const probs = new Float64Array(index.count * actions).fill(1 / actions);
1600
2226
  for (let i = 0; i < count; i++) {
1601
- const at = lists.slot[from + i];
1602
- 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
+ }
1603
2231
  }
1604
2232
  return { actions, probs };
1605
2233
  }
@@ -1725,8 +2353,6 @@ function enumerateRunouts(board, symmetries, merge) {
1725
2353
  stabiliserMap.push(Int32Array.from(flat));
1726
2354
  };
1727
2355
  recordStabilisers(stabilisers);
1728
- const used = new Uint8Array(DECK);
1729
- const seen = new Uint8Array(DECK);
1730
2356
  for (let round = 1; round < rounds; round++) {
1731
2357
  const previousWidth = width[round - 1];
1732
2358
  const previousCount = counts[round - 1];
@@ -1741,49 +2367,9 @@ function enumerateRunouts(board, symmetries, merge) {
1741
2367
  const nextStabilisers = [];
1742
2368
  for (let p = 0; p < previousCount; p++) {
1743
2369
  starts[p] = parents.length;
1744
- used.fill(0);
1745
- seen.fill(0);
1746
2370
  const base = p * previousWidth;
1747
- for (let i = 0; i < previousWidth; i++) used[previousCards[base + i]] = 1;
1748
- const stabiliser = stabilisers[p];
1749
- const children = [];
1750
- for (let card = 0; card < DECK; card++) {
1751
- if (used[card] || seen[card]) continue;
1752
- const child = { card, maps: [], cards: [], fixing: [], merged: false };
1753
- for (const sigma of stabiliser) {
1754
- const image = maps.card[sigma][card];
1755
- if (image === card) child.fixing.push(sigma);
1756
- if (seen[image]) continue;
1757
- seen[image] = 1;
1758
- child.maps.push(image === card ? 0 : maps.inverse(sigma));
1759
- child.cards.push(image);
1760
- }
1761
- children.push(child);
1762
- }
1763
- if (merge) {
1764
- const boardRanks = /* @__PURE__ */ new Set();
1765
- for (let i = 0; i < previousWidth; i++) boardRanks.add(previousCards[base + i] >> 2);
1766
- for (let j = 0; j < children.length; j++) {
1767
- const later = children[j];
1768
- const rankJ = later.card >> 2;
1769
- if (boardRanks.has(rankJ)) continue;
1770
- for (let i = 0; i < j; i++) {
1771
- const earlier = children[i];
1772
- if (earlier.merged || (earlier.card & 3) !== (later.card & 3)) continue;
1773
- const rankI = earlier.card >> 2;
1774
- if (boardRanks.has(rankI) || rankJ - rankI > merge.maxGap || !merge.ranks(rankI, rankJ)) continue;
1775
- if (connectivity(boardRanks, rankI) !== connectivity(boardRanks, rankJ)) continue;
1776
- const swap = maps.add(rankSwap(rankI, rankJ));
1777
- for (let m = 0; m < later.maps.length; m++) {
1778
- earlier.maps.push(maps.then(later.maps[m], swap));
1779
- earlier.cards.push(later.cards[m]);
1780
- }
1781
- later.merged = true;
1782
- approximate = true;
1783
- break;
1784
- }
1785
- }
1786
- }
2371
+ const children = dealChildren(maps, previousCards, base, previousWidth, stabilisers[p], merge);
2372
+ for (const child of children) if (child.merged) approximate = true;
1787
2373
  for (const child of children) {
1788
2374
  if (child.merged) continue;
1789
2375
  for (let i = 0; i < previousWidth; i++) level.push(previousCards[base + i]);
@@ -1826,6 +2412,53 @@ function enumerateRunouts(board, symmetries, merge) {
1826
2412
  initial: [...board]
1827
2413
  };
1828
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
+ }
1829
2462
  function rankSwap(a, b) {
1830
2463
  const out = new Uint8Array(DECK);
1831
2464
  for (let card = 0; card < DECK; card++) {
@@ -1863,11 +2496,13 @@ function resolveBoard(runouts, board) {
1863
2496
  const round = i - start + 1;
1864
2497
  const dealt = runouts.maps.card[map][board[i]];
1865
2498
  let found = -1;
1866
- 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++) {
1867
2502
  for (let m = runouts.orbitStart[round][child]; m < runouts.orbitStart[round][child + 1]; m++) {
1868
2503
  if (runouts.orbitCard[round][m] !== dealt) continue;
1869
2504
  found = child;
1870
- map = runouts.maps.then(map, runouts.orbitMap[round][m]);
2505
+ map = runouts.maps.then(map, relabel[m]);
1871
2506
  break;
1872
2507
  }
1873
2508
  }
@@ -2028,18 +2663,108 @@ var CONTROL = {
2028
2663
  iterWeight: 4,
2029
2664
  ready: 5,
2030
2665
  mode: 6,
2666
+ /** Set, never cleared, once any thread's part of a step threw; see src/worker.ts. */
2667
+ failed: 7,
2031
2668
  size: 8
2032
2669
  };
2033
2670
  var COMMAND = { work: 0, exit: 1 };
2034
2671
 
2035
- // 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
2036
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
2037
2762
  var OPS_PER_SECOND = 2e8;
2038
2763
  var SpotTooLargeError = class extends Error {
2039
2764
  estimate;
2040
2765
  constructor(estimate, maxBytes) {
2041
2766
  super(
2042
- `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)}.
2043
2768
  ${estimate.decisionNodes} decision nodes x up to ${estimate.runouts.toLocaleString()} runouts x ${Math.max(...estimate.combos)} combos.
2044
2769
  ` + (estimate.suggestions.length ? `Try:
2045
2770
  ${estimate.suggestions.map((s) => ` - ${s}`).join("\n")}
@@ -2069,16 +2794,10 @@ function defineSpot(config2) {
2069
2794
  const rounds = 6 - board.length;
2070
2795
  if (config2.pot <= 0) throw new Error("pot must be positive");
2071
2796
  if (config2.stack <= 0) throw new Error("stack must be positive");
2072
- const rowsFor = (sizes, who) => {
2073
- const expanded = sizes.length === 1 ? Array.from({ length: rounds }, () => sizes[0]) : sizes;
2074
- if (expanded.length !== rounds) {
2075
- throw new Error(
2076
- `${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`
2077
- );
2078
- }
2079
- return expanded;
2080
- };
2081
- const rows = isPerPlayer(config2.betSizes) ? { oop: rowsFor(config2.betSizes.oop, "oop "), ip: rowsFor(config2.betSizes.ip, "ip ") } : rowsFor(config2.betSizes, "");
2797
+ if (config2.evPot !== void 0 && !(Number.isFinite(config2.evPot) && config2.evPot > 0)) {
2798
+ throw new Error(`evPot must be a positive number of chips; got ${config2.evPot}`);
2799
+ }
2800
+ const rows = betRows(config2, rounds);
2082
2801
  const onBoard = new Set(board);
2083
2802
  const trim = (range, who) => {
2084
2803
  const weights2 = typeof range === "string" ? parseRange(range) : Float64Array.from(range);
@@ -2108,34 +2827,21 @@ function defineSpot(config2) {
2108
2827
  buildPlayerIndex(trim(config2.ip, "in-position"))
2109
2828
  ];
2110
2829
  const symmetries = config2.isomorphism === false || board.length === 5 ? void 0 : suitSymmetries(board, [players[0].weights, players[1].weights]);
2111
- const runouts = enumerateRunouts(
2112
- board,
2113
- symmetries,
2114
- config2.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config2.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config2.runoutBuckets) : void 0
2115
- );
2116
- const tree = buildTree(
2117
- {
2118
- potUnits: Math.round(config2.pot * chipScale),
2119
- stackUnits: Math.round(config2.stack * chipScale),
2120
- betSizes: rows,
2121
- raiseSizes: config2.raiseSizes,
2122
- maxRaises: config2.maxRaises ?? 1,
2123
- allowAllIn: config2.allowAllIn ?? false,
2124
- allInThreshold: config2.allInThreshold,
2125
- noDonk: config2.noDonk,
2126
- mergeSizes: config2.mergeSizes,
2127
- chipScale,
2128
- minRaiseUnits: chipScale
2129
- },
2130
- runouts
2131
- );
2132
- const layout2 = buildLayout(tree, runouts, players, 4);
2830
+ const merge = config2.runoutBuckets && board.length < 5 ? rangeRankMerge(players, config2.runoutBuckets === true ? DEFAULT_BUCKET_GAP : config2.runoutBuckets) : void 0;
2831
+ const runouts = enumerateRunouts(board, symmetries, merge);
2832
+ const tree = buildTree(treeConfig(config2, rows), runouts);
2833
+ const historyAlias = config2.shareHistories ? shareHistories(tree, runouts, config2, chipScale) : void 0;
2834
+ const layout2 = buildLayout(tree, runouts, players, 4, historyAlias);
2133
2835
  const last = runouts.rounds - 1;
2134
2836
  const showdownBytes = runouts.counts[last] * (2 * COMBOS + COMBOS + 1) * 2;
2135
2837
  const bytes = layout2.bytes + showdownBytes;
2136
- const compressedBytes = buildLayout(tree, runouts, players, 2).bytes + showdownBytes;
2838
+ const compressedBytes = buildLayout(tree, runouts, players, 2, historyAlias).bytes + showdownBytes;
2839
+ const walkedSlots = layout2.walkedSlots;
2840
+ const compact2 = config2.compactStorage ? compactPlan(config2.compactStorage, runouts.rounds) : null;
2841
+ const compactBytes = compact2 ? buildLayout(tree, runouts, players, 4, historyAlias, compact2).bytes + showdownBytes : null;
2842
+ const needed = compactBytes ?? compressedBytes;
2137
2843
  const suggestions = [];
2138
- if (compressedBytes > maxBytes) {
2844
+ if (needed > maxBytes) {
2139
2845
  const widest = Math.max(...[0, 1].flatMap((p) => forPlayer(rows, p).map((r) => r.length)));
2140
2846
  if (widest > 1) suggestions.push(`use fewer bet sizes (currently up to ${widest} per round)`);
2141
2847
  const raises = [0, 1].flatMap((p) => [forPlayer(config2.maxRaises ?? 1, p)].flat());
@@ -2151,8 +2857,9 @@ function defineSpot(config2) {
2151
2857
  totalSlots: layout2.totalSlots,
2152
2858
  bytes,
2153
2859
  compressedBytes,
2154
- secondsPerThousandIterations: layout2.totalSlots * 4 * 1e3 / OPS_PER_SECOND,
2155
- fits: compressedBytes <= maxBytes,
2860
+ compactBytes,
2861
+ secondsPerThousandIterations: walkedSlots * 4 * 1e3 / OPS_PER_SECOND,
2862
+ fits: needed <= maxBytes,
2156
2863
  suggestions
2157
2864
  };
2158
2865
  if (!estimate.fits) throw new SpotTooLargeError(estimate, maxBytes);
@@ -2166,12 +2873,74 @@ function defineSpot(config2) {
2166
2873
  potUnits: Math.round(config2.pot * chipScale),
2167
2874
  stackUnits: Math.round(config2.stack * chipScale),
2168
2875
  source: config2,
2876
+ ...historyAlias ? { historyAlias } : {},
2169
2877
  resolveBoard(cards) {
2170
2878
  return resolveBoard(runouts, typeof cards === "string" ? parseCards(cards) : cards);
2171
2879
  }
2172
2880
  };
2173
2881
  }
2882
+ function shareHistories(tree, runouts, config2, chipScale) {
2883
+ const asked = config2.shareHistories === true ? {} : config2.shareHistories || {};
2884
+ const keep = asked.keepLines && asked.keepLines.length > 0 ? keptNodes(tree, chipScale, asked.keepLines) : void 0;
2885
+ return aliasHistories(tree, runouts, { keep }).alias;
2886
+ }
2887
+ function keptNodes(tree, chipScale, lines) {
2888
+ const parent = new Int32Array(tree.nodeCount).fill(-1);
2889
+ const paths = new Array(tree.nodeCount);
2890
+ paths[0] = "(root)";
2891
+ for (let node = 0; node < tree.nodeCount; node++) {
2892
+ for (let e = 0; e < tree.numEdges[node]; e++) {
2893
+ const edge = tree.firstEdge[node] + e;
2894
+ const child = tree.edgeChild[edge];
2895
+ parent[child] = node;
2896
+ const step = tree.kind[node] === NodeKind.Decision ? actionLabel(tree.edgeAction[edge], tree.edgeTarget[edge], chipScale) : "/";
2897
+ paths[child] = node === 0 ? step : `${paths[node]} ${step}`;
2898
+ }
2899
+ }
2900
+ const listed = new Set(lines);
2901
+ const missing = new Set(lines);
2902
+ const marks = new Uint8Array(tree.nodeCount);
2903
+ for (let node = 0; node < tree.nodeCount; node++) {
2904
+ if (listed.has(paths[node])) {
2905
+ missing.delete(paths[node]);
2906
+ marks[node] = 1;
2907
+ } else if (parent[node] >= 0 && marks[parent[node]]) {
2908
+ marks[node] = 1;
2909
+ }
2910
+ }
2911
+ if (missing.size > 0) {
2912
+ throw new Error(`shareHistories.keepLines: no node of this tree has the path ${[...missing].map((l) => `"${l}"`).join(", ")}`);
2913
+ }
2914
+ for (let node = tree.nodeCount - 1; node > 0; node--) if (marks[node]) marks[parent[node]] = 1;
2915
+ return marks;
2916
+ }
2174
2917
  var PRECISION_BYTES = { f64: 8, f32: 4, i16: 2 };
2918
+ function compactPlan(settings, rounds) {
2919
+ const from = settings.from ?? 0;
2920
+ if (!Number.isInteger(from) || from < 0 || from >= rounds) {
2921
+ throw new Error(`compactStorage.from must be a round of this spot, 0 to ${rounds - 1}; got ${from}`);
2922
+ }
2923
+ const chunkBytes = settings.chunkBytes ?? 2 ** 30;
2924
+ if (!Number.isInteger(chunkBytes) || chunkBytes < 1) {
2925
+ throw new Error(`compactStorage.chunkBytes must be a positive whole number of bytes; got ${chunkBytes}`);
2926
+ }
2927
+ const steps = settings.steps ?? 127;
2928
+ if (!Number.isInteger(steps) || steps < 1 || steps > 127) {
2929
+ throw new Error(`compactStorage.steps must be an integer from 1 to 127; got ${steps}`);
2930
+ }
2931
+ if (settings.sums !== false && (settings.blockScale || settings.float)) {
2932
+ throw new Error("compactStorage.sums keeps a scale per hand, so blockScale and float need sums: false");
2933
+ }
2934
+ return {
2935
+ from,
2936
+ steps,
2937
+ perHand: !settings.blockScale && !settings.float,
2938
+ stochastic: !settings.nearest,
2939
+ float: settings.float === true,
2940
+ chunkBytes,
2941
+ sums: settings.sums ?? true
2942
+ };
2943
+ }
2175
2944
  var DEFAULT_BUCKET_GAP = 1;
2176
2945
  function rangeRankMerge(players, maxGap) {
2177
2946
  const allowed = new Uint8Array(13 * 13);
@@ -2202,15 +2971,23 @@ function makeSumStore(precision2, buffer) {
2202
2971
 
2203
2972
  // src/worker.ts
2204
2973
  var setup = workerData;
2205
- var { config, dcfr, precision, simd } = setup.payload;
2974
+ var { config, dcfr, precision, simd, compact, approximations } = setup.payload;
2206
2975
  var spot = defineSpot(config);
2207
2976
  var relevant = new Uint8Array(COMBOS);
2208
2977
  for (const combo of spot.players[0].combos) relevant[combo] = 1;
2209
2978
  for (const combo of spot.players[1].combos) relevant[combo] = 1;
2210
2979
  var weights = runoutWeights(spot.runouts);
2211
- var layout = buildLayout(spot.tree, spot.runouts, spot.players, PRECISION_BYTES[precision]);
2980
+ var layout = buildLayout(
2981
+ spot.tree,
2982
+ spot.runouts,
2983
+ spot.players,
2984
+ PRECISION_BYTES[precision],
2985
+ spot.historyAlias,
2986
+ compact ?? void 0
2987
+ );
2212
2988
  var showdown = buildShowdownTable(spot.runouts, relevant);
2213
2989
  var active = buildActiveLists(spot.runouts, spot.players, showdown);
2990
+ var hands = buildHandSpace(spot.runouts, spot.players, active);
2214
2991
  var ctx = {
2215
2992
  tree: spot.tree,
2216
2993
  runouts: spot.runouts,
@@ -2221,10 +2998,16 @@ var ctx = {
2221
2998
  strategySum: makeSumStore(precision, setup.strategySum),
2222
2999
  regretScale: setup.regretScale ? new Float64Array(setup.regretScale) : null,
2223
3000
  sumScale: setup.sumScale ? new Float64Array(setup.sumScale) : null,
3001
+ compact,
3002
+ compactRegret: setup.compactRegret?.map((chunk) => compact?.float ? new Float32Array(chunk) : new Int8Array(chunk)) ?? null,
3003
+ handShift: setup.handShift?.map((chunk) => new Uint8Array(chunk)) ?? null,
3004
+ compactSum: setup.compactSum?.map((chunk) => new Uint8Array(chunk)) ?? null,
3005
+ sumShift: setup.sumShift?.map((chunk) => new Uint8Array(chunk)) ?? null,
3006
+ compactScale: setup.compactScale ? new Float64Array(setup.compactScale) : null,
2224
3007
  scratch: makeTerminalScratch(),
2225
3008
  chipScale: spot.chipScale,
2226
3009
  active,
2227
- hands: buildHandSpace(spot.runouts, spot.players, active),
3010
+ hands,
2228
3011
  runoutWeight: weights,
2229
3012
  totalMass: matchupMass(spot.players[0].weights, spot.players[1].weights) * weights[0],
2230
3013
  dcfr,
@@ -2236,8 +3019,19 @@ var ctx = {
2236
3019
  chanceOverride: null,
2237
3020
  entryIndexOf: null,
2238
3021
  expandOrbits: false,
2239
- simd
3022
+ simd,
3023
+ // This worker's runouts are its own, so are their blocks and the marks on them.
3024
+ discounted: layout.shared ? new Int32Array(layout.blocks) : null
2240
3025
  };
3026
+ var samplingOptions = approximations?.chanceSampling;
3027
+ if (samplingOptions && setup.sampling) {
3028
+ const [baseline, lastWalk, lastUpdate] = setup.sampling;
3029
+ ctx.sampling = makeSampling(planSampling(spot.tree, spot.runouts, active, layout, samplingOptions), {
3030
+ baseline: new Float32Array(baseline),
3031
+ lastWalk: new Int32Array(lastWalk),
3032
+ lastUpdate: new Int32Array(lastUpdate)
3033
+ });
3034
+ }
2241
3035
  var solver = makeSolver(ctx);
2242
3036
  var control = new Int32Array(setup.control);
2243
3037
  var exchange = new Float64Array(setup.exchange);
@@ -2255,17 +3049,23 @@ for (; ; ) {
2255
3049
  const mode = Atomics.load(control, CONTROL.mode);
2256
3050
  const traverser = Atomics.load(control, CONTROL.traverser);
2257
3051
  const iterWeight = Atomics.load(control, CONTROL.iterWeight);
2258
- for (let entry = 0; entry < setup.plan.entryNodes.length; entry++) {
2259
- const node = setup.plan.entryNodes[entry];
2260
- for (let i = 0; i < COMBOS; i++) {
2261
- reachMe[i] = exchange[entry * 2 * COMBOS + i];
2262
- reachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];
3052
+ try {
3053
+ for (let entry = 0; entry < setup.plan.entryNodes.length; entry++) {
3054
+ const node = setup.plan.entryNodes[entry];
3055
+ for (let i = 0; i < COMBOS; i++) {
3056
+ reachMe[i] = exchange[entry * 2 * COMBOS + i];
3057
+ reachOpp[i] = exchange[entry * 2 * COMBOS + COMBOS + i];
3058
+ }
3059
+ const value = solver.traverseChance(mode, traverser, iterWeight, node, reachMe, reachOpp);
3060
+ for (let i = 0; i < COMBOS; i++) exchange[partialBase + entry * COMBOS + i] = value[i];
2263
3061
  }
2264
- const value = solver.traverseChance(mode, traverser, iterWeight, node, reachMe, reachOpp);
2265
- for (let i = 0; i < COMBOS; i++) exchange[partialBase + entry * COMBOS + i] = value[i];
3062
+ } catch (error) {
3063
+ Atomics.store(control, CONTROL.failed, 1);
3064
+ throw error;
3065
+ } finally {
3066
+ Atomics.add(control, CONTROL.done, 1);
3067
+ Atomics.notify(control, CONTROL.done);
2266
3068
  }
2267
- Atomics.add(control, CONTROL.done, 1);
2268
- Atomics.notify(control, CONTROL.done);
2269
3069
  }
2270
3070
  parentPort?.close();
2271
3071
  //# sourceMappingURL=worker.js.map