gdp-wired 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/core/accel.d.ts +44 -0
- package/dist/core/accel.js +720 -0
- package/dist/core/bmc.d.ts +13 -2
- package/dist/core/bmc.js +390 -18
- package/dist/core/cycles.d.ts +23 -0
- package/dist/core/cycles.js +527 -146
- package/dist/core/data.d.ts +17 -0
- package/dist/core/data.js +1177 -213
- package/dist/core/discover.js +8 -3
- package/dist/core/dsl.d.ts +7 -2
- package/dist/core/dsl.js +47 -9
- package/dist/core/extract-check.d.ts +77 -0
- package/dist/core/extract-check.js +785 -0
- package/dist/core/extract-ir.d.ts +139 -0
- package/dist/core/extract-ir.js +198 -0
- package/dist/core/extract-print.d.ts +30 -0
- package/dist/core/extract-print.js +426 -0
- package/dist/core/extract-read.d.ts +298 -0
- package/dist/core/extract-read.js +1298 -0
- package/dist/core/extract-shapes.d.ts +13 -0
- package/dist/core/extract-shapes.js +993 -0
- package/dist/core/extract-xstate.d.ts +34 -0
- package/dist/core/extract-xstate.js +320 -0
- package/dist/core/extract.d.ts +31 -0
- package/dist/core/extract.js +249 -0
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +298 -28
- package/dist/core/kind.d.ts +30 -0
- package/dist/core/kind.js +81 -0
- package/dist/core/nonterm.d.ts +4 -1
- package/dist/core/nonterm.js +98 -2
- package/dist/core/relation.js +82 -7
- package/dist/core/transfer.js +1 -1
- package/dist/core/xstate.d.ts +6 -0
- package/dist/core/xstate.js +70 -12
- package/dist/kernel/cdcl.d.ts +15 -0
- package/dist/kernel/cdcl.js +331 -244
- package/dist/kernel/kernel.d.ts +15 -0
- package/dist/kernel/kernel.js +32 -0
- package/dist/kernel/prove.js +20 -7
- package/dist/kernel/reader.d.ts +14 -0
- package/dist/kernel/reader.js +102 -14
- package/dist/lean-kernel/emit.d.ts +28 -1
- package/dist/lean-kernel/emit.js +56 -15
- package/dist/lean-kernel/library.js +2 -1
- package/package.json +12 -3
package/dist/core/cycles.js
CHANGED
|
@@ -2,8 +2,8 @@ import { compileFunction, evalC as evalMC, evalE as evalME, fnValue, interpret,
|
|
|
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
4
|
import { proveCyclic } from "./cyclic.js";
|
|
5
|
-
import { solve } from "./solver.js";
|
|
6
|
-
import { grow, proveLaws, proveLiveness, proveStepLaws, withDeadline } from "../kernel/prove.js";
|
|
5
|
+
import { refuteFast, solve, work } from "./solver.js";
|
|
6
|
+
import { clock, grow, proveLaws, proveLiveness, proveStepLaws, withDeadline } from "../kernel/prove.js";
|
|
7
7
|
import { inferLaws } from "./infer.js";
|
|
8
8
|
import { generators, houdini, relationOf } from "./relation.js";
|
|
9
9
|
// --- terms ----------------------------------------------------------------------------------------------------------
|
|
@@ -402,7 +402,7 @@ function lp(must, pool, until, scale = 1, signs = [true, false], whole = false)
|
|
|
402
402
|
const b = x.startsWith('b:') ? (wide ? bound * scale : bound) : bound;
|
|
403
403
|
rows.push({ [x]: 1, 1: -b }, natural ? { [x]: -1 } : { [x]: -1, 1: -b });
|
|
404
404
|
}
|
|
405
|
-
for (let round = 0; round < 40 &&
|
|
405
|
+
for (let round = 0; round < 40 && clock() < until; round++) {
|
|
406
406
|
const out = solve(rows.map(lin => ({ lin, label: '' })), 4000);
|
|
407
407
|
if (out.kind !== 'sat')
|
|
408
408
|
break;
|
|
@@ -415,6 +415,9 @@ function lp(must, pool, until, scale = 1, signs = [true, false], whole = false)
|
|
|
415
415
|
};
|
|
416
416
|
// The widest box first: where it has no solution, none of the smaller has. Past it, a rank's rows (homogeneous in the
|
|
417
417
|
// unknowns, the drop's constant aside) are solved exactly over the rationals, the solution scaled to whole numbers.
|
|
418
|
+
// (a path's generators, `whole`: the LP over the rationals alone, its least Σ|u| as small a rank as the boxes find)
|
|
419
|
+
if (whole && !fit)
|
|
420
|
+
return exactLp(must, pool, until, whole);
|
|
418
421
|
if (!stage(signs.at(-1), bounds.at(-1), true))
|
|
419
422
|
return fit ? undefined : exactLp(must, pool, until, whole);
|
|
420
423
|
for (const natural of signs)
|
|
@@ -432,50 +435,67 @@ const bgcd = (a, b) => { if (a < 0n)
|
|
|
432
435
|
[a, b] = [b, a % b]; return a; };
|
|
433
436
|
const q = (n, d = 1n) => { if (d < 0n)
|
|
434
437
|
(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)
|
|
438
|
+
const Q0 = q(0n);
|
|
436
439
|
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
440
|
const qsub = (a, b) => qadd(a, { n: -b.n, d: b.d });
|
|
438
|
-
const
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
441
|
+
const reduce = (r) => { let g = r.d; for (const x of r.n) {
|
|
442
|
+
if (g === 1n)
|
|
443
|
+
break;
|
|
444
|
+
if (x)
|
|
445
|
+
g = bgcd(g, x);
|
|
446
|
+
} return g > 1n ? { n: r.n.map(x => x / g), d: r.d / g } : r; };
|
|
447
|
+
// row r minus f times the pivot row (its pivot entry pv > 0 at column e): r's entry at e becomes 0
|
|
448
|
+
const eliminate = (r, piv, e) => {
|
|
449
|
+
const f = r.n[e], pv = piv.n[e];
|
|
450
|
+
if (!f)
|
|
451
|
+
return r;
|
|
452
|
+
return reduce({ n: r.n.map((x, j) => x * pv - f * piv.n[j]), d: r.d * pv });
|
|
453
|
+
};
|
|
454
|
+
function pivotOn(T, z, leave, e) {
|
|
455
|
+
let L = T[leave];
|
|
456
|
+
if (L.n[e] < 0n)
|
|
457
|
+
L = { n: L.n.map(x => -x), d: L.d };
|
|
458
|
+
T[leave] = reduce({ n: L.n, d: L.n[e] });
|
|
459
|
+
const piv = { n: L.n, d: 1n };
|
|
460
|
+
for (let r = 0; r < T.length; r++)
|
|
461
|
+
if (r !== leave && T[r].n[e])
|
|
462
|
+
T[r] = eliminate(T[r], piv, e);
|
|
463
|
+
return z && eliminate(z, piv, e);
|
|
464
|
+
}
|
|
443
465
|
function simplex(T, basis, cost, open, until) {
|
|
444
466
|
const cols = cost.length;
|
|
467
|
+
let z = { n: [...cost, 0n], d: 1n };
|
|
468
|
+
for (const [i, b] of basis.entries())
|
|
469
|
+
if (cost[b])
|
|
470
|
+
z = eliminate(z, { n: T[i].n, d: 1n }, b);
|
|
445
471
|
for (let it = 0; it < 5000; it++) {
|
|
446
|
-
|
|
472
|
+
// (each pivot counted as work, as the solver's rows are: a counted search's clock runs while it solves)
|
|
473
|
+
work.n += 1 + ((T.length * cols) >> 6);
|
|
474
|
+
if (clock() > until)
|
|
447
475
|
return false;
|
|
448
476
|
let enter = -1;
|
|
449
|
-
for (let j = 0; j < cols && enter < 0; j++)
|
|
450
|
-
if (
|
|
451
|
-
continue;
|
|
452
|
-
let r = cost[j];
|
|
453
|
-
for (const [i, b] of basis.entries())
|
|
454
|
-
if (T[i][j].n && cost[b].n)
|
|
455
|
-
r = qsub(r, qmul(cost[b], T[i][j]));
|
|
456
|
-
if (r.n < 0n)
|
|
477
|
+
for (let j = 0; j < cols && enter < 0; j++)
|
|
478
|
+
if (z.n[j] < 0n && open(j))
|
|
457
479
|
enter = j;
|
|
458
|
-
}
|
|
459
480
|
if (enter < 0)
|
|
460
481
|
return true;
|
|
461
|
-
let leave = -1
|
|
482
|
+
let leave = -1;
|
|
462
483
|
for (const [i, row] of T.entries()) {
|
|
463
|
-
|
|
484
|
+
const a = row.n[enter];
|
|
485
|
+
if (a <= 0n)
|
|
464
486
|
continue;
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
487
|
+
if (leave < 0) {
|
|
488
|
+
leave = i;
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
// row's rhs / a against the best's (the denominators cancel)
|
|
492
|
+
const L = T[leave], lhs = row.n[cols] * L.n[enter], rhs = L.n[cols] * a;
|
|
493
|
+
if (lhs < rhs || (lhs === rhs && basis[i] < basis[leave]))
|
|
494
|
+
leave = i;
|
|
468
495
|
}
|
|
469
496
|
if (leave < 0)
|
|
470
497
|
return false; // unbounded: not for an objective bounded below
|
|
471
|
-
|
|
472
|
-
T[leave] = T[leave].map(x => qdiv(x, p));
|
|
473
|
-
for (const [i, row] of T.entries()) {
|
|
474
|
-
if (i === leave || !row[enter].n)
|
|
475
|
-
continue;
|
|
476
|
-
const f = row[enter];
|
|
477
|
-
T[i] = row.map((x, j) => qsub(x, qmul(f, T[leave][j])));
|
|
478
|
-
}
|
|
498
|
+
z = pivotOn(T, z, leave, enter);
|
|
479
499
|
basis[leave] = enter;
|
|
480
500
|
}
|
|
481
501
|
return false;
|
|
@@ -484,7 +504,211 @@ function simplex(T, basis, cost, open, until) {
|
|
|
484
504
|
// rational solution scaled by its denominators' least common multiple and divided by its numerators' common divisor;
|
|
485
505
|
// kept only if every row holds of it exactly (a row with a positive constant, a drop of at least 1, holds of any
|
|
486
506
|
// multiple at least 1 of a solution; one with a negative constant may not).
|
|
507
|
+
// The same LP in floating point first (the floats only pick the point): each coefficient read back as the nearest
|
|
508
|
+
// fraction of small denominator, scaled to whole numbers and kept only where every row holds of it exactly; else the
|
|
509
|
+
// 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
|
|
510
|
+
// reductions dominated it).
|
|
511
|
+
const nearFraction = (x, most = 10_000) => {
|
|
512
|
+
// continued fractions: the last convergent within the denominator bound
|
|
513
|
+
let [h0, h1, k0, k1, y] = [0, 1, 1, 0, x];
|
|
514
|
+
for (let i = 0; i < 40; i++) {
|
|
515
|
+
const a = Math.floor(y), h2 = a * h1 + h0, k2 = a * k1 + k0;
|
|
516
|
+
if (k2 > most)
|
|
517
|
+
break;
|
|
518
|
+
[h0, h1, k0, k1] = [h1, h2, k1, k2];
|
|
519
|
+
if (Math.abs(x - h1 / k1) < 1e-12 || Math.abs(y - a) < 1e-12)
|
|
520
|
+
break;
|
|
521
|
+
y = 1 / (y - a);
|
|
522
|
+
}
|
|
523
|
+
return [h1, k1];
|
|
524
|
+
};
|
|
525
|
+
const lpTrace = !!globalThis.process?.env?.LP_TRACE;
|
|
526
|
+
function floatSolve(rows, until, equil = true, again = true) {
|
|
527
|
+
const xs = [...new Set(rows.flatMap(l => Object.keys(l)).filter(x => x !== '1'))].sort(), n = xs.length, m = rows.length;
|
|
528
|
+
const cols = 2 * n + 2 * m, T = [], basis = [], eps = 1e-9;
|
|
529
|
+
for (const [i, l] of rows.entries()) {
|
|
530
|
+
let rhs = -(l['1'] ?? 0);
|
|
531
|
+
const sign = rhs < 0 ? -1 : 1;
|
|
532
|
+
rhs *= sign;
|
|
533
|
+
// (each row scaled to its largest entry 1: a vertex's coordinates reach 2^31, the drop's constant is 1)
|
|
534
|
+
const row = new Float64Array(cols + 1), big = (equil && Math.max(Math.abs(rhs), ...xs.map(x => Math.abs(l[x] ?? 0)))) || 1;
|
|
535
|
+
for (const [j, x] of xs.entries()) {
|
|
536
|
+
const c = sign * (l[x] ?? 0) / big;
|
|
537
|
+
if (c)
|
|
538
|
+
(row[j] = c, row[n + j] = -c);
|
|
539
|
+
}
|
|
540
|
+
row[2 * n + i] = sign;
|
|
541
|
+
if (sign < 0) {
|
|
542
|
+
row[2 * n + m + i] = 1;
|
|
543
|
+
basis.push(2 * n + m + i);
|
|
544
|
+
}
|
|
545
|
+
else
|
|
546
|
+
basis.push(2 * n + i);
|
|
547
|
+
row[cols] = rhs / big;
|
|
548
|
+
T.push(row);
|
|
549
|
+
}
|
|
550
|
+
const art = (j) => j >= 2 * n + m;
|
|
551
|
+
// minimize cost·y, the reduced costs kept as a row: the most negative enters (Dantzig's rule), Bland's after a run of
|
|
552
|
+
// degenerate pivots (no cycling)
|
|
553
|
+
const run = (cost, open) => {
|
|
554
|
+
const z = new Float64Array(cols + 1);
|
|
555
|
+
for (let j = 0; j < cols; j++)
|
|
556
|
+
z[j] = cost(j);
|
|
557
|
+
for (const [i, b] of basis.entries()) {
|
|
558
|
+
const c = cost(b);
|
|
559
|
+
if (c)
|
|
560
|
+
for (let j = 0; j <= cols; j++)
|
|
561
|
+
z[j] -= c * T[i][j];
|
|
562
|
+
}
|
|
563
|
+
let stalled = 0;
|
|
564
|
+
for (let it = 0; it < 10 * (m + cols); it++) {
|
|
565
|
+
// (each pivot counted as work, an eighth of the exact simplex's: a counted search's clock runs while it solves)
|
|
566
|
+
work.n += 1 + ((T.length * cols) >> 9);
|
|
567
|
+
if ((it & 63) === 0 && clock() > until)
|
|
568
|
+
return false;
|
|
569
|
+
let enter = -1;
|
|
570
|
+
if (stalled < 50) {
|
|
571
|
+
let low = -eps;
|
|
572
|
+
for (let j = 0; j < cols; j++)
|
|
573
|
+
if (z[j] < low && open(j)) {
|
|
574
|
+
low = z[j];
|
|
575
|
+
enter = j;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
else
|
|
579
|
+
for (let j = 0; j < cols; j++)
|
|
580
|
+
if (z[j] < -eps && open(j)) {
|
|
581
|
+
enter = j;
|
|
582
|
+
break;
|
|
583
|
+
}
|
|
584
|
+
if (enter < 0)
|
|
585
|
+
return true;
|
|
586
|
+
let leave = -1, best = Infinity;
|
|
587
|
+
for (let r = 0; r < T.length; r++) {
|
|
588
|
+
const a = T[r][enter];
|
|
589
|
+
if (a > eps) {
|
|
590
|
+
const ratio = T[r][cols] / a;
|
|
591
|
+
if (ratio < best - eps || (Math.abs(ratio - best) <= eps && basis[r] < basis[leave])) {
|
|
592
|
+
best = ratio;
|
|
593
|
+
leave = r;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
if (leave < 0)
|
|
598
|
+
return false;
|
|
599
|
+
stalled = best <= eps ? stalled + 1 : 0;
|
|
600
|
+
const p = T[leave], pv = p[enter];
|
|
601
|
+
for (let j = 0; j <= cols; j++)
|
|
602
|
+
p[j] /= pv;
|
|
603
|
+
for (let r = 0; r < T.length; r++)
|
|
604
|
+
if (r !== leave) {
|
|
605
|
+
const f = T[r][enter];
|
|
606
|
+
if (f !== 0) {
|
|
607
|
+
const row = T[r];
|
|
608
|
+
for (let j = 0; j <= cols; j++)
|
|
609
|
+
row[j] -= f * p[j];
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const f = z[enter];
|
|
613
|
+
if (f !== 0)
|
|
614
|
+
for (let j = 0; j <= cols; j++)
|
|
615
|
+
z[j] -= f * p[j];
|
|
616
|
+
basis[leave] = enter;
|
|
617
|
+
}
|
|
618
|
+
return false;
|
|
619
|
+
};
|
|
620
|
+
if (!run(j => (art(j) ? 1 : 0), () => true))
|
|
621
|
+
return undefined;
|
|
622
|
+
// (no point: the artificials' least sum clearly above zero, which the exact simplex is not asked again)
|
|
623
|
+
if (T.some((row, i) => art(basis[i]) && row[cols] > 1e-6))
|
|
624
|
+
return 'infeasible';
|
|
625
|
+
if (T.some((row, i) => art(basis[i]) && row[cols] > 1e-9))
|
|
626
|
+
return undefined;
|
|
627
|
+
for (let i = T.length - 1; i >= 0; i--) {
|
|
628
|
+
if (!art(basis[i]))
|
|
629
|
+
continue;
|
|
630
|
+
let j = -1;
|
|
631
|
+
for (let c = 0; c < 2 * n + m; c++)
|
|
632
|
+
if (Math.abs(T[i][c]) > eps) {
|
|
633
|
+
j = c;
|
|
634
|
+
break;
|
|
635
|
+
}
|
|
636
|
+
if (j < 0) {
|
|
637
|
+
T.splice(i, 1);
|
|
638
|
+
basis.splice(i, 1);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
const p = T[i], pv = p[j];
|
|
642
|
+
for (let c = 0; c <= cols; c++)
|
|
643
|
+
p[c] /= pv;
|
|
644
|
+
for (let r = 0; r < T.length; r++)
|
|
645
|
+
if (r !== i) {
|
|
646
|
+
const f = T[r][j];
|
|
647
|
+
if (f !== 0) {
|
|
648
|
+
const row = T[r];
|
|
649
|
+
for (let c = 0; c <= cols; c++)
|
|
650
|
+
row[c] -= f * p[c];
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
basis[i] = j;
|
|
654
|
+
}
|
|
655
|
+
if (!run(j => (j < 2 * n ? 1 : 0), j => !art(j)))
|
|
656
|
+
return undefined;
|
|
657
|
+
const val = (j) => { const i = basis.indexOf(j); return i < 0 ? 0 : T[i][cols]; };
|
|
658
|
+
const u = xs.map((_, j) => val(j) - val(n + j));
|
|
659
|
+
// 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'
|
|
660
|
+
// error), each the nearest fraction, the whole scaled to
|
|
661
|
+
// integers, with and without their common divisor; the first that every row holds of exactly
|
|
662
|
+
for (const [snap, most] of [[0, 10_000], [1e-7, 10_000], [1e-7, 1_000_000], [0, 2 ** 32]]) {
|
|
663
|
+
const fr = u.map(x => (Math.abs(x) <= snap ? [0, 1] : nearFraction(Math.abs(x), most)));
|
|
664
|
+
let lcm = 1n;
|
|
665
|
+
for (const [, d] of fr)
|
|
666
|
+
lcm = lcm / bgcd(lcm, BigInt(d)) * BigInt(d);
|
|
667
|
+
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;
|
|
668
|
+
for (const div of g > 1n ? [g, 1n] : [1n]) {
|
|
669
|
+
const w = {};
|
|
670
|
+
let safe = true;
|
|
671
|
+
for (const [j, x] of xs.entries()) {
|
|
672
|
+
const c = ints[j] / div;
|
|
673
|
+
if (c > BigInt(Number.MAX_SAFE_INTEGER) || -c > BigInt(Number.MAX_SAFE_INTEGER))
|
|
674
|
+
safe = false;
|
|
675
|
+
else if (c)
|
|
676
|
+
w[x] = Number(c);
|
|
677
|
+
}
|
|
678
|
+
if (safe && holdsExactly(rows, w))
|
|
679
|
+
return w;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
// Else the tiny values as 0 exactly, the LP solved again over the rest: within the tolerance a coefficient of 2^−31
|
|
683
|
+
// against a vertex at 2^31 is a drop of 1 the exact rows don't allow.
|
|
684
|
+
const zero = new Set(xs.filter((_, j) => u[j] !== 0 && Math.abs(u[j]) <= 1e-7));
|
|
685
|
+
if (!again || !zero.size)
|
|
686
|
+
return undefined;
|
|
687
|
+
const fewer = floatSolve(rows.map(r => Object.fromEntries(Object.entries(r).filter(([x]) => !zero.has(x)))), until, equil, false);
|
|
688
|
+
return fewer && fewer !== 'infeasible' && holdsExactly(rows, fewer) ? fewer : undefined;
|
|
689
|
+
}
|
|
690
|
+
// Every row (lin <= 0) at w, in BigInt: products past 2^53 read exactly.
|
|
691
|
+
const holdsExactly = (rows, w) => rows.every(l => {
|
|
692
|
+
let s = 0n;
|
|
693
|
+
for (const x in l)
|
|
694
|
+
s += BigInt(l[x]) * (x === '1' ? 1n : BigInt(w[x] ?? 0));
|
|
695
|
+
return s <= 0n;
|
|
696
|
+
});
|
|
487
697
|
function exactSolve(rows, until) {
|
|
698
|
+
// (the rows scaled to their largest entry first, then as they are: either way the tolerance may hide what a row of a
|
|
699
|
+
// vertex at 2^31 says, a coefficient 2^−31 read as 0 or 0 as 2^−31; infeasible where both say so)
|
|
700
|
+
const t0 = performance.now(), first = floatSolve(rows, until), second = first && first !== 'infeasible' ? first : floatSolve(rows, until, false);
|
|
701
|
+
const fast = second && second !== 'infeasible' ? second : first === 'infeasible' && second === 'infeasible' ? 'infeasible' : undefined;
|
|
702
|
+
if (lpTrace)
|
|
703
|
+
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`);
|
|
704
|
+
if (fast === 'infeasible')
|
|
705
|
+
return undefined;
|
|
706
|
+
if (fast)
|
|
707
|
+
return fast;
|
|
708
|
+
// (no point read back, or the two disagree: a refutation over the rationals, Farkas' rows picked by the floats and
|
|
709
|
+
// checked by elimination on them, which the exact simplex below would take far longer to give; else the exact simplex)
|
|
710
|
+
if (refuteFast(rows.map(lin => ({ lin, label: '' })), 2_000, false)?.kind === 'refuted')
|
|
711
|
+
return undefined;
|
|
488
712
|
const xs = [...new Set(rows.flatMap(l => Object.keys(l)).filter(x => x !== '1'))].sort(), n = xs.length, m = rows.length;
|
|
489
713
|
// Columns: p (n), q (n), a slack per row (m), an artificial per row (m); the right-hand side last.
|
|
490
714
|
const cols = 2 * n + 2 * m, T = [], basis = [];
|
|
@@ -492,51 +716,45 @@ function exactSolve(rows, until) {
|
|
|
492
716
|
let rhs = -(l['1'] ?? 0);
|
|
493
717
|
const sign = rhs < 0 ? -1 : 1;
|
|
494
718
|
rhs *= sign;
|
|
495
|
-
const row = Array.from({ length: cols + 1 }, () =>
|
|
719
|
+
const row = Array.from({ length: cols + 1 }, () => 0n);
|
|
496
720
|
for (const [j, x] of xs.entries()) {
|
|
497
721
|
const c = sign * (l[x] ?? 0);
|
|
498
722
|
if (c)
|
|
499
|
-
(row[j] =
|
|
723
|
+
(row[j] = BigInt(c), row[n + j] = BigInt(-c));
|
|
500
724
|
}
|
|
501
|
-
row[2 * n + i] =
|
|
725
|
+
row[2 * n + i] = BigInt(sign);
|
|
502
726
|
if (sign < 0) {
|
|
503
|
-
row[2 * n + m + i] =
|
|
727
|
+
row[2 * n + m + i] = 1n;
|
|
504
728
|
basis.push(2 * n + m + i);
|
|
505
729
|
}
|
|
506
730
|
else
|
|
507
731
|
basis.push(2 * n + i);
|
|
508
|
-
row[cols] =
|
|
509
|
-
T.push(row);
|
|
732
|
+
row[cols] = BigInt(rhs);
|
|
733
|
+
T.push({ n: row, d: 1n });
|
|
510
734
|
}
|
|
511
735
|
const art = (j) => j >= 2 * n + m;
|
|
512
|
-
const phase1 = Array.from({ length: cols }, (_, j) => (art(j) ?
|
|
736
|
+
const phase1 = Array.from({ length: cols }, (_, j) => (art(j) ? 1n : 0n));
|
|
513
737
|
if (!simplex(T, basis, phase1, () => true, until))
|
|
514
738
|
return undefined;
|
|
515
|
-
if (T.some((row, i) => art(basis[i]) && row[cols]
|
|
739
|
+
if (T.some((row, i) => art(basis[i]) && row.n[cols]))
|
|
516
740
|
return undefined; // infeasible
|
|
517
741
|
// An artificial left in the basis at zero: pivoted out on any other column, or its row dropped (redundant).
|
|
518
742
|
for (let i = T.length - 1; i >= 0; i--) {
|
|
519
743
|
if (!art(basis[i]))
|
|
520
744
|
continue;
|
|
521
|
-
const j = T[i].findIndex((x, c) => c < 2 * n + m && x
|
|
745
|
+
const j = T[i].n.findIndex((x, c) => c < 2 * n + m && x !== 0n);
|
|
522
746
|
if (j < 0) {
|
|
523
747
|
T.splice(i, 1);
|
|
524
748
|
basis.splice(i, 1);
|
|
525
749
|
continue;
|
|
526
750
|
}
|
|
527
|
-
|
|
528
|
-
T[i] = T[i].map(x => qdiv(x, p));
|
|
529
|
-
for (const [r, row] of T.entries())
|
|
530
|
-
if (r !== i && row[j].n) {
|
|
531
|
-
const f = row[j];
|
|
532
|
-
T[r] = row.map((x, c) => qsub(x, qmul(f, T[i][c])));
|
|
533
|
-
}
|
|
751
|
+
pivotOn(T, undefined, i, j);
|
|
534
752
|
basis[i] = j;
|
|
535
753
|
}
|
|
536
|
-
const phase2 = Array.from({ length: cols }, (_, j) => (j < 2 * n ?
|
|
754
|
+
const phase2 = Array.from({ length: cols }, (_, j) => (j < 2 * n ? 1n : 0n));
|
|
537
755
|
if (!simplex(T, basis, phase2, j => !art(j), until))
|
|
538
756
|
return undefined;
|
|
539
|
-
const val = (j) => { const i = basis.indexOf(j); return i < 0 ? Q0 : T[i][cols]; };
|
|
757
|
+
const val = (j) => { const i = basis.indexOf(j); return i < 0 ? Q0 : q(T[i].n[cols], T[i].d); };
|
|
540
758
|
const u = xs.map((_, j) => qsub(val(j), val(n + j)));
|
|
541
759
|
let lcm = 1n;
|
|
542
760
|
for (const r of u)
|
|
@@ -550,7 +768,7 @@ function exactSolve(rows, until) {
|
|
|
550
768
|
if (c)
|
|
551
769
|
w[x] = c;
|
|
552
770
|
}
|
|
553
|
-
return rows
|
|
771
|
+
return holdsExactly(rows, w) ? w : undefined;
|
|
554
772
|
}
|
|
555
773
|
// exactSolve over `must` and the pool's rows, the pool's added as they are violated (the most violated first). The
|
|
556
774
|
// solution is found on the smaller half of the runs (each row's size its largest coefficient, a sample's value or a
|
|
@@ -563,7 +781,7 @@ function exactLp(must, pool, until, whole = false) {
|
|
|
563
781
|
if (x !== '1')
|
|
564
782
|
m = Math.max(m, Math.abs(l[x])); return m; };
|
|
565
783
|
const sizes = pool.map(size), half = sizes.reduce((a, b) => Math.max(a, b), 0) / 2, small = whole ? pool : pool.filter((_, i) => sizes[i] <= half), rows = [...must];
|
|
566
|
-
for (let round = 0; round < 40 &&
|
|
784
|
+
for (let round = 0; round < 40 && clock() < until; round++) {
|
|
567
785
|
const w = exactSolve(rows, until);
|
|
568
786
|
if (!w)
|
|
569
787
|
return undefined;
|
|
@@ -594,17 +812,23 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
|
|
|
594
812
|
const ends = onEdges ? edges.flatMap(e => [[e.from, e.s], [e.to, e.t]]) : idx.flatMap(n => samples[n].map(s => [n, s.env]));
|
|
595
813
|
const points = [...new Map(ends.map(([n, env]) => { const l = rankRow(n, nodes, env, name, -1); return [id(l), l]; })).values()];
|
|
596
814
|
const delta = (e) => plus(rankRow(e.to, nodes, e.t, name), rankRow(e.from, nodes, e.s, name, -1));
|
|
597
|
-
|
|
815
|
+
// (a loop, not a spread: tens of thousands of samples' values overflow the stack as arguments)
|
|
816
|
+
let scale = 1;
|
|
817
|
+
for (const n of idx)
|
|
818
|
+
for (const s of samples[n])
|
|
819
|
+
for (const x of Object.values(s.env))
|
|
820
|
+
if (x + 1 > scale)
|
|
821
|
+
scale = x + 1;
|
|
598
822
|
let left = [...new Map(edges.map(e => { const l = delta(e); return [id(l), l]; })).values()];
|
|
599
823
|
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)));
|
|
600
824
|
const comps = [];
|
|
601
|
-
while (left.length && comps.length < 4 &&
|
|
825
|
+
while (left.length && comps.length < 4 && clock() < until) {
|
|
602
826
|
let sum = {};
|
|
603
827
|
const strict = (l) => valueAt(l, sum) < 0;
|
|
604
828
|
// One try per pattern of signs (which unknowns an edge raises and lowers): edges alike drop alike, mostly.
|
|
605
829
|
const tried = new Set(), sign = (l) => id(Object.keys(l).filter(x => x !== '1').sort().map(x => `${x}${Math.sign(l[x])}`));
|
|
606
830
|
for (const l of left) {
|
|
607
|
-
if (strict(l) ||
|
|
831
|
+
if (strict(l) || clock() > until || tried.has(sign(l)) || tried.size > 40)
|
|
608
832
|
continue;
|
|
609
833
|
tried.add(sign(l));
|
|
610
834
|
const w = lp([plus(l, { 1: 1 })], [...left, ...keep, ...points], until, scale);
|
|
@@ -628,11 +852,20 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
|
|
|
628
852
|
}
|
|
629
853
|
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
|
|
630
854
|
// The same over named naturals and the edges of runs alone (core/data.ts: a recursive function's calls, each from its
|
|
631
|
-
// parameters' sizes to its arguments'): each component's coefficient per variable and its constant.
|
|
855
|
+
// parameters' sizes to its arguments'): each component's coefficient per variable and its constant. Several nodes (a
|
|
856
|
+
// ring of functions calling each other, each its own names; `nodes`), each its own coefficients and constant per
|
|
857
|
+
// component (a rank per location: (size(x), 1) at one function, (size(x), 0) at the one it calls with x). Its budget,
|
|
858
|
+
// `ms`, is read on the shared clock (kernel/prove.ts's `clock`): counted work inside a counted search, its pivots counted
|
|
859
|
+
// as the solver's rows are, so a counted search's verdict doesn't depend on the machine's speed.
|
|
632
860
|
export function ranksOfRuns(vars, points, edges, ms = 1000) {
|
|
633
|
-
const
|
|
634
|
-
|
|
635
|
-
|
|
861
|
+
const r = ranksOfCalls([vars], points.map(env => ({ node: 0, env })), edges.map(e => ({ from: 0, to: 0, s: e.s, t: e.t })), ms);
|
|
862
|
+
return { comps: r.comps.map(c => c[0]), left: r.left };
|
|
863
|
+
}
|
|
864
|
+
export function ranksOfCalls(nodes, points, edges, ms = 1000) {
|
|
865
|
+
const ns = nodes.map((vars, i) => ({ name: `runs ${i}`, hyps: [], concl: yes, vars, level: 0, given: true }));
|
|
866
|
+
const name = nodes.length === 1 ? shared : own(ns), idx = nodes.map((_, i) => i);
|
|
867
|
+
const { comps, left } = lexRanks(idx, ns, nodes.map((_, i) => points.filter(p => p.node === i).map(p => ({ env: p.env, calls: new Set() }))), edges, name, clock() + ms);
|
|
868
|
+
return { comps: comps.map(c => ns.map((nd, n) => ({ coef: Object.fromEntries(nd.vars.map((x, j) => [x, c[name(n, j)] ?? 0])), c: c[name(n, 'b')] ?? 0 }))), left };
|
|
636
869
|
}
|
|
637
870
|
const compE = (c, n, node, name) => unfeat(linE(Object.fromEntries(node.vars.map((x, j) => [x, c[name(n, j)] ?? 0])), c[name(n, 'b')] ?? 0));
|
|
638
871
|
// Ranks of degree 2: a product of two of a node's variables (a square too) a further variable of the LP, its value at
|
|
@@ -882,7 +1115,7 @@ export function claimInstances(facts, claim, depth = 2) {
|
|
|
882
1115
|
return instancesFor(facts, { eqs, arity, values: {}, memo: new Map(), fuel: 0, depth: 0 }, nodeOf(claim, 0, true), depth).insts;
|
|
883
1116
|
}
|
|
884
1117
|
export function findCycles(facts, claims, opts = {}) {
|
|
885
|
-
const t0 =
|
|
1118
|
+
const t0 = clock(), until = t0 + (opts.ms ?? 10_000), depth = opts.depth ?? 1;
|
|
886
1119
|
const { eqs, arity } = equations(facts);
|
|
887
1120
|
const cx = { eqs, arity, values: opts.values ?? {}, memo: new Map(), fuel: 20_000, depth: 0 };
|
|
888
1121
|
const big = Math.max(0, ...constsOf([facts.map(f => f.holds), claims]).filter(c => c <= 1000));
|
|
@@ -901,7 +1134,7 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
901
1134
|
console.error(`[cycles] ${sp.name}: rank (${sp.rank.map(showE).join(', ')}), ${sp.insts.length} instances, uses ${sp.uses.map(u => `${u.node}@{${Object.entries(u.subst).map(([x, t]) => `${x} := ${showE(t)}`).join(', ')}}`).join(' ')}`);
|
|
902
1135
|
const out = withDeadline(until, () => proveCyclic(facts, b.specs));
|
|
903
1136
|
if (trace)
|
|
904
|
-
console.error(`[cycles] ${out.proven ? 'proven' : `${out.node}: ${out.goal} ${out.stuck}`} at ${Math.round(
|
|
1137
|
+
console.error(`[cycles] ${out.proven ? 'proven' : `${out.node}: ${out.goal} ${out.stuck}`} at ${Math.round(clock() - t0)} ms`);
|
|
905
1138
|
if (!out.proven) {
|
|
906
1139
|
const at = nodes.find(n => n.name === out.node) ?? nodes[0];
|
|
907
1140
|
return { failed: at, verdict: { proven: false, checked: false, goal: out.goal, stuck: out.stuck } };
|
|
@@ -913,7 +1146,7 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
913
1146
|
// dropped in turn where the rest are proven without it (only what the claims need is kept).
|
|
914
1147
|
const attempt = (start, depth, quad) => {
|
|
915
1148
|
let nodes = start, done;
|
|
916
|
-
for (let round = 0; round <= start.length && nodes.length &&
|
|
1149
|
+
for (let round = 0; round <= start.length && nodes.length && clock() < until && !done; round++) {
|
|
917
1150
|
const t = once(nodes, depth, quad);
|
|
918
1151
|
if ('proven' in t) {
|
|
919
1152
|
done = t.proven;
|
|
@@ -924,11 +1157,11 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
924
1157
|
nodes = nodes.filter(n => n !== t.failed);
|
|
925
1158
|
}
|
|
926
1159
|
if (!done)
|
|
927
|
-
return { proven: false, checked: false, why:
|
|
1160
|
+
return { proven: false, checked: false, why: clock() >= until ? 'out of time' : 'every candidate dropped' };
|
|
928
1161
|
if (opts.houdini)
|
|
929
1162
|
return done;
|
|
930
1163
|
for (const c of nodes.filter(n => !n.given)) {
|
|
931
|
-
if (
|
|
1164
|
+
if (clock() >= until)
|
|
932
1165
|
break;
|
|
933
1166
|
const rest = nodes.filter(n => n !== c), t = once(rest, depth, quad);
|
|
934
1167
|
if ('proven' in t && t.proven.checked)
|
|
@@ -951,7 +1184,7 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
951
1184
|
];
|
|
952
1185
|
const tried = new Set();
|
|
953
1186
|
for (const [d, t, quad] of tries) {
|
|
954
|
-
if (
|
|
1187
|
+
if (clock() >= until)
|
|
955
1188
|
break;
|
|
956
1189
|
const nodes = t();
|
|
957
1190
|
if (tried.has(id([d, nodes.map(n => n.name), quad])))
|
|
@@ -1018,12 +1251,21 @@ const locations = (rel) => {
|
|
|
1018
1251
|
}
|
|
1019
1252
|
return { values, fromOf, toOf, names, at: live.map(s => [...s].sort()) };
|
|
1020
1253
|
};
|
|
1021
|
-
|
|
1254
|
+
// A rank from a relation made elsewhere (core/data.ts: a ring of functions' calls, a location per function, each
|
|
1255
|
+
// call's argument sizes bounded from its parameters' and fields'): per location, each component's linear form over the
|
|
1256
|
+
// names (no regions: those read an atom, not a form).
|
|
1257
|
+
export function rankOfPaths(name, rel, until) {
|
|
1258
|
+
const r = relationRank({ name }, rel, until);
|
|
1259
|
+
if (!('rank' in r))
|
|
1260
|
+
return r;
|
|
1261
|
+
return r.forms ? { forms: r.forms, values: locations(rel).values } : { why: 'a rank by regions' };
|
|
1262
|
+
}
|
|
1263
|
+
function relationRank(l, rel, until, extra = [], inv) {
|
|
1022
1264
|
const { values, fromOf, toOf, names, at } = locations(rel);
|
|
1023
1265
|
const every = [...new Set(at.flat())].sort();
|
|
1024
1266
|
const gpaths = [];
|
|
1025
1267
|
for (const [i, p] of rel.paths.entries()) {
|
|
1026
|
-
if (
|
|
1268
|
+
if (clock() > until)
|
|
1027
1269
|
return { why: 'out of time on the relation' };
|
|
1028
1270
|
const rows = [...p.rows, ...(extra[fromOf(i)] ?? [])];
|
|
1029
1271
|
const ns = [...new Set([...rows.flatMap(r => Object.keys(r)), ...Object.values(p.post).flatMap(r => Object.keys(r)), ...every])].filter(x => x !== '1').sort();
|
|
@@ -1037,7 +1279,7 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1037
1279
|
const unknown = (tp, j, n, x) => (x === 1 ? `b:${tp.tag}${j}:${n}` : `a:${tp.tag}${j}:${tp.own ? n : '*'}:${x}`);
|
|
1038
1280
|
// a node: a location, or one side of an atom at a location (regions, below)
|
|
1039
1281
|
const nodeLoc = values.map((_, n) => n);
|
|
1040
|
-
const varsAt = (tp, n) => (tp.own ? at[nodeLoc[n]] :
|
|
1282
|
+
const varsAt = (tp, n) => (tp.own ? at[nodeLoc[n]] : tp.names);
|
|
1041
1283
|
const fAt = (tp, j, n, x, t) => {
|
|
1042
1284
|
const out = {};
|
|
1043
1285
|
for (const v of varsAt(tp, n))
|
|
@@ -1062,11 +1304,16 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1062
1304
|
const holds = (p, h, c) => {
|
|
1063
1305
|
const env = (g) => Object.fromEntries(p.gens.names.map((x, i) => [x, g[i]]));
|
|
1064
1306
|
const tOf = (g) => g[p.gens.names.length];
|
|
1065
|
-
|
|
1307
|
+
// (each row once; one that reads no unknown and holds, along a name the template doesn't read, left out)
|
|
1308
|
+
const out = new Map();
|
|
1309
|
+
for (const r of [
|
|
1066
1310
|
...p.gens.vertices.map(g => plusL(scaleL(h(env(g), tOf(g)), -1), { 1: c * tOf(g) })),
|
|
1067
1311
|
...p.gens.rays.map(g => scaleL(h(env(g), 0), -1)),
|
|
1068
1312
|
...p.gens.lines.flatMap(g => [h(env(g), 0), scaleL(h(env(g), 0), -1)]),
|
|
1069
|
-
]
|
|
1313
|
+
])
|
|
1314
|
+
if (Object.keys(r).some(x => x !== '1') || (r['1'] ?? 0) > 0)
|
|
1315
|
+
out.set(id(Object.keys(r).sort().map(x => [x, r[x]])), r);
|
|
1316
|
+
return [...out.values()];
|
|
1070
1317
|
};
|
|
1071
1318
|
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);
|
|
1072
1319
|
const strictRows = (tp, p) => [
|
|
@@ -1075,7 +1322,12 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1075
1322
|
...holds(p, (x, t) => fAt(tp, tp.depth - 1, p.from, x, t), tp.depth === 1 ? 1 : 0),
|
|
1076
1323
|
];
|
|
1077
1324
|
const weakRows = (tp, p) => Array.from({ length: tp.depth }, (_, j) => holds(p, delta(tp, j, p), 0)).flat();
|
|
1078
|
-
|
|
1325
|
+
let scale = 1;
|
|
1326
|
+
for (const p of gpaths)
|
|
1327
|
+
for (const g of p.gens.vertices)
|
|
1328
|
+
for (const x of g)
|
|
1329
|
+
if (Math.abs(x) + 1 > scale)
|
|
1330
|
+
scale = Math.abs(x) + 1;
|
|
1079
1331
|
const sat = (w, rows) => rows.every(r => valueAt(r, w) <= 0);
|
|
1080
1332
|
// One block over the paths left: strict on all of them at once, else on as many as one after another allows.
|
|
1081
1333
|
const block = (tp, left, greedy, until) => {
|
|
@@ -1091,7 +1343,7 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1091
1343
|
const must = [];
|
|
1092
1344
|
let w;
|
|
1093
1345
|
for (const p of left) {
|
|
1094
|
-
if (
|
|
1346
|
+
if (clock() > until)
|
|
1095
1347
|
break;
|
|
1096
1348
|
if (w && sat(w, strict.get(p)))
|
|
1097
1349
|
continue;
|
|
@@ -1114,17 +1366,19 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1114
1366
|
const ranked = (paths, tag0, until) => {
|
|
1115
1367
|
let left = paths;
|
|
1116
1368
|
const mine = [], sizes = [];
|
|
1117
|
-
|
|
1369
|
+
// a shared template's names: those live where the component's paths begin or end
|
|
1370
|
+
const names = [...new Set(paths.flatMap(p => [...at[nodeLoc[p.from]], ...at[nodeLoc[p.to]]]))].sort();
|
|
1371
|
+
while (left.length && mine.length < 16 && clock() < until) {
|
|
1118
1372
|
const tag = `${tag0}${mine.length}.`;
|
|
1119
1373
|
// depth 1 first, all at once then one path after another; then deeper
|
|
1120
|
-
const order = [1, 2, 3].flatMap(depth => [false, true].flatMap(greedy => [false, true].map((own) => [{ depth, own, tag }, greedy])));
|
|
1374
|
+
const order = [1, 2, 3].flatMap(depth => [false, true].flatMap(greedy => [false, true].map((own) => [{ depth, own, tag, names }, greedy])));
|
|
1121
1375
|
let found;
|
|
1122
1376
|
for (const [tp, greedy] of order) {
|
|
1123
|
-
if (found ||
|
|
1377
|
+
if (found || clock() > until)
|
|
1124
1378
|
break;
|
|
1125
|
-
const t1 =
|
|
1379
|
+
const t1 = clock(), b = block(tp, left, greedy, until);
|
|
1126
1380
|
if (trace)
|
|
1127
|
-
console.error(`[cycles] ${l.name}: block ${tag} depth ${tp.depth}${tp.own ? ' own' : ''}${greedy ? ' greedy' : ''}: ${b ? b.strict.length : 'none'} of ${left.length} paths, ${Math.round(
|
|
1381
|
+
console.error(`[cycles] ${l.name}: block ${tag} depth ${tp.depth}${tp.own ? ' own' : ''}${greedy ? ' greedy' : ''}: ${b ? b.strict.length : 'none'} of ${left.length} paths, ${Math.round(clock() - t1)} ms`);
|
|
1128
1382
|
if (b && b.strict.length)
|
|
1129
1383
|
found = { ...b, tp };
|
|
1130
1384
|
}
|
|
@@ -1145,60 +1399,136 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1145
1399
|
left = left.filter(p => !strict.includes(p));
|
|
1146
1400
|
}
|
|
1147
1401
|
if (left.length)
|
|
1148
|
-
return { why:
|
|
1402
|
+
return { why: clock() >= until ? 'out of time on the relation' : 'past 16 components' };
|
|
1149
1403
|
return { parts: mine, sizes };
|
|
1150
1404
|
};
|
|
1151
|
-
// Regions: a component with no rank, its locations split by
|
|
1152
|
-
//
|
|
1153
|
-
//
|
|
1405
|
+
// Regions: a component with no rank, its locations split by atoms (one, then two at once): the atoms its paths read
|
|
1406
|
+
// (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
|
|
1407
|
+
// 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
|
|
1408
|
+
// (if atom then f else g). With invariants (`inv`), each node's own first, by Houdini over every path of the relation
|
|
1409
|
+
// split the same way: disjunctive invariants (x ≤ −1 where x ≥ 1 fails, after x := 1 or x := −1), each a law
|
|
1410
|
+
// (pc = ℓ ∧ the signs → atom) the kernel proves inductive with the rest.
|
|
1154
1411
|
const after1 = (p, a) => { let o = {}; for (const [x, c] of Object.entries(a))
|
|
1155
1412
|
o = plusL(o, x !== '1' && p.post[x] ? scaleL(p.post[x], c) : { [x]: c }); return o; };
|
|
1156
1413
|
const side = (a, yes) => (yes ? a : plusL({ 1: 1 }, a, -1));
|
|
1414
|
+
const regionLaws = [], regionTexts = [];
|
|
1157
1415
|
const regions = (c, paths) => {
|
|
1158
|
-
const seen = new Set(),
|
|
1159
|
-
|
|
1160
|
-
if (!Object.keys(r).every(x => x === '1' || names.has(x)) || Object.keys(r).length < 2)
|
|
1161
|
-
continue;
|
|
1416
|
+
const seen = new Set(), guards = [], deltas = [];
|
|
1417
|
+
const add = (r, to) => {
|
|
1162
1418
|
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();
|
|
1163
1419
|
if (!seen.has(key)) {
|
|
1164
1420
|
seen.add(key);
|
|
1165
|
-
|
|
1421
|
+
to.push(r);
|
|
1166
1422
|
}
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1423
|
+
};
|
|
1424
|
+
for (const r of paths.flatMap(p => p.rows))
|
|
1425
|
+
if (Object.keys(r).every(x => x === '1' || names.has(x)) && Object.keys(r).length >= 2)
|
|
1426
|
+
add(r, guards);
|
|
1427
|
+
for (const p of paths)
|
|
1428
|
+
for (const [x, f] of Object.entries(p.post)) {
|
|
1429
|
+
const d = plusL(f, { [x]: 1 }, -1);
|
|
1430
|
+
if (Object.keys(d).some(y => y !== '1') && Object.keys(d).every(y => y === '1' || every.includes(y)))
|
|
1431
|
+
add(plusL({ 1: 1 }, d, -1), deltas); // d ≥ 1, over live names
|
|
1432
|
+
}
|
|
1433
|
+
guards.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
|
|
1434
|
+
// (the signs of what paths add first: fewer, and each a direction of progress; then the guards' atoms)
|
|
1435
|
+
const singles = [...deltas.slice(0, 4), ...guards.slice(0, 8)], few = singles.slice(0, 4);
|
|
1436
|
+
// (two atoms at once only with the regions' own invariants: without them, the relation's search is the first of
|
|
1437
|
+
// several, and one atom's regions are what it had)
|
|
1438
|
+
const tries = [...singles.map(a => [a]), ...(inv ? few.flatMap((a, i) => few.slice(i + 1).map(b => [a, b])) : [])];
|
|
1439
|
+
if (trace)
|
|
1440
|
+
console.error(`[cycles] ${l.name}: component ${c}: ${tries.length} splits to try`);
|
|
1169
1441
|
const locs = values.flatMap((_, n) => (comp[n] === c ? [n] : []));
|
|
1170
|
-
for (const [ai,
|
|
1171
|
-
if (
|
|
1442
|
+
for (const [ai, as] of tries.entries()) {
|
|
1443
|
+
if (clock() > until)
|
|
1172
1444
|
return undefined;
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1445
|
+
// (each try its share of the time left)
|
|
1446
|
+
const mine = clock() + (until - clock()) / Math.max(2, tries.length - ai);
|
|
1447
|
+
// (every location split, not only the component's: a disjunction an invariant needs is often made before it, x := 1
|
|
1448
|
+
// or x := −1 on the way in)
|
|
1449
|
+
const K = as.length, base = nodeLoc.length, node = (n, bits) => base + (n << K) + bits;
|
|
1450
|
+
for (const n of values.keys())
|
|
1451
|
+
for (let b = 0; b < 1 << K; b++)
|
|
1452
|
+
nodeLoc.push(n);
|
|
1453
|
+
const sides = (p, bits, after) => as.map((a, i) => side(after ? after1(p, a) : a, ((bits >> i) & 1) === 0));
|
|
1454
|
+
// (undefined where a path's generators aren't found, past their cap or the time: a path left out is no path ranked)
|
|
1455
|
+
const splitOf = (ps, extra = () => []) => {
|
|
1456
|
+
const out = [];
|
|
1457
|
+
for (const p of ps)
|
|
1458
|
+
for (let b1 = 0; b1 < 1 << K; b1++)
|
|
1459
|
+
for (let b2 = 0; b2 < 1 << K; b2++) {
|
|
1460
|
+
const rows = [...p.rows, ...sides(p, b1, false), ...sides(p, b2, true), ...extra(node(p.from, b1))];
|
|
1461
|
+
// (over the path's names and any an atom reads beside them: a name missing would drop its coefficient)
|
|
1462
|
+
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 => Object.keys(r).filter(x => x !== '1'))])].sort() : p.gens.names;
|
|
1463
|
+
const gens = generators(rows, ns, rel.nats, 600, mine);
|
|
1464
|
+
if (!gens)
|
|
1465
|
+
return undefined;
|
|
1466
|
+
if (gens.vertices.length)
|
|
1467
|
+
out.push({ from: node(p.from, b1), to: node(p.to, b2), gens, post: p.post, rows });
|
|
1468
|
+
}
|
|
1469
|
+
return out;
|
|
1470
|
+
};
|
|
1471
|
+
const conds = as.map(a => leC(rel, a));
|
|
1472
|
+
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)) });
|
|
1473
|
+
const answer = (out) => ({ parts: out.parts.map(fs => values.map((_, n) => (locs.includes(n) ? term(fs, n) : k(0)))), sizes: out.sizes });
|
|
1474
|
+
// (with invariants to find, the split is ranked once, with its regions' own: more rows, no fewer ranks)
|
|
1475
|
+
if (!inv) {
|
|
1476
|
+
const split = splitOf(paths);
|
|
1477
|
+
if (!split)
|
|
1478
|
+
continue;
|
|
1479
|
+
const out = ranked(split, `${c}.r${ai}.`, mine);
|
|
1480
|
+
if (trace)
|
|
1481
|
+
console.error(`[cycles] ${l.name}: component ${c} split by ${conds.map(showC).join(' and ')}: ${'parts' in out ? out.parts.length + ' parts' : out.why}`);
|
|
1482
|
+
if ('parts' in out)
|
|
1483
|
+
return answer(out);
|
|
1484
|
+
continue;
|
|
1191
1485
|
}
|
|
1486
|
+
// the nodes' invariants: Houdini over every path split, each node's candidates its location's, those false at a
|
|
1487
|
+
// start in its region dropped
|
|
1488
|
+
const N = values.length << K;
|
|
1489
|
+
const split0 = splitOf(gpaths);
|
|
1490
|
+
if (!split0)
|
|
1491
|
+
continue;
|
|
1492
|
+
const cands = Array.from({ length: N }, (_, j) => {
|
|
1493
|
+
const n = j >> K, bits = j & ((1 << K) - 1);
|
|
1494
|
+
const here = inv.starts.filter(([m, env]) => m === n && as.every((a, i) => valueAt(side(a, ((bits >> i) & 1) === 0), env) <= 0));
|
|
1495
|
+
return (inv.cands[n] ?? []).filter(h => here.every(([, env]) => valueAt(h, env) <= 0));
|
|
1496
|
+
});
|
|
1497
|
+
const relSplit = { ...rel, paths: split0.map(p => ({ rows: p.rows, pins: {}, post: p.post })) };
|
|
1498
|
+
const H = houdini(relSplit, cands, i => [split0[i].from - base, split0[i].to - base], mine);
|
|
1499
|
+
if (trace && !H)
|
|
1500
|
+
console.error(`[cycles] ${l.name}: component ${c} split by ${conds.map(showC).join(' and ')}: Houdini out of time`);
|
|
1501
|
+
if (!H)
|
|
1502
|
+
continue;
|
|
1503
|
+
const Ht = H.map(inv.tightest);
|
|
1504
|
+
const split = splitOf(paths, nd => Ht[nd - base] ?? []);
|
|
1505
|
+
if (!split)
|
|
1506
|
+
continue;
|
|
1507
|
+
const out = ranked(split, `${c}.h${ai}.`, mine);
|
|
1508
|
+
if (trace)
|
|
1509
|
+
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}`);
|
|
1510
|
+
if (!('parts' in out))
|
|
1511
|
+
continue;
|
|
1512
|
+
for (let j = 0; j < N; j++)
|
|
1513
|
+
for (const h of Ht[j]) {
|
|
1514
|
+
const n = j >> K, bits = j & ((1 << K) - 1), atom = leC(rel, h);
|
|
1515
|
+
const not = [...(rel.loc ? [eqC(v(rel.loc), k(values[n]))] : []), ...as.map((a, i) => leC(rel, side(a, ((bits >> i) & 1) === 0)))];
|
|
1516
|
+
regionLaws.push({ name: `region invariant ${c}.${j}.${regionLaws.length}`, holds: { op: 'or', xs: [...not.map((x) => ({ op: 'not', x })), atom] } });
|
|
1517
|
+
regionTexts.push(`${not.map(showC).join(' ∧ ')} → ${showC(atom)}`);
|
|
1518
|
+
}
|
|
1519
|
+
return answer(out);
|
|
1192
1520
|
}
|
|
1193
1521
|
return undefined;
|
|
1194
1522
|
};
|
|
1195
1523
|
const parts = []; // per component of the locations: its parts, each a term per location
|
|
1524
|
+
const lins = []; // the same as forms, where no regions were needed
|
|
1196
1525
|
const sizes = [];
|
|
1197
1526
|
for (const c of [...new Set(comp)].sort((a, b) => a - b)) {
|
|
1198
1527
|
// (half the time left for the component as it is: the regions have the rest)
|
|
1199
|
-
const inner = gpaths.filter(p => comp[p.from] === c && comp[p.to] === c), out = ranked(inner, `${c}.`,
|
|
1528
|
+
const inner = gpaths.filter(p => comp[p.from] === c && comp[p.to] === c), out = ranked(inner, `${c}.`, clock() + (until - clock()) / 2);
|
|
1200
1529
|
if ('parts' in out) {
|
|
1201
1530
|
parts[c] = out.parts.map(fs => values.map((_, n) => termOf(rel, fs[n])));
|
|
1531
|
+
lins[c] = out.parts;
|
|
1202
1532
|
sizes.push(...out.sizes);
|
|
1203
1533
|
continue;
|
|
1204
1534
|
}
|
|
@@ -1206,6 +1536,7 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1206
1536
|
if (!r)
|
|
1207
1537
|
return out;
|
|
1208
1538
|
parts[c] = r.parts;
|
|
1539
|
+
lins[c] = undefined;
|
|
1209
1540
|
sizes.push(...r.sizes);
|
|
1210
1541
|
}
|
|
1211
1542
|
// per location, its component's parts in order (0 past them), the heights first where paths join components
|
|
@@ -1221,7 +1552,10 @@ function relationRank(l, rel, until, extra = []) {
|
|
|
1221
1552
|
});
|
|
1222
1553
|
if (!rank.length)
|
|
1223
1554
|
rank.push(k(0));
|
|
1224
|
-
|
|
1555
|
+
const linear = [...new Set(comp)].every(c => lins[c] || !parts[c]);
|
|
1556
|
+
const forms = linear ? [...(gpaths.some(p => comp[p.from] !== comp[p.to]) ? [values.map((_, n) => konstL(heightOf(comp[n])))] : []),
|
|
1557
|
+
...Array.from({ length: width }, (_, j) => values.map((_, n) => lins[comp[n]]?.[j]?.[n] ?? {}))] : undefined;
|
|
1558
|
+
return { rank, text: `(${rank.map(showE).join(', ')})`, blocks: sizes, laws: regionLaws, texts: regionTexts, ...(forms ? { forms } : {}) };
|
|
1225
1559
|
}
|
|
1226
1560
|
// Invariants first, so a rank may assume them: atoms per location (each name's bounds at the constants the paths
|
|
1227
1561
|
// read, and the paths' own atoms over the state and params), those false at a start dropped (the loop's starts, run
|
|
@@ -1271,8 +1605,20 @@ export function rankWithInvariants(l, laws, until) {
|
|
|
1271
1605
|
const K = [...consts].sort((a, b) => Math.abs(a) - Math.abs(b) || a - b).slice(0, 24);
|
|
1272
1606
|
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()];
|
|
1273
1607
|
// per location, over the names live there: their bounds at the constants, then (a second try) the paths' atoms too
|
|
1274
|
-
|
|
1275
|
-
const
|
|
1608
|
+
// (and 1 ≤ 0: the location unreachable, where every path into it leaves from states the rest rule out)
|
|
1609
|
+
const bounds = values.map((_, n) => [{ 1: 1 }, ...at[n].flatMap(x => K.flatMap((c) => [plusL({ [x]: 1 }, konstL(-c)), plusL({ [x]: -1 }, konstL(c))]))]);
|
|
1610
|
+
// 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₁)
|
|
1611
|
+
const copies = values.map(() => []);
|
|
1612
|
+
for (const [i, p] of rel.paths.entries())
|
|
1613
|
+
for (const [x, f] of Object.entries(p.post)) {
|
|
1614
|
+
const ys = Object.keys(f).filter(y => y !== '1');
|
|
1615
|
+
if (ys.length !== 1 || f[ys[0]] !== 1 || ys[0] === x || !names.has(ys[0]))
|
|
1616
|
+
continue;
|
|
1617
|
+
const y = ys[0], kept = p.post[y] ? id(p.post[y]) === id({ [y]: 1 }) : true;
|
|
1618
|
+
if (kept)
|
|
1619
|
+
copies[toOf(i)].push(plusL({ [x]: 1, [y]: -1 }, konstL(-(f['1'] ?? 0))), plusL({ [x]: -1, [y]: 1 }, konstL(f['1'] ?? 0)));
|
|
1620
|
+
}
|
|
1621
|
+
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)))]);
|
|
1276
1622
|
// the starts: random params (the precondition's), the state they begin in
|
|
1277
1623
|
const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 }, rand = seeded(31);
|
|
1278
1624
|
const starts = [];
|
|
@@ -1301,6 +1647,10 @@ export function rankWithInvariants(l, laws, until) {
|
|
|
1301
1647
|
};
|
|
1302
1648
|
// of the bounds on one name each way, the tightest (the others follow from it: the same set)
|
|
1303
1649
|
const tightest = (hs) => {
|
|
1650
|
+
// (a location no run reaches: 1 ≤ 0 alone)
|
|
1651
|
+
const never = hs.find(c => Object.keys(c).every(x => x === '1') && (c['1'] ?? 0) > 0);
|
|
1652
|
+
if (never)
|
|
1653
|
+
return [never];
|
|
1304
1654
|
const best = new Map(), rest = [];
|
|
1305
1655
|
for (const c of hs) {
|
|
1306
1656
|
const xs = Object.keys(c).filter(x => x !== '1');
|
|
@@ -1315,15 +1665,20 @@ export function rankWithInvariants(l, laws, until) {
|
|
|
1315
1665
|
return [...best.values(), ...rest];
|
|
1316
1666
|
};
|
|
1317
1667
|
let H = [], found = { why: 'no invariant' };
|
|
1318
|
-
const t1 =
|
|
1668
|
+
const t1 = clock();
|
|
1319
1669
|
for (const [i, cands] of [bounds, withAtoms].entries()) {
|
|
1320
|
-
if (
|
|
1670
|
+
if (clock() > until)
|
|
1321
1671
|
break;
|
|
1322
|
-
const closed = houdini(rel, atStarts(cands), locOf, i ? until :
|
|
1323
|
-
if (
|
|
1672
|
+
const closed = houdini(rel, atStarts(cands), locOf, i ? until : clock() + (until - clock()) / 2);
|
|
1673
|
+
if (trace)
|
|
1674
|
+
console.error(`[cycles] ${l.name}: houdini round ${i}: ${closed ? closed.map(h => h.map(x => showC(leC(rel, x))).join(" ∧ ")).join(" | ") : "none"}`);
|
|
1675
|
+
if (!closed)
|
|
1676
|
+
continue;
|
|
1677
|
+
// (with none at any location, the regions' own may still be found: the second try only)
|
|
1678
|
+
if (!closed.some(h => h.length) && !i)
|
|
1324
1679
|
continue;
|
|
1325
1680
|
H = closed.map(tightest);
|
|
1326
|
-
found = relationRank(l, rel, until, H);
|
|
1681
|
+
found = relationRank(l, rel, i ? until : clock() + (until - clock()) / 2, H, { cands: atStarts(cands), starts, tightest });
|
|
1327
1682
|
if ('rank' in found)
|
|
1328
1683
|
break;
|
|
1329
1684
|
found = { why: `with ${H.flat().length} invariants: ${found.why}` };
|
|
@@ -1331,11 +1686,12 @@ export function rankWithInvariants(l, laws, until) {
|
|
|
1331
1686
|
if (!('rank' in found))
|
|
1332
1687
|
return found;
|
|
1333
1688
|
// fewer: a location's atoms at once, then one atom at a time, within ten times the first search's time
|
|
1334
|
-
const stop = Math.min(until,
|
|
1689
|
+
const stop = Math.min(until, clock() + Math.max(500, 10 * (clock() - t1)));
|
|
1335
1690
|
const without = (drop) => {
|
|
1336
1691
|
const fewer = houdini(rel, H.map((g, n) => g.filter(h => !drop(n, h))), locOf, stop);
|
|
1337
1692
|
if (!fewer || fewer.flat().length === H.flat().length)
|
|
1338
1693
|
return false;
|
|
1694
|
+
// (no regions' own invariants here: they would only find again the ones dropped)
|
|
1339
1695
|
const r = relationRank(l, rel, stop, fewer);
|
|
1340
1696
|
if ('rank' in r) {
|
|
1341
1697
|
H = fewer;
|
|
@@ -1345,19 +1701,20 @@ export function rankWithInvariants(l, laws, until) {
|
|
|
1345
1701
|
return false;
|
|
1346
1702
|
};
|
|
1347
1703
|
for (const n of H.keys()) {
|
|
1348
|
-
if (
|
|
1704
|
+
if (clock() > stop)
|
|
1349
1705
|
break;
|
|
1350
1706
|
if (H[n].length)
|
|
1351
1707
|
without(m => m === n);
|
|
1352
1708
|
}
|
|
1353
1709
|
for (const [n, hs] of H.map((h, n) => [n, [...h]]))
|
|
1354
1710
|
for (const h of hs) {
|
|
1355
|
-
if (
|
|
1711
|
+
if (clock() > stop)
|
|
1356
1712
|
break;
|
|
1357
1713
|
if (H[n].includes(h))
|
|
1358
1714
|
without((m, g) => m === n && g === h);
|
|
1359
1715
|
}
|
|
1360
|
-
|
|
1716
|
+
const at0 = asLaws(H);
|
|
1717
|
+
return { rank: found.rank, text: found.text, laws: [...at0.laws, ...found.laws], texts: [...at0.texts, ...found.texts] };
|
|
1361
1718
|
}
|
|
1362
1719
|
const seeded = (seed) => { let x = seed; return (n) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * n); }; };
|
|
1363
1720
|
const goalsProven = (goals) => {
|
|
@@ -1374,13 +1731,13 @@ const goalsProven = (goals) => {
|
|
|
1374
1731
|
// turn that stays in the loop an edge; then the kernel's halting goals, with invariants inferLaws finds for them where
|
|
1375
1732
|
// the rank needs one.
|
|
1376
1733
|
export function findRank(l, laws = [], opts = {}) {
|
|
1377
|
-
const t0 =
|
|
1734
|
+
const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(23);
|
|
1378
1735
|
const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 };
|
|
1379
1736
|
const state = Object.keys(l.state), names = [...state, ...l.params].sort();
|
|
1380
1737
|
const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
|
|
1381
1738
|
const points = new Map(), edges = new Map();
|
|
1382
1739
|
for (const bound of [2, 4, 8, 16, 32])
|
|
1383
|
-
for (let trial = 0; trial < 40 &&
|
|
1740
|
+
for (let trial = 0; trial < 40 && clock() < t0 + 1000; trial++) {
|
|
1384
1741
|
const ps = Object.fromEntries(l.params.map(p => [p, rand(bound + 1)]));
|
|
1385
1742
|
if (l.pre && evC(cx, l.pre, ps) !== true)
|
|
1386
1743
|
continue;
|
|
@@ -1429,7 +1786,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1429
1786
|
const quadratic = (ps, until) => {
|
|
1430
1787
|
const out = [];
|
|
1431
1788
|
for (const p of ps) {
|
|
1432
|
-
if (
|
|
1789
|
+
if (clock() > until)
|
|
1433
1790
|
break;
|
|
1434
1791
|
const d = withProducts([node], samples, [...edges.values()], [p]), r = lexRanks([0], d.nodes, d.samples, d.edges, shared, until);
|
|
1435
1792
|
if (!r.comps.length || r.left)
|
|
@@ -1458,7 +1815,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1458
1815
|
if ('trees' in tried[0].verdict)
|
|
1459
1816
|
return done(linear, tried[0].verdict.trees);
|
|
1460
1817
|
}
|
|
1461
|
-
// The relation's rank (per location, in phases), within
|
|
1818
|
+
// The relation's rank (per location, in phases), within a third of the time left; then degree 2 over the products the loop
|
|
1462
1819
|
// reads; then the relation's rank with invariants. (A search that throws, a stack too deep for a large loop say,
|
|
1463
1820
|
// gives way to the rest.)
|
|
1464
1821
|
const safely = (f) => { try {
|
|
@@ -1467,16 +1824,16 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1467
1824
|
catch (e) {
|
|
1468
1825
|
return { why: `the relation's search threw: ${e.message.slice(0, 120)}` };
|
|
1469
1826
|
} };
|
|
1470
|
-
const relT0 =
|
|
1827
|
+
const relT0 = clock(), rel = safely(() => rankOfRelation(l, laws, clock() + (until - clock()) / 3));
|
|
1471
1828
|
let relWhy = 'rank' in rel ? `the kernel refused ${rel.text}` : rel.why;
|
|
1472
1829
|
if (trace)
|
|
1473
|
-
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(
|
|
1830
|
+
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)`);
|
|
1474
1831
|
if ('rank' in rel) {
|
|
1475
|
-
const verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
|
|
1832
|
+
const k0 = performance.now(), verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
|
|
1833
|
+
if (trace)
|
|
1834
|
+
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}`}`);
|
|
1476
1835
|
if ('trees' in verdict)
|
|
1477
1836
|
return done(rel.rank, verdict.trees);
|
|
1478
|
-
if (trace)
|
|
1479
|
-
console.error(`[cycles] ${l.name}: the kernel refused ${rel.text} at ${verdict.goal}`);
|
|
1480
1837
|
relWhy = `the kernel refused ${rel.text.slice(0, 300)} at ${verdict.goal}`;
|
|
1481
1838
|
}
|
|
1482
1839
|
tried.push(...quadratic(read, until));
|
|
@@ -1485,7 +1842,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1485
1842
|
return done(won.rank, won.verdict.trees);
|
|
1486
1843
|
if (!('rank' in rel)) {
|
|
1487
1844
|
// invariants first: the relation's rank where they hold, with as few of them as it needs
|
|
1488
|
-
const inv = safely(() => rankWithInvariants(l, laws,
|
|
1845
|
+
const inv = safely(() => rankWithInvariants(l, laws, clock() + (until - clock()) / 2));
|
|
1489
1846
|
if (trace)
|
|
1490
1847
|
console.error(`[cycles] ${l.name}: the relation's rank with invariants ${'rank' in inv ? `${inv.text} with ${inv.texts.join('; ')}` : inv.why}`);
|
|
1491
1848
|
if ('rank' in inv) {
|
|
@@ -1506,7 +1863,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1506
1863
|
const base = tried[0];
|
|
1507
1864
|
if (base && !('trees' in base.verdict)) {
|
|
1508
1865
|
const rank = base.rank, m = loopMachine(l), { stay, cover, helps } = livenessParts(m, loopLiveness(l, rank));
|
|
1509
|
-
const ms = (until -
|
|
1866
|
+
const ms = (until - clock()) * (rest.length ? 0.5 : 1);
|
|
1510
1867
|
if (ms > 300) {
|
|
1511
1868
|
const inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
|
|
1512
1869
|
const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
|
|
@@ -1518,7 +1875,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1518
1875
|
}
|
|
1519
1876
|
}
|
|
1520
1877
|
// (the products the loop doesn't read within a quarter of its time: a search that fails tries each of them)
|
|
1521
|
-
tried = quadratic(rest, Math.min(until,
|
|
1878
|
+
tried = quadratic(rest, Math.min(until, clock() + (opts.ms ?? 10_000) / 4));
|
|
1522
1879
|
const late = tried.find(t => 'trees' in t.verdict);
|
|
1523
1880
|
if (late && 'trees' in late.verdict)
|
|
1524
1881
|
return done(late.rank, late.verdict.trees);
|
|
@@ -1528,7 +1885,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1528
1885
|
return { proven: false, checked: false, rank: base.rank, found: { rank: text, laws: [] }, goal: first.goal, stuck: first.stuck, ...(first.witness ? { witness: first.witness } : {}), why: `rank ${text} from the runs; no invariant found that it needs; the relation: ${relWhy}` };
|
|
1529
1886
|
}
|
|
1530
1887
|
export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
1531
|
-
const t0 =
|
|
1888
|
+
const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(29), run = interpret(m);
|
|
1532
1889
|
const names = [...Object.keys(m.state), ...m.params].sort(), helpful = livenessHelpful(l);
|
|
1533
1890
|
const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
|
|
1534
1891
|
const env = (ps, st) => ({ ...ps, ...st.scalars });
|
|
@@ -1541,7 +1898,7 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1541
1898
|
const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
|
|
1542
1899
|
const points = new Map(), strong = new Map(), weak = new Map();
|
|
1543
1900
|
for (const bound of [2, 4, 8, 16])
|
|
1544
|
-
for (let trial = 0; trial < 20 &&
|
|
1901
|
+
for (let trial = 0; trial < 20 && clock() < t0 + 1000; trial++) {
|
|
1545
1902
|
let ps;
|
|
1546
1903
|
try {
|
|
1547
1904
|
ps = sample.params(rand, bound);
|
|
@@ -1584,15 +1941,36 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1584
1941
|
st = next;
|
|
1585
1942
|
}
|
|
1586
1943
|
}
|
|
1944
|
+
// The trivial ranks first, where the runs allow them: the constant 0 (every helpful step in its region reaches `to` at
|
|
1945
|
+
// once: none sampled stays pending, which leaves the fit below nothing to fit), then each state variable alone (every
|
|
1946
|
+
// helpful step sampled that stays pending lowers it, and no other raises it), up to four of them. Rank 0 may take half
|
|
1947
|
+
// of what is left, each variable a quarter.
|
|
1948
|
+
const zero = { op: 'const', value: 0 }, tried = new Map();
|
|
1949
|
+
const keeps = (x) => [...weak.values()].every(e => e.t[x] <= e.s[x]), lowers = (x) => [...strong.values()].every(e => e.t[x] < e.s[x]);
|
|
1950
|
+
const trivial = [...(strong.size ? [] : [[zero]]), ...Object.keys(m.state).filter(x => keeps(x) && lowers(x)).slice(0, 4).map(name => [{ op: 'var', name }])];
|
|
1951
|
+
const rankText = (rank) => `(${rank.map(showE).join(', ')})`;
|
|
1952
|
+
for (const [i, rank] of trivial.entries()) {
|
|
1953
|
+
const ms = until - performance.now();
|
|
1954
|
+
if (ms < 200)
|
|
1955
|
+
break;
|
|
1956
|
+
const v = withDeadline(performance.now() + ms * (i === 0 && !strong.size ? 0.5 : 0.25), () => proveLiveness(m, laws, { ...l, rank }));
|
|
1957
|
+
if (v.proven && v.checked)
|
|
1958
|
+
return { proven: true, checked: true, rank, laws: [], found: { rank: rankText(rank), laws: [] } };
|
|
1959
|
+
tried.set(id(rank), v);
|
|
1960
|
+
}
|
|
1587
1961
|
const samples = [[...points.values()].map(env => ({ env, calls: new Set() }))];
|
|
1588
1962
|
const { comps, left } = lexRanks([0], [node], samples, [...strong.values()], shared, until, false, [...weak.values()]);
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
const
|
|
1963
|
+
const noRank = `no linear rank, in order, that ${strong.size} helpful steps sampled lower and ${weak.size} others keep`;
|
|
1964
|
+
const fitted = comps.length && !left ? comps.map(c => compE(c, 0, node, shared)) : undefined;
|
|
1965
|
+
// Past the fit, the invariants a rank needs: the fitted one's, or else rank 0's where the runs allow it.
|
|
1966
|
+
const rank = fitted ?? (strong.size ? undefined : [zero]);
|
|
1967
|
+
if (!rank)
|
|
1968
|
+
return { proven: false, checked: false, why: noRank };
|
|
1969
|
+
const text = rankText(rank), lv = { ...l, rank };
|
|
1970
|
+
const first = tried.get(id(rank)) ?? withDeadline(until, () => proveLiveness(m, laws, lv));
|
|
1593
1971
|
if (first.proven && first.checked)
|
|
1594
1972
|
return { proven: true, checked: true, rank, laws: [], found: { rank: text, laws: [] } };
|
|
1595
|
-
const ms = until -
|
|
1973
|
+
const ms = until - clock();
|
|
1596
1974
|
if (ms > 300) {
|
|
1597
1975
|
const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
|
|
1598
1976
|
const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
|
|
@@ -1602,10 +1980,13 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1602
1980
|
return { proven: true, checked: true, rank, laws: more, found: { rank: text, laws: kept.map(f => f.text) } };
|
|
1603
1981
|
}
|
|
1604
1982
|
}
|
|
1605
|
-
|
|
1983
|
+
const failed = first.failed ? { goal: first.failed.goal, stuck: first.failed.stuck, ...(first.failed.witness ? { witness: first.failed.witness } : {}) } : {};
|
|
1984
|
+
if (!fitted)
|
|
1985
|
+
return { proven: false, checked: false, ...failed, why: `${noRank}; rank ${text}, which the runs allow, not proven, nor with the invariants found` };
|
|
1986
|
+
return { proven: false, checked: false, rank, found: { rank: text, laws: [] }, ...failed, why: `rank ${text} from the runs; the kernel's goals not proven with it` };
|
|
1606
1987
|
}
|
|
1607
1988
|
export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
|
|
1608
|
-
const until =
|
|
1989
|
+
const until = clock() + (opts.ms ?? 10_000);
|
|
1609
1990
|
const fns = Object.entries(m.fns ?? {}).filter(([, f]) => !f.recur && (f.arity ?? 1) === 1);
|
|
1610
1991
|
const fns2 = Object.entries(m.fns ?? {}).filter(([, f]) => !f.recur && f.arity === 2 && f.call);
|
|
1611
1992
|
if ((!fns.length && !fns2.length) || !m.facts?.length)
|
|
@@ -1698,16 +2079,16 @@ export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
|
|
|
1698
2079
|
const unique = [...new Map(claims.map(c => [c.name, c])).values()], two = (c) => m.fns?.[readsOf(c.concl)[0]?.map ?? '']?.arity === 2;
|
|
1699
2080
|
const proofs = new Map();
|
|
1700
2081
|
for (const c of unique.filter(two)) {
|
|
1701
|
-
if (
|
|
2082
|
+
if (clock() >= until)
|
|
1702
2083
|
break;
|
|
1703
|
-
const o = findCycles(facts, [c], { ms: Math.min(1000, (until -
|
|
2084
|
+
const o = findCycles(facts, [c], { ms: Math.min(1000, (until - clock()) * 0.1), values, houdini: true, generalize: false });
|
|
1704
2085
|
if (o.proven && o.checked && o.proof)
|
|
1705
2086
|
proofs.set(c.name, o.proof);
|
|
1706
2087
|
}
|
|
1707
2088
|
const ones = unique.filter(c => !two(c));
|
|
1708
2089
|
if (!ones.length && !proofs.size)
|
|
1709
2090
|
return { proven: false, checked: false, found: [], why: unique.length ? 'no lemma proven' : 'no lemma fits the values' };
|
|
1710
|
-
const out = ones.length ? findCycles(facts, ones, { ms: Math.max(0, until -
|
|
2091
|
+
const out = ones.length ? findCycles(facts, ones, { ms: Math.max(0, until - clock()) * 0.6, values, houdini: true, generalize: false }) : { proven: true, checked: true, kept: [] };
|
|
1711
2092
|
if ((!out.proven || !out.checked || !out.kept?.length) && !proofs.size)
|
|
1712
2093
|
return { proven: false, checked: false, found: [], why: out.why ?? 'no lemma proven' };
|
|
1713
2094
|
const kept = [...(out.proven && out.checked ? out.kept ?? [] : []), ...proofs.keys()];
|
|
@@ -1732,7 +2113,7 @@ export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
|
|
|
1732
2113
|
if (!best.ok)
|
|
1733
2114
|
return { proven: false, checked: false, found: [], why: `lemmas proven (${found.map(f => f.text).join('; ')}), the laws not with them` };
|
|
1734
2115
|
for (const f of [...found]) {
|
|
1735
|
-
if (
|
|
2116
|
+
if (clock() >= until)
|
|
1736
2117
|
break;
|
|
1737
2118
|
const rest = found.filter(g => g !== f), again = proveWith(rest);
|
|
1738
2119
|
if (again.ok)
|