gdp-wired 0.24.0 → 0.26.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.
Files changed (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +955 -0
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +409 -174
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +9 -1
  11. package/dist/core/data.js +872 -168
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +364 -40
  29. package/dist/core/machine.d.ts +6 -0
  30. package/dist/core/machine.js +35 -3
  31. package/dist/core/nonterm.d.ts +9 -2
  32. package/dist/core/nonterm.js +173 -9
  33. package/dist/core/q.d.ts +1 -0
  34. package/dist/core/q.js +2 -2
  35. package/dist/core/relation.d.ts +1 -0
  36. package/dist/core/relation.js +95 -39
  37. package/dist/core/solver.d.ts +12 -0
  38. package/dist/core/solver.js +76 -30
  39. package/dist/core/transfer.js +23 -14
  40. package/dist/core/translate.d.ts +1 -1
  41. package/dist/core/translate.js +22 -49
  42. package/dist/core/xstate.d.ts +6 -1
  43. package/dist/core/xstate.js +336 -55
  44. package/dist/kernel/cdcl.d.ts +5 -0
  45. package/dist/kernel/cdcl.js +44 -8
  46. package/dist/kernel/prove.d.ts +6 -1
  47. package/dist/kernel/prove.js +101 -85
  48. package/dist/kernel/reader.d.ts +1 -0
  49. package/dist/kernel/reader.js +4 -3
  50. package/dist/kernel/simplex.d.ts +1 -1
  51. package/dist/kernel/simplex.js +13 -1
  52. package/package.json +3 -2
@@ -1,22 +1,16 @@
1
- import { compileFunction, evalC as evalMC, evalE as evalME, fnValue, interpret, pairedArgs } from "./machine.js";
1
+ import { argsKey, atMost as le, compileFunction, evalC as evalMC, evalE as evalME, fnValue, get, interpret, minus as sub, n as k, pairedArgs, plus as add, same as eqC, seeded, walk, x as v } from "./machine.js";
2
2
  import { check, livenessHelpful, livenessParts, loopLiveness, loopMachine, loopObligations, substC, substE } from "../kernel/kernel.js";
3
3
  import { checkCyclic, factsAvoid, lexLt } from "../kernel/cyclic.js";
4
- import { proveCyclic } from "./cyclic.js";
5
- import { solve, work } from "./solver.js";
4
+ import { and, proveCyclic, vars as vs } from "./cyclic.js";
5
+ import { canon, env, gcd, konst, pivot, plus, ratioRow, refuteFast, solve, subst, times, vars, work } from "./solver.js";
6
6
  import { clock, grow, proveLaws, proveLiveness, proveStepLaws, withDeadline } from "../kernel/prove.js";
7
7
  import { inferLaws } from "./infer.js";
8
- import { generators, houdini, relationOf } from "./relation.js";
8
+ import { bgcd } from "./q.js";
9
+ import { generators, houdini, relationOf, tightBounds } from "./relation.js";
9
10
  // --- terms ----------------------------------------------------------------------------------------------------------
10
- const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
11
- const add = (a, b) => ({ op: 'add', a, b }), sub = (a, b) => ({ op: 'sub', a, b });
12
- const get = (map, key) => ({ op: 'get', map, key });
13
- const le = (a, b) => ({ op: '<=', a, b }), eqC = (a, b) => ({ op: '=', a, b });
14
- const and = (...xs) => (xs.length === 1 ? xs[0] : { op: 'and', xs });
15
11
  const yes = le(k(0), k(0));
16
- const vs = (s) => ({ vars: s, maps: {}, flags: {} });
17
12
  const id = (t) => JSON.stringify(t);
18
- export const pairE = (a, b) => { const s = add(a, b); return add({ op: 'prod', a: s, b: s }, b); };
19
- export const argsKey = (args) => args.slice(1).reduce(pairE, args[0]);
13
+ export { argsKey };
20
14
  // Σ coef·x + c as a term over the naturals: the negative part subtracted (truncated, as the kernel reads sub).
21
15
  export const linE = (coef, c) => {
22
16
  const pos = [], neg = [];
@@ -62,19 +56,6 @@ export const showC = (c) => {
62
56
  case 'all': return `∀${c.key}. ${showC(c.c)}`;
63
57
  }
64
58
  };
65
- const walk = (t, f) => {
66
- if (Array.isArray(t)) {
67
- for (const x of t)
68
- walk(x, f);
69
- return;
70
- }
71
- if (!t || typeof t !== 'object')
72
- return;
73
- const o = t;
74
- f(o);
75
- for (const x of Object.values(o))
76
- walk(x, f);
77
- };
78
59
  const readsOf = (t) => { const out = []; walk(t, o => { if (o.op === 'get')
79
60
  out.push(o); }); return out; };
80
61
  const varsOf = (t) => { const out = new Set(); walk(t, o => { if (o.op === 'var')
@@ -382,11 +363,6 @@ const rankRow = (n, nodes, s, name, scale = 1) => {
382
363
  out = plus(out, { [name(n, j)]: scale * s[x] });
383
364
  return out;
384
365
  };
385
- const plus = (a, b) => { const o = { ...a }; for (const [x, c] of Object.entries(b)) {
386
- o[x] = (o[x] ?? 0) + c;
387
- if (!o[x])
388
- delete o[x];
389
- } return o; };
390
366
  const valueAt = (l, w) => Object.entries(l).reduce((s, [x, c]) => s + c * (x === '1' ? 1 : w[x] ?? 0), 0);
391
367
  // An integer solution of every row (lin <= 0) of `must` and `pool`, the pool's rows added as they are violated. Its
392
368
  // unknowns are bounded, the coefficients first to naturals (a rank with no subtraction, which no truncation bends), then
@@ -415,6 +391,9 @@ function lp(must, pool, until, scale = 1, signs = [true, false], whole = false)
415
391
  };
416
392
  // The widest box first: where it has no solution, none of the smaller has. Past it, a rank's rows (homogeneous in the
417
393
  // unknowns, the drop's constant aside) are solved exactly over the rationals, the solution scaled to whole numbers.
394
+ // (a path's generators, `whole`: the LP over the rationals alone, its least Σ|u| as small a rank as the boxes find)
395
+ if (whole && !fit)
396
+ return exactLp(must, pool, until, whole);
418
397
  if (!stage(signs.at(-1), bounds.at(-1), true))
419
398
  return fit ? undefined : exactLp(must, pool, until, whole);
420
399
  for (const natural of signs)
@@ -426,58 +405,69 @@ function lp(must, pool, until, scale = 1, signs = [true, false], whole = false)
426
405
  }
427
406
  return undefined;
428
407
  }
429
- const bgcd = (a, b) => { if (a < 0n)
430
- a = -a; if (b < 0n)
431
- b = -b; while (b)
432
- [a, b] = [b, a % b]; return a; };
433
408
  const q = (n, d = 1n) => { if (d < 0n)
434
409
  (n = -n, d = -d); const g = bgcd(n, d) || 1n; return g === 1n ? { n, d } : { n: n / g, d: d / g }; };
435
- const Q0 = q(0n), Q1 = q(1n);
410
+ const Q0 = q(0n);
436
411
  const qadd = (a, b) => (a.d === b.d ? q(a.n + b.n, a.d) : q(a.n * b.d + b.n * a.d, a.d * b.d));
437
412
  const qsub = (a, b) => qadd(a, { n: -b.n, d: b.d });
438
- const qmul = (a, b) => (!a.n || !b.n ? Q0 : q(a.n * b.n, a.d * b.d));
439
- const qdiv = (a, b) => q(a.n * b.d, a.d * b.n);
440
- const qlt = (a, b) => a.n * b.d < b.n * a.d;
441
- // The primal simplex on a tableau whose basis is feasible: minimize cost·y over T·y = rhs (the last column), y >= 0,
442
- // Bland's rule (the smallest column that improves, the smallest basis index among ties), only `open` columns entering.
413
+ const reduce = (r) => { let g = r.d; for (const x of r.n) {
414
+ if (g === 1n)
415
+ break;
416
+ if (x)
417
+ g = bgcd(g, x);
418
+ } return g > 1n ? { n: r.n.map(x => x / g), d: r.d / g } : r; };
419
+ // row r minus f times the pivot row (its pivot entry pv > 0 at column e): r's entry at e becomes 0
420
+ const eliminate = (r, piv, e) => {
421
+ const f = r.n[e], pv = piv.n[e];
422
+ if (!f)
423
+ return r;
424
+ return reduce({ n: r.n.map((x, j) => x * pv - f * piv.n[j]), d: r.d * pv });
425
+ };
426
+ function pivotOn(T, z, leave, e) {
427
+ let L = T[leave];
428
+ if (L.n[e] < 0n)
429
+ L = { n: L.n.map(x => -x), d: L.d };
430
+ T[leave] = reduce({ n: L.n, d: L.n[e] });
431
+ const piv = { n: L.n, d: 1n };
432
+ for (let r = 0; r < T.length; r++)
433
+ if (r !== leave && T[r].n[e])
434
+ T[r] = eliminate(T[r], piv, e);
435
+ return z && eliminate(z, piv, e);
436
+ }
443
437
  function simplex(T, basis, cost, open, until) {
444
438
  const cols = cost.length;
439
+ let z = { n: [...cost, 0n], d: 1n };
440
+ for (const [i, b] of basis.entries())
441
+ if (cost[b])
442
+ z = eliminate(z, { n: T[i].n, d: 1n }, b);
445
443
  for (let it = 0; it < 5000; it++) {
446
444
  // (each pivot counted as work, as the solver's rows are: a counted search's clock runs while it solves)
447
445
  work.n += 1 + ((T.length * cols) >> 6);
448
446
  if (clock() > until)
449
447
  return false;
450
448
  let enter = -1;
451
- for (let j = 0; j < cols && enter < 0; j++) {
452
- if (!open(j) || basis.includes(j))
453
- continue;
454
- let r = cost[j];
455
- for (const [i, b] of basis.entries())
456
- if (T[i][j].n && cost[b].n)
457
- r = qsub(r, qmul(cost[b], T[i][j]));
458
- if (r.n < 0n)
449
+ for (let j = 0; j < cols && enter < 0; j++)
450
+ if (z.n[j] < 0n && open(j))
459
451
  enter = j;
460
- }
461
452
  if (enter < 0)
462
453
  return true;
463
- let leave = -1, best;
454
+ let leave = -1;
464
455
  for (const [i, row] of T.entries()) {
465
- if (row[enter].n <= 0n)
456
+ const a = row.n[enter];
457
+ if (a <= 0n)
458
+ continue;
459
+ if (leave < 0) {
460
+ leave = i;
466
461
  continue;
467
- const ratio = qdiv(row[cols], row[enter]);
468
- if (!best || qlt(ratio, best) || (!qlt(best, ratio) && basis[i] < basis[leave]))
469
- (best = ratio, leave = i);
462
+ }
463
+ // row's rhs / a against the best's (the denominators cancel)
464
+ const L = T[leave], lhs = row.n[cols] * L.n[enter], rhs = L.n[cols] * a;
465
+ if (lhs < rhs || (lhs === rhs && basis[i] < basis[leave]))
466
+ leave = i;
470
467
  }
471
468
  if (leave < 0)
472
469
  return false; // unbounded: not for an objective bounded below
473
- const p = T[leave][enter];
474
- T[leave] = T[leave].map(x => qdiv(x, p));
475
- for (const [i, row] of T.entries()) {
476
- if (i === leave || !row[enter].n)
477
- continue;
478
- const f = row[enter];
479
- T[i] = row.map((x, j) => qsub(x, qmul(f, T[leave][j])));
480
- }
470
+ z = pivotOn(T, z, leave, enter);
481
471
  basis[leave] = enter;
482
472
  }
483
473
  return false;
@@ -486,7 +476,173 @@ function simplex(T, basis, cost, open, until) {
486
476
  // rational solution scaled by its denominators' least common multiple and divided by its numerators' common divisor;
487
477
  // kept only if every row holds of it exactly (a row with a positive constant, a drop of at least 1, holds of any
488
478
  // multiple at least 1 of a solution; one with a negative constant may not).
479
+ // The same LP in floating point first (the floats only pick the point): each coefficient read back as the nearest
480
+ // fraction of small denominator, scaled to whole numbers and kept only where every row holds of it exactly; else the
481
+ // exact simplex below (where the floats find no point, none is looked for again). Over hundreds of rows the floats are what makes the search affordable (the exact tableau's
482
+ // reductions dominated it).
483
+ const nearFraction = (x, most = 10_000) => {
484
+ // continued fractions: the last convergent within the denominator bound
485
+ let [h0, h1, k0, k1, y] = [0, 1, 1, 0, x];
486
+ for (let i = 0; i < 40; i++) {
487
+ const a = Math.floor(y), h2 = a * h1 + h0, k2 = a * k1 + k0;
488
+ if (k2 > most)
489
+ break;
490
+ [h0, h1, k0, k1] = [h1, h2, k1, k2];
491
+ if (Math.abs(x - h1 / k1) < 1e-12 || Math.abs(y - a) < 1e-12)
492
+ break;
493
+ y = 1 / (y - a);
494
+ }
495
+ return [h1, k1];
496
+ };
497
+ const lpTrace = !!env.LP_TRACE;
498
+ function floatSolve(rows, until, equil = true, again = true) {
499
+ const xs = [...new Set(rows.flatMap(l => Object.keys(l)).filter(x => x !== '1'))].sort(), n = xs.length, m = rows.length;
500
+ const cols = 2 * n + 2 * m, T = [], basis = [], eps = 1e-9;
501
+ for (const [i, l] of rows.entries()) {
502
+ let rhs = -(l['1'] ?? 0);
503
+ const sign = rhs < 0 ? -1 : 1;
504
+ rhs *= sign;
505
+ // (each row scaled to its largest entry 1: a vertex's coordinates reach 2^31, the drop's constant is 1)
506
+ const row = new Float64Array(cols + 1), big = (equil && Math.max(Math.abs(rhs), ...xs.map(x => Math.abs(l[x] ?? 0)))) || 1;
507
+ for (const [j, x] of xs.entries()) {
508
+ const c = sign * (l[x] ?? 0) / big;
509
+ if (c)
510
+ (row[j] = c, row[n + j] = -c);
511
+ }
512
+ row[2 * n + i] = sign;
513
+ if (sign < 0) {
514
+ row[2 * n + m + i] = 1;
515
+ basis.push(2 * n + m + i);
516
+ }
517
+ else
518
+ basis.push(2 * n + i);
519
+ row[cols] = rhs / big;
520
+ T.push(row);
521
+ }
522
+ const art = (j) => j >= 2 * n + m;
523
+ // minimize cost·y, the reduced costs kept as a row: the most negative enters (Dantzig's rule), Bland's after a run of
524
+ // degenerate pivots (no cycling)
525
+ const run = (cost, open) => {
526
+ const z = new Float64Array(cols + 1);
527
+ for (let j = 0; j < cols; j++)
528
+ z[j] = cost(j);
529
+ for (const [i, b] of basis.entries()) {
530
+ const c = cost(b);
531
+ if (c)
532
+ for (let j = 0; j <= cols; j++)
533
+ z[j] -= c * T[i][j];
534
+ }
535
+ let stalled = 0;
536
+ for (let it = 0; it < 10 * (m + cols); it++) {
537
+ // (each pivot counted as work, an eighth of the exact simplex's: a counted search's clock runs while it solves)
538
+ work.n += 1 + ((T.length * cols) >> 9);
539
+ if ((it & 63) === 0 && clock() > until)
540
+ return false;
541
+ let enter = -1;
542
+ if (stalled < 50) {
543
+ let low = -eps;
544
+ for (let j = 0; j < cols; j++)
545
+ if (z[j] < low && open(j)) {
546
+ low = z[j];
547
+ enter = j;
548
+ }
549
+ }
550
+ else
551
+ for (let j = 0; j < cols; j++)
552
+ if (z[j] < -eps && open(j)) {
553
+ enter = j;
554
+ break;
555
+ }
556
+ if (enter < 0)
557
+ return true;
558
+ const [leave, best] = ratioRow(T, basis, enter, cols, eps);
559
+ if (leave < 0)
560
+ return false;
561
+ stalled = best <= eps ? stalled + 1 : 0;
562
+ pivot(T, z, basis, leave, enter, cols);
563
+ }
564
+ return false;
565
+ };
566
+ if (!run(j => (art(j) ? 1 : 0), () => true))
567
+ return undefined;
568
+ // (no point: the artificials' least sum clearly above zero, which the exact simplex is not asked again)
569
+ if (T.some((row, i) => art(basis[i]) && row[cols] > 1e-6))
570
+ return 'infeasible';
571
+ if (T.some((row, i) => art(basis[i]) && row[cols] > 1e-9))
572
+ return undefined;
573
+ for (let i = T.length - 1; i >= 0; i--) {
574
+ if (!art(basis[i]))
575
+ continue;
576
+ let j = -1;
577
+ for (let c = 0; c < 2 * n + m; c++)
578
+ if (Math.abs(T[i][c]) > eps) {
579
+ j = c;
580
+ break;
581
+ }
582
+ if (j < 0) {
583
+ T.splice(i, 1);
584
+ basis.splice(i, 1);
585
+ continue;
586
+ }
587
+ pivot(T, undefined, basis, i, j, cols);
588
+ }
589
+ if (!run(j => (j < 2 * n ? 1 : 0), j => !art(j)))
590
+ return undefined;
591
+ const val = (j) => { const i = basis.indexOf(j); return i < 0 ? 0 : T[i][cols]; };
592
+ const u = xs.map((_, j) => val(j) - val(n + j));
593
+ // read back: tiny values kept or as 0 (a coefficient 1/2^31 against a bound of the int range is one, or the floats'
594
+ // error), each the nearest fraction, the whole scaled to
595
+ // integers, with and without their common divisor; the first that every row holds of exactly
596
+ for (const [snap, most] of [[0, 10_000], [1e-7, 10_000], [1e-7, 1_000_000], [0, 2 ** 32]]) {
597
+ const fr = u.map(x => (Math.abs(x) <= snap ? [0, 1] : nearFraction(Math.abs(x), most)));
598
+ let lcm = 1n;
599
+ for (const [, d] of fr)
600
+ lcm = lcm / bgcd(lcm, BigInt(d)) * BigInt(d);
601
+ const ints = u.map((x, j) => BigInt(Math.sign(x) * fr[j][0]) * (lcm / BigInt(fr[j][1]))), g = ints.reduce((a, b) => bgcd(a, b), 0n) || 1n;
602
+ for (const div of g > 1n ? [g, 1n] : [1n]) {
603
+ const w = {};
604
+ let safe = true;
605
+ for (const [j, x] of xs.entries()) {
606
+ const c = ints[j] / div;
607
+ if (c > BigInt(Number.MAX_SAFE_INTEGER) || -c > BigInt(Number.MAX_SAFE_INTEGER))
608
+ safe = false;
609
+ else if (c)
610
+ w[x] = Number(c);
611
+ }
612
+ if (safe && holdsExactly(rows, w))
613
+ return w;
614
+ }
615
+ }
616
+ // Else the tiny values as 0 exactly, the LP solved again over the rest: within the tolerance a coefficient of 2^−31
617
+ // against a vertex at 2^31 is a drop of 1 the exact rows don't allow.
618
+ const zero = new Set(xs.filter((_, j) => u[j] !== 0 && Math.abs(u[j]) <= 1e-7));
619
+ if (!again || !zero.size)
620
+ return undefined;
621
+ const fewer = floatSolve(rows.map(r => Object.fromEntries(Object.entries(r).filter(([x]) => !zero.has(x)))), until, equil, false);
622
+ return fewer && fewer !== 'infeasible' && holdsExactly(rows, fewer) ? fewer : undefined;
623
+ }
624
+ // Every row (lin <= 0) at w, in BigInt: products past 2^53 read exactly.
625
+ const holdsExactly = (rows, w) => rows.every(l => {
626
+ let s = 0n;
627
+ for (const x in l)
628
+ s += BigInt(l[x]) * (x === '1' ? 1n : BigInt(w[x] ?? 0));
629
+ return s <= 0n;
630
+ });
489
631
  function exactSolve(rows, until) {
632
+ // (the rows scaled to their largest entry first, then as they are: either way the tolerance may hide what a row of a
633
+ // vertex at 2^31 says, a coefficient 2^−31 read as 0 or 0 as 2^−31; infeasible where both say so)
634
+ const t0 = performance.now(), first = floatSolve(rows, until), second = first && first !== 'infeasible' ? first : floatSolve(rows, until, false);
635
+ const fast = second && second !== 'infeasible' ? second : first === 'infeasible' && second === 'infeasible' ? 'infeasible' : undefined;
636
+ if (lpTrace)
637
+ console.error(`[lp] ${rows.length} rows ${new Set(rows.flatMap(l => Object.keys(l))).size} unknowns: ${fast === undefined ? 'undefined' : fast === 'infeasible' ? 'infeasible' : 'found'} ${Math.round(performance.now() - t0)} ms`);
638
+ if (fast === 'infeasible')
639
+ return undefined;
640
+ if (fast)
641
+ return fast;
642
+ // (no point read back, or the two disagree: a refutation over the rationals, Farkas' rows picked by the floats and
643
+ // checked by elimination on them, which the exact simplex below would take far longer to give; else the exact simplex)
644
+ if (refuteFast(rows.map(lin => ({ lin, label: '' })), 2_000, false)?.kind === 'refuted')
645
+ return undefined;
490
646
  const xs = [...new Set(rows.flatMap(l => Object.keys(l)).filter(x => x !== '1'))].sort(), n = xs.length, m = rows.length;
491
647
  // Columns: p (n), q (n), a slack per row (m), an artificial per row (m); the right-hand side last.
492
648
  const cols = 2 * n + 2 * m, T = [], basis = [];
@@ -494,51 +650,45 @@ function exactSolve(rows, until) {
494
650
  let rhs = -(l['1'] ?? 0);
495
651
  const sign = rhs < 0 ? -1 : 1;
496
652
  rhs *= sign;
497
- const row = Array.from({ length: cols + 1 }, () => Q0);
653
+ const row = Array.from({ length: cols + 1 }, () => 0n);
498
654
  for (const [j, x] of xs.entries()) {
499
655
  const c = sign * (l[x] ?? 0);
500
656
  if (c)
501
- (row[j] = q(BigInt(c)), row[n + j] = q(BigInt(-c)));
657
+ (row[j] = BigInt(c), row[n + j] = BigInt(-c));
502
658
  }
503
- row[2 * n + i] = q(BigInt(sign));
659
+ row[2 * n + i] = BigInt(sign);
504
660
  if (sign < 0) {
505
- row[2 * n + m + i] = Q1;
661
+ row[2 * n + m + i] = 1n;
506
662
  basis.push(2 * n + m + i);
507
663
  }
508
664
  else
509
665
  basis.push(2 * n + i);
510
- row[cols] = q(BigInt(rhs));
511
- T.push(row);
666
+ row[cols] = BigInt(rhs);
667
+ T.push({ n: row, d: 1n });
512
668
  }
513
669
  const art = (j) => j >= 2 * n + m;
514
- const phase1 = Array.from({ length: cols }, (_, j) => (art(j) ? Q1 : Q0));
670
+ const phase1 = Array.from({ length: cols }, (_, j) => (art(j) ? 1n : 0n));
515
671
  if (!simplex(T, basis, phase1, () => true, until))
516
672
  return undefined;
517
- if (T.some((row, i) => art(basis[i]) && row[cols].n))
673
+ if (T.some((row, i) => art(basis[i]) && row.n[cols]))
518
674
  return undefined; // infeasible
519
675
  // An artificial left in the basis at zero: pivoted out on any other column, or its row dropped (redundant).
520
676
  for (let i = T.length - 1; i >= 0; i--) {
521
677
  if (!art(basis[i]))
522
678
  continue;
523
- const j = T[i].findIndex((x, c) => c < 2 * n + m && x.n !== 0n);
679
+ const j = T[i].n.findIndex((x, c) => c < 2 * n + m && x !== 0n);
524
680
  if (j < 0) {
525
681
  T.splice(i, 1);
526
682
  basis.splice(i, 1);
527
683
  continue;
528
684
  }
529
- const p = T[i][j];
530
- T[i] = T[i].map(x => qdiv(x, p));
531
- for (const [r, row] of T.entries())
532
- if (r !== i && row[j].n) {
533
- const f = row[j];
534
- T[r] = row.map((x, c) => qsub(x, qmul(f, T[i][c])));
535
- }
685
+ pivotOn(T, undefined, i, j);
536
686
  basis[i] = j;
537
687
  }
538
- const phase2 = Array.from({ length: cols }, (_, j) => (j < 2 * n ? Q1 : Q0));
688
+ const phase2 = Array.from({ length: cols }, (_, j) => (j < 2 * n ? 1n : 0n));
539
689
  if (!simplex(T, basis, phase2, j => !art(j), until))
540
690
  return undefined;
541
- const val = (j) => { const i = basis.indexOf(j); return i < 0 ? Q0 : T[i][cols]; };
691
+ const val = (j) => { const i = basis.indexOf(j); return i < 0 ? Q0 : q(T[i].n[cols], T[i].d); };
542
692
  const u = xs.map((_, j) => qsub(val(j), val(n + j)));
543
693
  let lcm = 1n;
544
694
  for (const r of u)
@@ -552,7 +702,7 @@ function exactSolve(rows, until) {
552
702
  if (c)
553
703
  w[x] = c;
554
704
  }
555
- return rows.every(l => valueAt(l, w) <= 0) ? w : undefined;
705
+ return holdsExactly(rows, w) ? w : undefined;
556
706
  }
557
707
  // exactSolve over `must` and the pool's rows, the pool's added as they are violated (the most violated first). The
558
708
  // solution is found on the smaller half of the runs (each row's size its largest coefficient, a sample's value or a
@@ -596,7 +746,13 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
596
746
  const ends = onEdges ? edges.flatMap(e => [[e.from, e.s], [e.to, e.t]]) : idx.flatMap(n => samples[n].map(s => [n, s.env]));
597
747
  const points = [...new Map(ends.map(([n, env]) => { const l = rankRow(n, nodes, env, name, -1); return [id(l), l]; })).values()];
598
748
  const delta = (e) => plus(rankRow(e.to, nodes, e.t, name), rankRow(e.from, nodes, e.s, name, -1));
599
- const scale = 1 + Math.max(0, ...idx.flatMap(n => samples[n].flatMap(s => Object.values(s.env))));
749
+ // (a loop, not a spread: tens of thousands of samples' values overflow the stack as arguments)
750
+ let scale = 1;
751
+ for (const n of idx)
752
+ for (const s of samples[n])
753
+ for (const x of Object.values(s.env))
754
+ if (x + 1 > scale)
755
+ scale = x + 1;
600
756
  let left = [...new Map(edges.map(e => { const l = delta(e); return [id(l), l]; })).values()];
601
757
  let keep = [...new Map(weak.map(e => { const l = delta(e); return [id(l), l]; })).values()].filter(l => !left.some(x => id(x) === id(l)));
602
758
  const comps = [];
@@ -604,7 +760,7 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
604
760
  let sum = {};
605
761
  const strict = (l) => valueAt(l, sum) < 0;
606
762
  // One try per pattern of signs (which unknowns an edge raises and lowers): edges alike drop alike, mostly.
607
- const tried = new Set(), sign = (l) => id(Object.keys(l).filter(x => x !== '1').sort().map(x => `${x}${Math.sign(l[x])}`));
763
+ const tried = new Set(), sign = (l) => id(vars(l).sort().map(x => `${x}${Math.sign(l[x])}`));
608
764
  for (const l of left) {
609
765
  if (strict(l) || clock() > until || tried.has(sign(l)) || tried.size > 40)
610
766
  continue;
@@ -628,7 +784,6 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
628
784
  }
629
785
  return { comps, left: left.length };
630
786
  }
631
- const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
632
787
  // The same over named naturals and the edges of runs alone (core/data.ts: a recursive function's calls, each from its
633
788
  // parameters' sizes to its arguments'): each component's coefficient per variable and its constant. Several nodes (a
634
789
  // ring of functions calling each other, each its own names; `nodes`), each its own coefficients and constant per
@@ -884,7 +1039,7 @@ function beside(cx, facts, nodes, big, until, analog) {
884
1039
  }
885
1040
  return [...new Map(out.map(n => [n.name, n])).values()];
886
1041
  }
887
- const trace = !!globalThis.process?.env?.CYCLES_TRACE;
1042
+ const trace = !!env.CYCLES_TRACE;
888
1043
  const nodeOf = (c, level, given) => ({ name: c.name, hyps: c.hyps ?? [], concl: c.concl, vars: varsOf([c.hyps ?? [], c.concl]), level, given });
889
1044
  // The facts at the terms a claim's goal reads (and at those the facts read, `depth` times over): what the search gives
890
1045
  // each node, for a caller building nodes of its own (research/frontier's today, the builders' shape).
@@ -975,15 +1130,6 @@ export function findCycles(facts, claims, opts = {}) {
975
1130
  }
976
1131
  return last;
977
1132
  }
978
- const plusL = (a, b, f = 1) => { const o = { ...a }; for (const x in b) {
979
- o[x] = (o[x] ?? 0) + f * b[x];
980
- if (!o[x])
981
- delete o[x];
982
- } return o; };
983
- const konstL = (c) => (c ? { 1: c } : {});
984
- const scaleL = (a, f) => { const o = {}; if (f)
985
- for (const x in a)
986
- o[x] = a[x] * f; return o; };
987
1133
  // A form over the relation's names as the kernel's term (an integer's coefficient on its two parts), read truncated.
988
1134
  const termOf = (rel, f) => {
989
1135
  const coef = {};
@@ -1038,7 +1184,7 @@ export function rankOfPaths(name, rel, until) {
1038
1184
  return r;
1039
1185
  return r.forms ? { forms: r.forms, values: locations(rel).values } : { why: 'a rank by regions' };
1040
1186
  }
1041
- function relationRank(l, rel, until, extra = []) {
1187
+ function relationRank(l, rel, until, extra = [], inv) {
1042
1188
  const { values, fromOf, toOf, names, at } = locations(rel);
1043
1189
  const every = [...new Set(at.flat())].sort();
1044
1190
  const gpaths = [];
@@ -1057,7 +1203,7 @@ function relationRank(l, rel, until, extra = []) {
1057
1203
  const unknown = (tp, j, n, x) => (x === 1 ? `b:${tp.tag}${j}:${n}` : `a:${tp.tag}${j}:${tp.own ? n : '*'}:${x}`);
1058
1204
  // a node: a location, or one side of an atom at a location (regions, below)
1059
1205
  const nodeLoc = values.map((_, n) => n);
1060
- const varsAt = (tp, n) => (tp.own ? at[nodeLoc[n]] : every);
1206
+ const varsAt = (tp, n) => (tp.own ? at[nodeLoc[n]] : tp.names);
1061
1207
  const fAt = (tp, j, n, x, t) => {
1062
1208
  const out = {};
1063
1209
  for (const v of varsAt(tp, n))
@@ -1082,20 +1228,30 @@ function relationRank(l, rel, until, extra = []) {
1082
1228
  const holds = (p, h, c) => {
1083
1229
  const env = (g) => Object.fromEntries(p.gens.names.map((x, i) => [x, g[i]]));
1084
1230
  const tOf = (g) => g[p.gens.names.length];
1085
- return [
1086
- ...p.gens.vertices.map(g => plusL(scaleL(h(env(g), tOf(g)), -1), { 1: c * tOf(g) })),
1087
- ...p.gens.rays.map(g => scaleL(h(env(g), 0), -1)),
1088
- ...p.gens.lines.flatMap(g => [h(env(g), 0), scaleL(h(env(g), 0), -1)]),
1089
- ];
1231
+ // (each row once; one that reads no unknown and holds, along a name the template doesn't read, left out)
1232
+ const out = new Map();
1233
+ for (const r of [
1234
+ ...p.gens.vertices.map(g => plus(times(h(env(g), tOf(g)), -1), { 1: c * tOf(g) })),
1235
+ ...p.gens.rays.map(g => times(h(env(g), 0), -1)),
1236
+ ...p.gens.lines.flatMap(g => [h(env(g), 0), times(h(env(g), 0), -1)]),
1237
+ ])
1238
+ if (Object.keys(r).some(x => x !== '1') || (r['1'] ?? 0) > 0)
1239
+ out.set(canon(r), r);
1240
+ return [...out.values()];
1090
1241
  };
1091
- const delta = (tp, j, p) => (x, t) => plusL(fAt(tp, j, p.from, x, t), fAt(tp, j, p.to, postAt(p, x, t), t), -1);
1242
+ const delta = (tp, j, p) => (x, t) => plus(fAt(tp, j, p.from, x, t), fAt(tp, j, p.to, postAt(p, x, t), t), -1);
1092
1243
  const strictRows = (tp, p) => [
1093
1244
  ...holds(p, delta(tp, 0, p), 1),
1094
- ...Array.from({ length: tp.depth - 1 }, (_, j) => holds(p, (x, t) => plusL(delta(tp, j + 1, p)(x, t), fAt(tp, j, p.from, x, t)), 1)).flat(),
1245
+ ...Array.from({ length: tp.depth - 1 }, (_, j) => holds(p, (x, t) => plus(delta(tp, j + 1, p)(x, t), fAt(tp, j, p.from, x, t)), 1)).flat(),
1095
1246
  ...holds(p, (x, t) => fAt(tp, tp.depth - 1, p.from, x, t), tp.depth === 1 ? 1 : 0),
1096
1247
  ];
1097
1248
  const weakRows = (tp, p) => Array.from({ length: tp.depth }, (_, j) => holds(p, delta(tp, j, p), 0)).flat();
1098
- const scale = 1 + Math.max(0, ...gpaths.flatMap(p => p.gens.vertices.flatMap(g => g.map(Math.abs))));
1249
+ let scale = 1;
1250
+ for (const p of gpaths)
1251
+ for (const g of p.gens.vertices)
1252
+ for (const x of g)
1253
+ if (Math.abs(x) + 1 > scale)
1254
+ scale = Math.abs(x) + 1;
1099
1255
  const sat = (w, rows) => rows.every(r => valueAt(r, w) <= 0);
1100
1256
  // One block over the paths left: strict on all of them at once, else on as many as one after another allows.
1101
1257
  const block = (tp, left, greedy, until) => {
@@ -1134,10 +1290,12 @@ function relationRank(l, rel, until, extra = []) {
1134
1290
  const ranked = (paths, tag0, until) => {
1135
1291
  let left = paths;
1136
1292
  const mine = [], sizes = [];
1137
- while (left.length && mine.length < 8 && clock() < until) {
1293
+ // a shared template's names: those live where the component's paths begin or end
1294
+ const names = [...new Set(paths.flatMap(p => [...at[nodeLoc[p.from]], ...at[nodeLoc[p.to]]]))].sort();
1295
+ while (left.length && mine.length < 16 && clock() < until) {
1138
1296
  const tag = `${tag0}${mine.length}.`;
1139
1297
  // depth 1 first, all at once then one path after another; then deeper
1140
- const order = [1, 2, 3].flatMap(depth => [false, true].flatMap(greedy => [false, true].map((own) => [{ depth, own, tag }, greedy])));
1298
+ const order = [1, 2, 3].flatMap(depth => [false, true].flatMap(greedy => [false, true].map((own) => [{ depth, own, tag, names }, greedy])));
1141
1299
  let found;
1142
1300
  for (const [tp, greedy] of order) {
1143
1301
  if (found || clock() > until)
@@ -1159,56 +1317,128 @@ function relationRank(l, rel, until, extra = []) {
1159
1317
  if (a)
1160
1318
  f[x] = a;
1161
1319
  }
1162
- return plusL(f, { 1: (tp.depth === 1 ? 0 : 1) + (w[unknown(tp, j, n, 1)] ?? 0) });
1320
+ return plus(f, { 1: (tp.depth === 1 ? 0 : 1) + (w[unknown(tp, j, n, 1)] ?? 0) });
1163
1321
  }));
1164
1322
  sizes.push(tp.depth);
1165
1323
  left = left.filter(p => !strict.includes(p));
1166
1324
  }
1167
1325
  if (left.length)
1168
- return { why: clock() >= until ? 'out of time on the relation' : 'past 8 components' };
1326
+ return { why: clock() >= until ? 'out of time on the relation' : 'past 16 components' };
1169
1327
  return { parts: mine, sizes };
1170
1328
  };
1171
- // Regions: a component with no rank, its locations split by an atom its paths read (q < p: min(p, q); y ≥ 2: a
1172
- // sign), each side a node of its own, its paths split by the side before and after; the kernel's term reads the atom
1173
- // (if atom then f else g).
1174
- const after1 = (p, a) => { let o = {}; for (const [x, c] of Object.entries(a))
1175
- o = plusL(o, x !== '1' && p.post[x] ? scaleL(p.post[x], c) : { [x]: c }); return o; };
1176
- const side = (a, yes) => (yes ? a : plusL({ 1: 1 }, a, -1));
1329
+ // Regions: a component with no rank, its locations split by atoms (one, then two at once): the atoms its paths read
1330
+ // (q < p: min(p, q); y ≥ 2: a sign) and the signs of what a path adds to a value (y := y + x: x ≥ 1). Each sign vector
1331
+ // at a location is a node of its own, the paths split by the signs before and after; the kernel's term reads the atoms
1332
+ // (if atom then f else g). With invariants (`inv`), each node's own first, by Houdini over every path of the relation
1333
+ // split the same way: disjunctive invariants (x ≤ −1 where x ≥ 1 fails, after x := 1 or x := −1), each a law
1334
+ // (pc = ℓ ∧ the signs → atom) the kernel proves inductive with the rest.
1335
+ const side = (a, yes) => (yes ? a : plus({ 1: 1 }, a, -1));
1336
+ const regionLaws = [], regionTexts = [];
1177
1337
  const regions = (c, paths) => {
1178
- const seen = new Set(), atoms = [];
1179
- for (const r of paths.flatMap(p => p.rows)) {
1180
- if (!Object.keys(r).every(x => x === '1' || names.has(x)) || Object.keys(r).length < 2)
1181
- continue;
1182
- const key = [id(Object.keys(r).sort().map(x => [x, r[x]])), id(Object.keys(side(r, false)).sort().map(x => [x, side(r, false)[x]]))].sort().join();
1338
+ const seen = new Set(), guards = [], deltas = [];
1339
+ const add = (r, to) => {
1340
+ const key = [canon(r), id(Object.keys(side(r, false)).sort().map(x => [x, side(r, false)[x]]))].sort().join();
1183
1341
  if (!seen.has(key)) {
1184
1342
  seen.add(key);
1185
- atoms.push(r);
1343
+ to.push(r);
1186
1344
  }
1187
- }
1188
- atoms.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
1345
+ };
1346
+ for (const r of paths.flatMap(p => p.rows))
1347
+ if (Object.keys(r).every(x => x === '1' || names.has(x)) && Object.keys(r).length >= 2)
1348
+ add(r, guards);
1349
+ for (const p of paths)
1350
+ for (const [x, f] of Object.entries(p.post)) {
1351
+ const d = plus(f, { [x]: 1 }, -1);
1352
+ if (Object.keys(d).some(y => y !== '1') && Object.keys(d).every(y => y === '1' || every.includes(y)))
1353
+ add(plus({ 1: 1 }, d, -1), deltas); // d ≥ 1, over live names
1354
+ }
1355
+ guards.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
1356
+ // (the signs of what paths add first: fewer, and each a direction of progress; then the guards' atoms)
1357
+ const singles = [...deltas.slice(0, 4), ...guards.slice(0, 8)], few = singles.slice(0, 4);
1358
+ // (two atoms at once only with the regions' own invariants: without them, the relation's search is the first of
1359
+ // several, and one atom's regions are what it had)
1360
+ const tries = [...singles.map(a => [a]), ...(inv ? few.flatMap((a, i) => few.slice(i + 1).map(b => [a, b])) : [])];
1361
+ if (trace)
1362
+ console.error(`[cycles] ${l.name}: component ${c}: ${tries.length} splits to try`);
1189
1363
  const locs = values.flatMap((_, n) => (comp[n] === c ? [n] : []));
1190
- for (const [ai, a] of atoms.slice(0, 8).entries()) {
1364
+ for (const [ai, as] of tries.entries()) {
1191
1365
  if (clock() > until)
1192
1366
  return undefined;
1193
- const base = nodeLoc.length, node = (n, yes) => base + 2 * locs.indexOf(n) + (yes ? 0 : 1);
1194
- for (const n of locs)
1195
- nodeLoc.push(n, n);
1196
- const split = [];
1197
- for (const p of paths)
1198
- for (const yes of [true, false])
1199
- for (const yes2 of [true, false]) {
1200
- const rows = [...p.rows, side(a, yes), side(after1(p, a), yes2)];
1201
- const gens = generators(rows, p.gens.names, rel.nats, 600, until);
1202
- if (gens?.vertices.length)
1203
- split.push({ from: node(p.from, yes), to: node(p.to, yes2), gens, post: p.post, rows });
1204
- }
1205
- const out = ranked(split, `${c}.r${ai}.`, until);
1206
- if (trace)
1207
- console.error(`[cycles] ${l.name}: component ${c} split by ${showC(leC(rel, a))}: ${'parts' in out ? out.parts.length + ' parts' : out.why}`);
1208
- if ('parts' in out) {
1209
- const cond = leC(rel, a);
1210
- return { parts: out.parts.map(fs => values.map((_, n) => (locs.includes(n) ? { op: 'if', c: cond, then: termOf(rel, fs[node(n, true)]), else: termOf(rel, fs[node(n, false)]) } : k(0)))), sizes: out.sizes };
1367
+ // (each try its share of the time left)
1368
+ const mine = clock() + (until - clock()) / Math.max(2, tries.length - ai);
1369
+ // (every location split, not only the component's: a disjunction an invariant needs is often made before it, x := 1
1370
+ // or x := −1 on the way in)
1371
+ const K = as.length, base = nodeLoc.length, node = (n, bits) => base + (n << K) + bits;
1372
+ for (const n of values.keys())
1373
+ for (let b = 0; b < 1 << K; b++)
1374
+ nodeLoc.push(n);
1375
+ const sides = (p, bits, after) => as.map((a, i) => side(after ? subst(a, p.post) : a, ((bits >> i) & 1) === 0));
1376
+ // (undefined where a path's generators aren't found, past their cap or the time: a path left out is no path ranked)
1377
+ const splitOf = (ps, extra = () => []) => {
1378
+ const out = [];
1379
+ for (const p of ps)
1380
+ for (let b1 = 0; b1 < 1 << K; b1++)
1381
+ for (let b2 = 0; b2 < 1 << K; b2++) {
1382
+ const rows = [...p.rows, ...sides(p, b1, false), ...sides(p, b2, true), ...extra(node(p.from, b1))];
1383
+ // (over the path's names and any an atom reads beside them: a name missing would drop its coefficient)
1384
+ const ns = rows.some(r => Object.keys(r).some(x => x !== '1' && !p.gens.names.includes(x))) ? [...new Set([...p.gens.names, ...rows.flatMap(r => vars(r))])].sort() : p.gens.names;
1385
+ const gens = generators(rows, ns, rel.nats, 600, mine);
1386
+ if (!gens)
1387
+ return undefined;
1388
+ if (gens.vertices.length)
1389
+ out.push({ from: node(p.from, b1), to: node(p.to, b2), gens, post: p.post, rows });
1390
+ }
1391
+ return out;
1392
+ };
1393
+ const conds = as.map(a => leC(rel, a));
1394
+ const term = (fs, n, i = 0, bits = 0) => (i === K ? termOf(rel, fs[node(n, bits)]) : { op: 'if', c: conds[i], then: term(fs, n, i + 1, bits), else: term(fs, n, i + 1, bits | (1 << i)) });
1395
+ const answer = (out) => ({ parts: out.parts.map(fs => values.map((_, n) => (locs.includes(n) ? term(fs, n) : k(0)))), sizes: out.sizes });
1396
+ // (with invariants to find, the split is ranked once, with its regions' own: more rows, no fewer ranks)
1397
+ if (!inv) {
1398
+ const split = splitOf(paths);
1399
+ if (!split)
1400
+ continue;
1401
+ const out = ranked(split, `${c}.r${ai}.`, mine);
1402
+ if (trace)
1403
+ console.error(`[cycles] ${l.name}: component ${c} split by ${conds.map(showC).join(' and ')}: ${'parts' in out ? out.parts.length + ' parts' : out.why}`);
1404
+ if ('parts' in out)
1405
+ return answer(out);
1406
+ continue;
1211
1407
  }
1408
+ // the nodes' invariants: Houdini over every path split, each node's candidates its location's, those false at a
1409
+ // start in its region dropped
1410
+ const N = values.length << K;
1411
+ const split0 = splitOf(gpaths);
1412
+ if (!split0)
1413
+ continue;
1414
+ const cands = Array.from({ length: N }, (_, j) => {
1415
+ const n = j >> K, bits = j & ((1 << K) - 1);
1416
+ const here = inv.starts.filter(([m, env]) => m === n && as.every((a, i) => valueAt(side(a, ((bits >> i) & 1) === 0), env) <= 0));
1417
+ return (inv.cands[n] ?? []).filter(h => here.every(([, env]) => valueAt(h, env) <= 0));
1418
+ });
1419
+ const relSplit = { ...rel, paths: split0.map(p => ({ rows: p.rows, pins: {}, post: p.post })) };
1420
+ const H = houdini(relSplit, cands, i => [split0[i].from - base, split0[i].to - base], mine);
1421
+ if (trace && !H)
1422
+ console.error(`[cycles] ${l.name}: component ${c} split by ${conds.map(showC).join(' and ')}: Houdini out of time`);
1423
+ if (!H)
1424
+ continue;
1425
+ const Ht = H.map(inv.tightest);
1426
+ const split = splitOf(paths, nd => Ht[nd - base] ?? []);
1427
+ if (!split)
1428
+ continue;
1429
+ const out = ranked(split, `${c}.h${ai}.`, mine);
1430
+ if (trace)
1431
+ console.error(`[cycles] ${l.name}: component ${c} split by ${conds.map(showC).join(' and ')}, with ${Ht.flat().length} invariants of the regions: ${'parts' in out ? out.parts.length + ' parts' : out.why}`);
1432
+ if (!('parts' in out))
1433
+ continue;
1434
+ for (let j = 0; j < N; j++)
1435
+ for (const h of Ht[j]) {
1436
+ const n = j >> K, bits = j & ((1 << K) - 1), atom = leC(rel, h);
1437
+ const not = [...(rel.loc ? [eqC(v(rel.loc), k(values[n]))] : []), ...as.map((a, i) => leC(rel, side(a, ((bits >> i) & 1) === 0)))];
1438
+ regionLaws.push({ name: `region invariant ${c}.${j}.${regionLaws.length}`, holds: { op: 'or', xs: [...not.map((x) => ({ op: 'not', x })), atom] } });
1439
+ regionTexts.push(`${not.map(showC).join(' ∧ ')} → ${showC(atom)}`);
1440
+ }
1441
+ return answer(out);
1212
1442
  }
1213
1443
  return undefined;
1214
1444
  };
@@ -1233,7 +1463,7 @@ function relationRank(l, rel, until, extra = []) {
1233
1463
  }
1234
1464
  // per location, its component's parts in order (0 past them), the heights first where paths join components
1235
1465
  const width = Math.max(0, ...parts.map(p => p?.length ?? 0));
1236
- const columns = [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => termOf(rel, konstL(heightOf(comp[n]))))] : []),
1466
+ const columns = [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => termOf(rel, konst(heightOf(comp[n]))))] : []),
1237
1467
  ...Array.from({ length: width }, (_, j) => values.map((_, n) => parts[comp[n]]?.[j]?.[n] ?? k(0)))];
1238
1468
  const rank = columns.map(terms => {
1239
1469
  let e = terms.at(-1) ?? k(0);
@@ -1245,9 +1475,9 @@ function relationRank(l, rel, until, extra = []) {
1245
1475
  if (!rank.length)
1246
1476
  rank.push(k(0));
1247
1477
  const linear = [...new Set(comp)].every(c => lins[c] || !parts[c]);
1248
- const forms = linear ? [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => konstL(heightOf(comp[n])))] : []),
1478
+ const forms = linear ? [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => konst(heightOf(comp[n])))] : []),
1249
1479
  ...Array.from({ length: width }, (_, j) => values.map((_, n) => lins[comp[n]]?.[j]?.[n] ?? {}))] : undefined;
1250
- return { rank, text: `(${rank.map(showE).join(', ')})`, blocks: sizes, ...(forms ? { forms } : {}) };
1480
+ return { rank, text: `(${rank.map(showE).join(', ')})`, blocks: sizes, laws: regionLaws, texts: regionTexts, ...(forms ? { forms } : {}) };
1251
1481
  }
1252
1482
  // Invariants first, so a rank may assume them: atoms per location (each name's bounds at the constants the paths
1253
1483
  // read, and the paths' own atoms over the state and params), those false at a start dropped (the loop's starts, run
@@ -1282,7 +1512,7 @@ export function rankWithInvariants(l, laws, until) {
1282
1512
  const consts = new Set([0, 1, -1]);
1283
1513
  for (const p of rel.paths)
1284
1514
  for (const r of p.rows) {
1285
- const c = r['1'] ?? 0, xs = Object.keys(r).filter(x => x !== '1');
1515
+ const c = r['1'] ?? 0, xs = vars(r);
1286
1516
  if (Math.abs(c) <= 1_000_000)
1287
1517
  for (const d of xs.length === 1 ? [c / Math.abs(r[xs[0]])] : [c])
1288
1518
  if (Number.isInteger(d)) {
@@ -1295,10 +1525,22 @@ export function rankWithInvariants(l, laws, until) {
1295
1525
  }
1296
1526
  }
1297
1527
  const K = [...consts].sort((a, b) => Math.abs(a) - Math.abs(b) || a - b).slice(0, 24);
1298
- const atoms = [...new Map(rel.paths.flatMap(p => p.rows).filter(r => Object.keys(r).filter(x => x !== '1').length > 1 && Object.keys(r).every(x => x === '1' || names.has(x))).map(r => [id(Object.keys(r).sort().map(x => [x, r[x]])), r])).values()];
1528
+ const atoms = [...new Map(rel.paths.flatMap(p => p.rows).filter(r => vars(r).length > 1 && Object.keys(r).every(x => x === '1' || names.has(x))).map(r => [canon(r), r])).values()];
1299
1529
  // per location, over the names live there: their bounds at the constants, then (a second try) the paths' atoms too
1300
- const bounds = values.map((_, n) => at[n].flatMap(x => K.flatMap((c) => [plusL({ [x]: 1 }, konstL(-c)), plusL({ [x]: -1 }, konstL(c))])));
1301
- const withAtoms = values.map((_, n) => [...bounds[n], ...atoms.filter(a => Object.keys(a).every(x => x === '1' || at[n].includes(x)))]);
1530
+ // (and 1 ≤ 0: the location unreachable, where every path into it leaves from states the rest rule out)
1531
+ const bounds = values.map((_, n) => [{ 1: 1 }, ...at[n].flatMap(x => K.flatMap((c) => [plus({ [x]: 1 }, konst(-c)), plus({ [x]: -1 }, konst(c))]))]);
1532
+ // and what a path's assignments leave where it goes: x := y + c with y kept, x − y = c there (KoAT2's 2 + X₄ = X₁)
1533
+ const copies = values.map(() => []);
1534
+ for (const [i, p] of rel.paths.entries())
1535
+ for (const [x, f] of Object.entries(p.post)) {
1536
+ const ys = Object.keys(f).filter(y => y !== '1');
1537
+ if (ys.length !== 1 || f[ys[0]] !== 1 || ys[0] === x || !names.has(ys[0]))
1538
+ continue;
1539
+ const y = ys[0], kept = p.post[y] ? id(p.post[y]) === id({ [y]: 1 }) : true;
1540
+ if (kept)
1541
+ copies[toOf(i)].push(plus({ [x]: 1, [y]: -1 }, konst(-(f['1'] ?? 0))), plus({ [x]: -1, [y]: 1 }, konst(f['1'] ?? 0)));
1542
+ }
1543
+ const withAtoms = values.map((_, n) => [...bounds[n], ...atoms.filter(a => Object.keys(a).every(x => x === '1' || at[n].includes(x))), ...copies[n].filter(a => Object.keys(a).every(x => x === '1' || at[n].includes(x)))]);
1302
1544
  // the starts: random params (the precondition's), the state they begin in
1303
1545
  const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 }, rand = seeded(31);
1304
1546
  const starts = [];
@@ -1325,31 +1567,23 @@ export function rankWithInvariants(l, laws, until) {
1325
1567
  }
1326
1568
  return { laws: out, texts };
1327
1569
  };
1328
- // of the bounds on one name each way, the tightest (the others follow from it: the same set)
1329
- const tightest = (hs) => {
1330
- const best = new Map(), rest = [];
1331
- for (const c of hs) {
1332
- const xs = Object.keys(c).filter(x => x !== '1');
1333
- if (xs.length !== 1) {
1334
- rest.push(c);
1335
- continue;
1336
- }
1337
- const x = xs[0], key = `${x}${Math.sign(c[x])}`, b = (c['1'] ?? 0) / Math.abs(c[x]), was = best.get(key);
1338
- if (!was || b > (was['1'] ?? 0) / Math.abs(was[x]))
1339
- best.set(key, c);
1340
- }
1341
- return [...best.values(), ...rest];
1342
- };
1570
+ // of the bounds on one name each way, the tightest (the same set); a location no run reaches: 1 ≤ 0 alone
1571
+ const tightest = (hs) => { const never = hs.find(c => Object.keys(c).every(x => x === '1') && (c['1'] ?? 0) > 0); return never ? [never] : tightBounds(hs); };
1343
1572
  let H = [], found = { why: 'no invariant' };
1344
1573
  const t1 = clock();
1345
1574
  for (const [i, cands] of [bounds, withAtoms].entries()) {
1346
1575
  if (clock() > until)
1347
1576
  break;
1348
1577
  const closed = houdini(rel, atStarts(cands), locOf, i ? until : clock() + (until - clock()) / 2);
1349
- if (!closed || !closed.some(h => h.length))
1578
+ if (trace)
1579
+ console.error(`[cycles] ${l.name}: houdini round ${i}: ${closed ? closed.map(h => h.map(x => showC(leC(rel, x))).join(" ∧ ")).join(" | ") : "none"}`);
1580
+ if (!closed)
1581
+ continue;
1582
+ // (with none at any location, the regions' own may still be found: the second try only)
1583
+ if (!closed.some(h => h.length) && !i)
1350
1584
  continue;
1351
1585
  H = closed.map(tightest);
1352
- found = relationRank(l, rel, until, H);
1586
+ found = relationRank(l, rel, i ? until : clock() + (until - clock()) / 2, H, { cands: atStarts(cands), starts, tightest });
1353
1587
  if ('rank' in found)
1354
1588
  break;
1355
1589
  found = { why: `with ${H.flat().length} invariants: ${found.why}` };
@@ -1362,6 +1596,7 @@ export function rankWithInvariants(l, laws, until) {
1362
1596
  const fewer = houdini(rel, H.map((g, n) => g.filter(h => !drop(n, h))), locOf, stop);
1363
1597
  if (!fewer || fewer.flat().length === H.flat().length)
1364
1598
  return false;
1599
+ // (no regions' own invariants here: they would only find again the ones dropped)
1365
1600
  const r = relationRank(l, rel, stop, fewer);
1366
1601
  if ('rank' in r) {
1367
1602
  H = fewer;
@@ -1383,9 +1618,9 @@ export function rankWithInvariants(l, laws, until) {
1383
1618
  if (H[n].includes(h))
1384
1619
  without((m, g) => m === n && g === h);
1385
1620
  }
1386
- return { rank: found.rank, text: found.text, ...asLaws(H) };
1621
+ const at0 = asLaws(H);
1622
+ return { rank: found.rank, text: found.text, laws: [...at0.laws, ...found.laws], texts: [...at0.texts, ...found.texts] };
1387
1623
  }
1388
- const seeded = (seed) => { let x = seed; return (n) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * n); }; };
1389
1624
  const goalsProven = (goals) => {
1390
1625
  const trees = {};
1391
1626
  for (const g of goals) {
@@ -1484,7 +1719,7 @@ export function findRank(l, laws = [], opts = {}) {
1484
1719
  if ('trees' in tried[0].verdict)
1485
1720
  return done(linear, tried[0].verdict.trees);
1486
1721
  }
1487
- // The relation's rank (per location, in phases), within half the time left; then degree 2 over the products the loop
1722
+ // The relation's rank (per location, in phases), within a third of the time left; then degree 2 over the products the loop
1488
1723
  // reads; then the relation's rank with invariants. (A search that throws, a stack too deep for a large loop say,
1489
1724
  // gives way to the rest.)
1490
1725
  const safely = (f) => { try {
@@ -1493,16 +1728,16 @@ export function findRank(l, laws = [], opts = {}) {
1493
1728
  catch (e) {
1494
1729
  return { why: `the relation's search threw: ${e.message.slice(0, 120)}` };
1495
1730
  } };
1496
- const relT0 = clock(), rel = safely(() => rankOfRelation(l, laws, clock() + (until - clock()) / 2));
1731
+ const relT0 = clock(), rel = safely(() => rankOfRelation(l, laws, clock() + (until - clock()) / 3));
1497
1732
  let relWhy = 'rank' in rel ? `the kernel refused ${rel.text}` : rel.why;
1498
1733
  if (trace)
1499
1734
  console.error(`[cycles] ${l.name}: the relation's rank ${'rank' in rel ? rel.text : rel.why} (from ${Math.round(relT0 - t0)} ms to ${Math.round(clock() - t0)} ms)`);
1500
1735
  if ('rank' in rel) {
1501
- const verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
1736
+ const k0 = performance.now(), verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
1737
+ if (trace)
1738
+ console.error(`[cycles] ${l.name}: the kernel on the relation's rank, ${Math.round(performance.now() - k0)} ms: ${'trees' in verdict ? 'proven' : `${verdict.goal} ${verdict.stuck}`}`);
1502
1739
  if ('trees' in verdict)
1503
1740
  return done(rel.rank, verdict.trees);
1504
- if (trace)
1505
- console.error(`[cycles] ${l.name}: the kernel refused ${rel.text} at ${verdict.goal}`);
1506
1741
  relWhy = `the kernel refused ${rel.text.slice(0, 300)} at ${verdict.goal}`;
1507
1742
  }
1508
1743
  tried.push(...quadratic(read, until));
@@ -1619,10 +1854,10 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
1619
1854
  const trivial = [...(strong.size ? [] : [[zero]]), ...Object.keys(m.state).filter(x => keeps(x) && lowers(x)).slice(0, 4).map(name => [{ op: 'var', name }])];
1620
1855
  const rankText = (rank) => `(${rank.map(showE).join(', ')})`;
1621
1856
  for (const [i, rank] of trivial.entries()) {
1622
- const ms = until - performance.now();
1857
+ const ms = until - clock();
1623
1858
  if (ms < 200)
1624
1859
  break;
1625
- const v = withDeadline(performance.now() + ms * (i === 0 && !strong.size ? 0.5 : 0.25), () => proveLiveness(m, laws, { ...l, rank }));
1860
+ const v = withDeadline(clock() + ms * (i === 0 && !strong.size ? 0.5 : 0.25), () => proveLiveness(m, laws, { ...l, rank }));
1626
1861
  if (v.proven && v.checked)
1627
1862
  return { proven: true, checked: true, rank, laws: [], found: { rank: rankText(rank), laws: [] } };
1628
1863
  tried.set(id(rank), v);