gdp-wired 0.22.0 → 0.24.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 +27 -2
- package/dist/core/bmc.d.ts +49 -0
- package/dist/core/bmc.js +509 -0
- package/dist/core/check.d.ts +1 -1
- package/dist/core/check.js +19 -6
- package/dist/core/cycles.d.ts +38 -0
- package/dist/core/cycles.js +531 -43
- package/dist/core/data.d.ts +25 -1
- package/dist/core/data.js +984 -215
- package/dist/core/discover.js +8 -3
- package/dist/core/dsl.d.ts +17 -3
- package/dist/core/dsl.js +81 -15
- 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.js +518 -5
- package/dist/core/kind.d.ts +30 -0
- package/dist/core/kind.js +81 -0
- package/dist/core/nonterm.d.ts +34 -0
- package/dist/core/nonterm.js +610 -0
- package/dist/core/q.d.ts +17 -0
- package/dist/core/q.js +52 -0
- package/dist/core/rationals.d.ts +112 -0
- package/dist/core/rationals.js +281 -0
- package/dist/core/relation.d.ts +28 -0
- package/dist/core/relation.js +483 -0
- package/dist/core/solver.d.ts +5 -2
- package/dist/core/solver.js +65 -20
- package/dist/core/transfer.d.ts +3 -3
- package/dist/core/transfer.js +69 -42
- package/dist/core/xstate.d.ts +6 -0
- package/dist/core/xstate.js +70 -12
- package/dist/kernel/cdcl.d.ts +13 -0
- package/dist/kernel/cdcl.js +307 -236
- package/dist/kernel/kernel.d.ts +106 -0
- package/dist/kernel/kernel.js +342 -0
- package/dist/kernel/prove.js +14 -3
- package/dist/kernel/qprove.d.ts +18 -0
- package/dist/kernel/qprove.js +157 -0
- package/dist/kernel/reader.d.ts +14 -0
- package/dist/kernel/reader.js +102 -14
- package/dist/kernel/simplex.d.ts +4 -0
- package/dist/kernel/simplex.js +38 -11
- package/dist/lean-kernel/emit.d.ts +46 -1
- package/dist/lean-kernel/emit.js +125 -16
- package/dist/lean-kernel/library.js +4 -1
- package/dist/lean-kernel/qlean.d.ts +26 -0
- package/dist/lean-kernel/qlean.js +105 -0
- package/package.json +16 -3
package/dist/core/cycles.js
CHANGED
|
@@ -2,9 +2,10 @@ 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 { 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
|
+
import { generators, houdini, relationOf } from "./relation.js";
|
|
8
9
|
// --- terms ----------------------------------------------------------------------------------------------------------
|
|
9
10
|
const v = (name) => ({ op: 'var', name }), k = (value) => ({ op: 'const', value });
|
|
10
11
|
const add = (a, b) => ({ op: 'add', a, b }), sub = (a, b) => ({ op: 'sub', a, b });
|
|
@@ -392,7 +393,7 @@ const valueAt = (l, w) => Object.entries(l).reduce((s, [x, c]) => s + c * (x ===
|
|
|
392
393
|
// either sign, each bound doubled up to 4 and the constants' first small, then up to the samples' size: the first found
|
|
393
394
|
// is small (x + y, not 33·x + y; total − cur, not 26 − cur), and a rank the samples' size bounds is left to the next
|
|
394
395
|
// component (two phases: (x, y)). A fit's coefficients (c:) go up to 128.
|
|
395
|
-
function lp(must, pool, until, scale = 1, signs = [true, false]) {
|
|
396
|
+
function lp(must, pool, until, scale = 1, signs = [true, false], whole = false) {
|
|
396
397
|
const unknowns = [...new Set([...must, ...pool].flatMap(l => Object.keys(l)).filter(x => x !== '1'))];
|
|
397
398
|
const fit = unknowns.some(x => x.startsWith('c:')), bounds = fit ? [1, 2, 4, 16, 128] : [1, 2, 4];
|
|
398
399
|
const stage = (natural, bound, wide) => {
|
|
@@ -401,7 +402,7 @@ function lp(must, pool, until, scale = 1, signs = [true, false]) {
|
|
|
401
402
|
const b = x.startsWith('b:') ? (wide ? bound * scale : bound) : bound;
|
|
402
403
|
rows.push({ [x]: 1, 1: -b }, natural ? { [x]: -1 } : { [x]: -1, 1: -b });
|
|
403
404
|
}
|
|
404
|
-
for (let round = 0; round < 40 &&
|
|
405
|
+
for (let round = 0; round < 40 && clock() < until; round++) {
|
|
405
406
|
const out = solve(rows.map(lin => ({ lin, label: '' })), 4000);
|
|
406
407
|
if (out.kind !== 'sat')
|
|
407
408
|
break;
|
|
@@ -415,7 +416,7 @@ function lp(must, pool, until, scale = 1, signs = [true, false]) {
|
|
|
415
416
|
// The widest box first: where it has no solution, none of the smaller has. Past it, a rank's rows (homogeneous in the
|
|
416
417
|
// unknowns, the drop's constant aside) are solved exactly over the rationals, the solution scaled to whole numbers.
|
|
417
418
|
if (!stage(signs.at(-1), bounds.at(-1), true))
|
|
418
|
-
return fit ? undefined : exactLp(must, pool, until);
|
|
419
|
+
return fit ? undefined : exactLp(must, pool, until, whole);
|
|
419
420
|
for (const natural of signs)
|
|
420
421
|
for (const bound of bounds)
|
|
421
422
|
for (const wide of [false, true]) {
|
|
@@ -442,7 +443,9 @@ const qlt = (a, b) => a.n * b.d < b.n * a.d;
|
|
|
442
443
|
function simplex(T, basis, cost, open, until) {
|
|
443
444
|
const cols = cost.length;
|
|
444
445
|
for (let it = 0; it < 5000; it++) {
|
|
445
|
-
|
|
446
|
+
// (each pivot counted as work, as the solver's rows are: a counted search's clock runs while it solves)
|
|
447
|
+
work.n += 1 + ((T.length * cols) >> 6);
|
|
448
|
+
if (clock() > until)
|
|
446
449
|
return false;
|
|
447
450
|
let enter = -1;
|
|
448
451
|
for (let j = 0; j < cols && enter < 0; j++) {
|
|
@@ -556,12 +559,13 @@ function exactSolve(rows, until) {
|
|
|
556
559
|
// turn's change) and kept only where it holds of all of them: a coefficient the runs' size forces (32·x + y where x
|
|
557
560
|
// reaches 33, a reset y := x − 1 in the runs) grows with the runs, and is refused, where one a turn's change forces
|
|
558
561
|
// (11·x + 2·y, six tokens for a coin and a coin for five) is the same on both.
|
|
559
|
-
|
|
562
|
+
// `whole`: rows that are facts, not samples (a path's generators, core/relation.ts), solved over all of them.
|
|
563
|
+
function exactLp(must, pool, until, whole = false) {
|
|
560
564
|
const size = (l) => { let m = 0; for (const x in l)
|
|
561
565
|
if (x !== '1')
|
|
562
566
|
m = Math.max(m, Math.abs(l[x])); return m; };
|
|
563
|
-
const sizes = pool.map(size), half = sizes.reduce((a, b) => Math.max(a, b), 0) / 2, small = pool.filter((_, i) => sizes[i] <= half), rows = [...must];
|
|
564
|
-
for (let round = 0; round < 40 &&
|
|
567
|
+
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];
|
|
568
|
+
for (let round = 0; round < 40 && clock() < until; round++) {
|
|
565
569
|
const w = exactSolve(rows, until);
|
|
566
570
|
if (!w)
|
|
567
571
|
return undefined;
|
|
@@ -596,13 +600,13 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
|
|
|
596
600
|
let left = [...new Map(edges.map(e => { const l = delta(e); return [id(l), l]; })).values()];
|
|
597
601
|
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)));
|
|
598
602
|
const comps = [];
|
|
599
|
-
while (left.length && comps.length < 4 &&
|
|
603
|
+
while (left.length && comps.length < 4 && clock() < until) {
|
|
600
604
|
let sum = {};
|
|
601
605
|
const strict = (l) => valueAt(l, sum) < 0;
|
|
602
606
|
// One try per pattern of signs (which unknowns an edge raises and lowers): edges alike drop alike, mostly.
|
|
603
607
|
const tried = new Set(), sign = (l) => id(Object.keys(l).filter(x => x !== '1').sort().map(x => `${x}${Math.sign(l[x])}`));
|
|
604
608
|
for (const l of left) {
|
|
605
|
-
if (strict(l) ||
|
|
609
|
+
if (strict(l) || clock() > until || tried.has(sign(l)) || tried.size > 40)
|
|
606
610
|
continue;
|
|
607
611
|
tried.add(sign(l));
|
|
608
612
|
const w = lp([plus(l, { 1: 1 })], [...left, ...keep, ...points], until, scale);
|
|
@@ -626,11 +630,20 @@ function lexRanks(idx, nodes, samples, edges, name, until, onEdges = false, weak
|
|
|
626
630
|
}
|
|
627
631
|
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
|
|
628
632
|
// The same over named naturals and the edges of runs alone (core/data.ts: a recursive function's calls, each from its
|
|
629
|
-
// parameters' sizes to its arguments'): each component's coefficient per variable and its constant.
|
|
633
|
+
// parameters' sizes to its arguments'): each component's coefficient per variable and its constant. Several nodes (a
|
|
634
|
+
// ring of functions calling each other, each its own names; `nodes`), each its own coefficients and constant per
|
|
635
|
+
// component (a rank per location: (size(x), 1) at one function, (size(x), 0) at the one it calls with x). Its budget,
|
|
636
|
+
// `ms`, is read on the shared clock (kernel/prove.ts's `clock`): counted work inside a counted search, its pivots counted
|
|
637
|
+
// as the solver's rows are, so a counted search's verdict doesn't depend on the machine's speed.
|
|
630
638
|
export function ranksOfRuns(vars, points, edges, ms = 1000) {
|
|
631
|
-
const
|
|
632
|
-
|
|
633
|
-
|
|
639
|
+
const r = ranksOfCalls([vars], points.map(env => ({ node: 0, env })), edges.map(e => ({ from: 0, to: 0, s: e.s, t: e.t })), ms);
|
|
640
|
+
return { comps: r.comps.map(c => c[0]), left: r.left };
|
|
641
|
+
}
|
|
642
|
+
export function ranksOfCalls(nodes, points, edges, ms = 1000) {
|
|
643
|
+
const ns = nodes.map((vars, i) => ({ name: `runs ${i}`, hyps: [], concl: yes, vars, level: 0, given: true }));
|
|
644
|
+
const name = nodes.length === 1 ? shared : own(ns), idx = nodes.map((_, i) => i);
|
|
645
|
+
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);
|
|
646
|
+
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 };
|
|
634
647
|
}
|
|
635
648
|
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));
|
|
636
649
|
// 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
|
|
@@ -880,7 +893,7 @@ export function claimInstances(facts, claim, depth = 2) {
|
|
|
880
893
|
return instancesFor(facts, { eqs, arity, values: {}, memo: new Map(), fuel: 0, depth: 0 }, nodeOf(claim, 0, true), depth).insts;
|
|
881
894
|
}
|
|
882
895
|
export function findCycles(facts, claims, opts = {}) {
|
|
883
|
-
const t0 =
|
|
896
|
+
const t0 = clock(), until = t0 + (opts.ms ?? 10_000), depth = opts.depth ?? 1;
|
|
884
897
|
const { eqs, arity } = equations(facts);
|
|
885
898
|
const cx = { eqs, arity, values: opts.values ?? {}, memo: new Map(), fuel: 20_000, depth: 0 };
|
|
886
899
|
const big = Math.max(0, ...constsOf([facts.map(f => f.holds), claims]).filter(c => c <= 1000));
|
|
@@ -899,7 +912,7 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
899
912
|
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(' ')}`);
|
|
900
913
|
const out = withDeadline(until, () => proveCyclic(facts, b.specs));
|
|
901
914
|
if (trace)
|
|
902
|
-
console.error(`[cycles] ${out.proven ? 'proven' : `${out.node}: ${out.goal} ${out.stuck}`} at ${Math.round(
|
|
915
|
+
console.error(`[cycles] ${out.proven ? 'proven' : `${out.node}: ${out.goal} ${out.stuck}`} at ${Math.round(clock() - t0)} ms`);
|
|
903
916
|
if (!out.proven) {
|
|
904
917
|
const at = nodes.find(n => n.name === out.node) ?? nodes[0];
|
|
905
918
|
return { failed: at, verdict: { proven: false, checked: false, goal: out.goal, stuck: out.stuck } };
|
|
@@ -911,7 +924,7 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
911
924
|
// dropped in turn where the rest are proven without it (only what the claims need is kept).
|
|
912
925
|
const attempt = (start, depth, quad) => {
|
|
913
926
|
let nodes = start, done;
|
|
914
|
-
for (let round = 0; round <= start.length && nodes.length &&
|
|
927
|
+
for (let round = 0; round <= start.length && nodes.length && clock() < until && !done; round++) {
|
|
915
928
|
const t = once(nodes, depth, quad);
|
|
916
929
|
if ('proven' in t) {
|
|
917
930
|
done = t.proven;
|
|
@@ -922,11 +935,11 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
922
935
|
nodes = nodes.filter(n => n !== t.failed);
|
|
923
936
|
}
|
|
924
937
|
if (!done)
|
|
925
|
-
return { proven: false, checked: false, why:
|
|
938
|
+
return { proven: false, checked: false, why: clock() >= until ? 'out of time' : 'every candidate dropped' };
|
|
926
939
|
if (opts.houdini)
|
|
927
940
|
return done;
|
|
928
941
|
for (const c of nodes.filter(n => !n.given)) {
|
|
929
|
-
if (
|
|
942
|
+
if (clock() >= until)
|
|
930
943
|
break;
|
|
931
944
|
const rest = nodes.filter(n => n !== c), t = once(rest, depth, quad);
|
|
932
945
|
if ('proven' in t && t.proven.checked)
|
|
@@ -949,7 +962,7 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
949
962
|
];
|
|
950
963
|
const tried = new Set();
|
|
951
964
|
for (const [d, t, quad] of tries) {
|
|
952
|
-
if (
|
|
965
|
+
if (clock() >= until)
|
|
953
966
|
break;
|
|
954
967
|
const nodes = t();
|
|
955
968
|
if (tried.has(id([d, nodes.map(n => n.name), quad])))
|
|
@@ -962,6 +975,416 @@ export function findCycles(facts, claims, opts = {}) {
|
|
|
962
975
|
}
|
|
963
976
|
return last;
|
|
964
977
|
}
|
|
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
|
+
// A form over the relation's names as the kernel's term (an integer's coefficient on its two parts), read truncated.
|
|
988
|
+
const termOf = (rel, f) => {
|
|
989
|
+
const coef = {};
|
|
990
|
+
for (const [x, a] of Object.entries(f)) {
|
|
991
|
+
if (x === '1')
|
|
992
|
+
continue;
|
|
993
|
+
const p = rel.ints.get(x);
|
|
994
|
+
if (p) {
|
|
995
|
+
coef[p[0]] = a;
|
|
996
|
+
coef[p[1]] = -a;
|
|
997
|
+
}
|
|
998
|
+
else
|
|
999
|
+
coef[x] = a;
|
|
1000
|
+
}
|
|
1001
|
+
return linE(coef, f['1'] ?? 0);
|
|
1002
|
+
};
|
|
1003
|
+
export function rankOfRelation(l, laws, until) {
|
|
1004
|
+
const rel = relationOf(l, laws);
|
|
1005
|
+
return rel ? relationRank(l, rel, until) : { why: 'the turn is not linear (a map, a flag, or past the paths\' cap)' };
|
|
1006
|
+
}
|
|
1007
|
+
// `extra`: atoms (each ≤ 0) that hold at each location (by its index among the locations' values), read as rows of the
|
|
1008
|
+
// paths that leave it.
|
|
1009
|
+
// The locations (the values of the location natural, sorted; one with none), and the names each location's rank may
|
|
1010
|
+
// read: those its paths' rows read, and what the values after read of the names read where the paths go (live).
|
|
1011
|
+
const locations = (rel) => {
|
|
1012
|
+
const values = rel.loc ? [...new Set([...rel.from, ...rel.to])].sort((a, b) => a - b) : [0];
|
|
1013
|
+
const fromOf = (i) => (rel.loc ? values.indexOf(rel.from[i]) : 0), toOf = (i) => (rel.loc ? values.indexOf(rel.to[i]) : 0);
|
|
1014
|
+
const names = new Set([...rel.state, ...rel.params]), live = values.map(() => new Set());
|
|
1015
|
+
for (const [i, p] of rel.paths.entries())
|
|
1016
|
+
for (const r of p.rows)
|
|
1017
|
+
for (const x of Object.keys(r))
|
|
1018
|
+
if (names.has(x))
|
|
1019
|
+
live[fromOf(i)].add(x);
|
|
1020
|
+
for (let grew = true; grew;) {
|
|
1021
|
+
grew = false;
|
|
1022
|
+
for (const [i, p] of rel.paths.entries())
|
|
1023
|
+
for (const x of live[toOf(i)])
|
|
1024
|
+
for (const y of p.post[x] ? Object.keys(p.post[x]) : [x])
|
|
1025
|
+
if (names.has(y) && !live[fromOf(i)].has(y)) {
|
|
1026
|
+
live[fromOf(i)].add(y);
|
|
1027
|
+
grew = true;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return { values, fromOf, toOf, names, at: live.map(s => [...s].sort()) };
|
|
1031
|
+
};
|
|
1032
|
+
// A rank from a relation made elsewhere (core/data.ts: a ring of functions' calls, a location per function, each
|
|
1033
|
+
// call's argument sizes bounded from its parameters' and fields'): per location, each component's linear form over the
|
|
1034
|
+
// names (no regions: those read an atom, not a form).
|
|
1035
|
+
export function rankOfPaths(name, rel, until) {
|
|
1036
|
+
const r = relationRank({ name }, rel, until);
|
|
1037
|
+
if (!('rank' in r))
|
|
1038
|
+
return r;
|
|
1039
|
+
return r.forms ? { forms: r.forms, values: locations(rel).values } : { why: 'a rank by regions' };
|
|
1040
|
+
}
|
|
1041
|
+
function relationRank(l, rel, until, extra = []) {
|
|
1042
|
+
const { values, fromOf, toOf, names, at } = locations(rel);
|
|
1043
|
+
const every = [...new Set(at.flat())].sort();
|
|
1044
|
+
const gpaths = [];
|
|
1045
|
+
for (const [i, p] of rel.paths.entries()) {
|
|
1046
|
+
if (clock() > until)
|
|
1047
|
+
return { why: 'out of time on the relation' };
|
|
1048
|
+
const rows = [...p.rows, ...(extra[fromOf(i)] ?? [])];
|
|
1049
|
+
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();
|
|
1050
|
+
const gens = generators(rows, ns, rel.nats, 600, until);
|
|
1051
|
+
if (!gens)
|
|
1052
|
+
return { why: 'a path past the generators\' cap' };
|
|
1053
|
+
if (gens.vertices.length)
|
|
1054
|
+
gpaths.push({ from: fromOf(i), to: toOf(i), gens, post: p.post, rows });
|
|
1055
|
+
}
|
|
1056
|
+
// A template's value at a generator (x, t), as a form over the unknowns; after the turn, through the path's values.
|
|
1057
|
+
const unknown = (tp, j, n, x) => (x === 1 ? `b:${tp.tag}${j}:${n}` : `a:${tp.tag}${j}:${tp.own ? n : '*'}:${x}`);
|
|
1058
|
+
// a node: a location, or one side of an atom at a location (regions, below)
|
|
1059
|
+
const nodeLoc = values.map((_, n) => n);
|
|
1060
|
+
const varsAt = (tp, n) => (tp.own ? at[nodeLoc[n]] : every);
|
|
1061
|
+
const fAt = (tp, j, n, x, t) => {
|
|
1062
|
+
const out = {};
|
|
1063
|
+
for (const v of varsAt(tp, n))
|
|
1064
|
+
if (x[v])
|
|
1065
|
+
out[unknown(tp, j, n, v)] = x[v];
|
|
1066
|
+
if (t)
|
|
1067
|
+
out[unknown(tp, j, n, 1)] = t;
|
|
1068
|
+
return out;
|
|
1069
|
+
};
|
|
1070
|
+
const postAt = (p, x, t) => {
|
|
1071
|
+
const out = { ...x };
|
|
1072
|
+
for (const [v, f] of Object.entries(p.post)) {
|
|
1073
|
+
let s = 0;
|
|
1074
|
+
for (const [u, c] of Object.entries(f))
|
|
1075
|
+
s += c * (u === '1' ? t : x[u] ?? 0);
|
|
1076
|
+
out[v] = s;
|
|
1077
|
+
}
|
|
1078
|
+
return out;
|
|
1079
|
+
};
|
|
1080
|
+
// Rows (≤ 0) saying h ≥ c at every point of the path: at each vertex h(x, t) ≥ c·t, along each ray h's linear part
|
|
1081
|
+
// ≥ 0, along each line = 0.
|
|
1082
|
+
const holds = (p, h, c) => {
|
|
1083
|
+
const env = (g) => Object.fromEntries(p.gens.names.map((x, i) => [x, g[i]]));
|
|
1084
|
+
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
|
+
];
|
|
1090
|
+
};
|
|
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);
|
|
1092
|
+
const strictRows = (tp, p) => [
|
|
1093
|
+
...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(),
|
|
1095
|
+
...holds(p, (x, t) => fAt(tp, tp.depth - 1, p.from, x, t), tp.depth === 1 ? 1 : 0),
|
|
1096
|
+
];
|
|
1097
|
+
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))));
|
|
1099
|
+
const sat = (w, rows) => rows.every(r => valueAt(r, w) <= 0);
|
|
1100
|
+
// One block over the paths left: strict on all of them at once, else on as many as one after another allows.
|
|
1101
|
+
const block = (tp, left, greedy, until) => {
|
|
1102
|
+
// (each path's rows made once for the template)
|
|
1103
|
+
const strict = new Map(left.map(p => [p, strictRows(tp, p)])), weak = new Map();
|
|
1104
|
+
const weakOf = (q) => { let r = weak.get(q); if (!r)
|
|
1105
|
+
weak.set(q, r = weakRows(tp, q)); return r; };
|
|
1106
|
+
// all at once (a greedy try follows the same template's try of this, so it doesn't make it again)
|
|
1107
|
+
if (!greedy) {
|
|
1108
|
+
const all = lp(left.flatMap(p => strict.get(p)), [], until, scale, undefined, true);
|
|
1109
|
+
return all && { w: all, strict: left };
|
|
1110
|
+
}
|
|
1111
|
+
const must = [];
|
|
1112
|
+
let w;
|
|
1113
|
+
for (const p of left) {
|
|
1114
|
+
if (clock() > until)
|
|
1115
|
+
break;
|
|
1116
|
+
if (w && sat(w, strict.get(p)))
|
|
1117
|
+
continue;
|
|
1118
|
+
const rows = strict.get(p), w2 = lp([...must, ...rows], left.filter(q => q !== p).flatMap(weakOf), until, scale, undefined, true);
|
|
1119
|
+
if (w2) {
|
|
1120
|
+
must.push(...rows);
|
|
1121
|
+
w = w2;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
return w && { w, strict: left.filter(p => sat(w, strict.get(p))) };
|
|
1125
|
+
};
|
|
1126
|
+
// The locations' components: a path between two drops by the first part of the rank, the component's height; the
|
|
1127
|
+
// paths within each are ranked on their own (their locations are no other's, so the parts line up per location).
|
|
1128
|
+
const graph = values.map(() => new Set());
|
|
1129
|
+
for (const p of gpaths)
|
|
1130
|
+
graph[p.from].add(p.to);
|
|
1131
|
+
const comp = sccs(graph.map(g => [...g])), height = [];
|
|
1132
|
+
const heightOf = (c) => (height[c] ??= Math.max(0, ...values.flatMap((_, n) => (comp[n] === c ? [...graph[n]].filter(m => comp[m] !== c).map(m => heightOf(comp[m]) + 1) : []))));
|
|
1133
|
+
// The paths of one component in order of blocks: each component a form per node.
|
|
1134
|
+
const ranked = (paths, tag0, until) => {
|
|
1135
|
+
let left = paths;
|
|
1136
|
+
const mine = [], sizes = [];
|
|
1137
|
+
while (left.length && mine.length < 8 && clock() < until) {
|
|
1138
|
+
const tag = `${tag0}${mine.length}.`;
|
|
1139
|
+
// 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])));
|
|
1141
|
+
let found;
|
|
1142
|
+
for (const [tp, greedy] of order) {
|
|
1143
|
+
if (found || clock() > until)
|
|
1144
|
+
break;
|
|
1145
|
+
const t1 = clock(), b = block(tp, left, greedy, until);
|
|
1146
|
+
if (trace)
|
|
1147
|
+
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`);
|
|
1148
|
+
if (b && b.strict.length)
|
|
1149
|
+
found = { ...b, tp };
|
|
1150
|
+
}
|
|
1151
|
+
if (!found)
|
|
1152
|
+
return { why: `no block of a nested rank per location is strict on any of the ${left.length} paths left (of ${gpaths.length})` };
|
|
1153
|
+
const { w, tp, strict } = found;
|
|
1154
|
+
for (let j = 0; j < tp.depth; j++)
|
|
1155
|
+
mine.push(nodeLoc.map((_, n) => {
|
|
1156
|
+
const f = {};
|
|
1157
|
+
for (const x of varsAt(tp, n)) {
|
|
1158
|
+
const a = w[unknown(tp, j, n, x)] ?? 0;
|
|
1159
|
+
if (a)
|
|
1160
|
+
f[x] = a;
|
|
1161
|
+
}
|
|
1162
|
+
return plusL(f, { 1: (tp.depth === 1 ? 0 : 1) + (w[unknown(tp, j, n, 1)] ?? 0) });
|
|
1163
|
+
}));
|
|
1164
|
+
sizes.push(tp.depth);
|
|
1165
|
+
left = left.filter(p => !strict.includes(p));
|
|
1166
|
+
}
|
|
1167
|
+
if (left.length)
|
|
1168
|
+
return { why: clock() >= until ? 'out of time on the relation' : 'past 8 components' };
|
|
1169
|
+
return { parts: mine, sizes };
|
|
1170
|
+
};
|
|
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));
|
|
1177
|
+
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();
|
|
1183
|
+
if (!seen.has(key)) {
|
|
1184
|
+
seen.add(key);
|
|
1185
|
+
atoms.push(r);
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
atoms.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
|
|
1189
|
+
const locs = values.flatMap((_, n) => (comp[n] === c ? [n] : []));
|
|
1190
|
+
for (const [ai, a] of atoms.slice(0, 8).entries()) {
|
|
1191
|
+
if (clock() > until)
|
|
1192
|
+
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 };
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
return undefined;
|
|
1214
|
+
};
|
|
1215
|
+
const parts = []; // per component of the locations: its parts, each a term per location
|
|
1216
|
+
const lins = []; // the same as forms, where no regions were needed
|
|
1217
|
+
const sizes = [];
|
|
1218
|
+
for (const c of [...new Set(comp)].sort((a, b) => a - b)) {
|
|
1219
|
+
// (half the time left for the component as it is: the regions have the rest)
|
|
1220
|
+
const inner = gpaths.filter(p => comp[p.from] === c && comp[p.to] === c), out = ranked(inner, `${c}.`, clock() + (until - clock()) / 2);
|
|
1221
|
+
if ('parts' in out) {
|
|
1222
|
+
parts[c] = out.parts.map(fs => values.map((_, n) => termOf(rel, fs[n])));
|
|
1223
|
+
lins[c] = out.parts;
|
|
1224
|
+
sizes.push(...out.sizes);
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
const r = regions(c, inner);
|
|
1228
|
+
if (!r)
|
|
1229
|
+
return out;
|
|
1230
|
+
parts[c] = r.parts;
|
|
1231
|
+
lins[c] = undefined;
|
|
1232
|
+
sizes.push(...r.sizes);
|
|
1233
|
+
}
|
|
1234
|
+
// per location, its component's parts in order (0 past them), the heights first where paths join components
|
|
1235
|
+
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]))))] : []),
|
|
1237
|
+
...Array.from({ length: width }, (_, j) => values.map((_, n) => parts[comp[n]]?.[j]?.[n] ?? k(0)))];
|
|
1238
|
+
const rank = columns.map(terms => {
|
|
1239
|
+
let e = terms.at(-1) ?? k(0);
|
|
1240
|
+
for (let n = terms.length - 2; n >= 0; n--)
|
|
1241
|
+
if (id(terms[n]) !== id(e))
|
|
1242
|
+
e = { op: 'if', c: eqC(v(rel.loc), k(values[n])), then: terms[n], else: e };
|
|
1243
|
+
return e;
|
|
1244
|
+
});
|
|
1245
|
+
if (!rank.length)
|
|
1246
|
+
rank.push(k(0));
|
|
1247
|
+
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])))] : []),
|
|
1249
|
+
...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 } : {}) };
|
|
1251
|
+
}
|
|
1252
|
+
// Invariants first, so a rank may assume them: atoms per location (each name's bounds at the constants the paths
|
|
1253
|
+
// read, and the paths' own atoms over the state and params), those false at a start dropped (the loop's starts, run
|
|
1254
|
+
// from random params), then Houdini over the relation (core/relation.ts). Each kept as a law at its location
|
|
1255
|
+
// (pc ≠ ℓ ∨ atom), which the kernel proves inductive with the halting goals; then each dropped in turn where the
|
|
1256
|
+
// relation's rank is still found without it (and those that leaned on it).
|
|
1257
|
+
const leC = (rel, f) => {
|
|
1258
|
+
const pos = [], neg = [];
|
|
1259
|
+
for (const [x, a] of Object.entries(f)) {
|
|
1260
|
+
if (x === '1') {
|
|
1261
|
+
if (a > 0)
|
|
1262
|
+
pos.push(k(a));
|
|
1263
|
+
else if (a < 0)
|
|
1264
|
+
neg.push(k(-a));
|
|
1265
|
+
continue;
|
|
1266
|
+
}
|
|
1267
|
+
const p = rel.ints.get(x), parts = p ? [[p[0], a], [p[1], -a]] : [[x, a]];
|
|
1268
|
+
for (const [y, c] of parts)
|
|
1269
|
+
(c > 0 ? pos : neg).push(Math.abs(c) === 1 ? v(y) : { op: 'mul', k: Math.abs(c), a: v(y) });
|
|
1270
|
+
}
|
|
1271
|
+
const sum = (xs) => (xs.length ? xs.reduce((s, x) => add(s, x)) : k(0));
|
|
1272
|
+
return le(sum(pos), sum(neg));
|
|
1273
|
+
};
|
|
1274
|
+
// The relation's rank with invariants: Houdini's set, then each atom dropped in turn where the set without it, closed
|
|
1275
|
+
// again (those that leaned on it dropped too), still gives a rank.
|
|
1276
|
+
export function rankWithInvariants(l, laws, until) {
|
|
1277
|
+
const rel = relationOf(l, laws);
|
|
1278
|
+
if (!rel)
|
|
1279
|
+
return { why: 'the turn is not linear' };
|
|
1280
|
+
const { values, fromOf, toOf, names, at } = locations(rel);
|
|
1281
|
+
const locOf = (i) => [fromOf(i), toOf(i)];
|
|
1282
|
+
const consts = new Set([0, 1, -1]);
|
|
1283
|
+
for (const p of rel.paths)
|
|
1284
|
+
for (const r of p.rows) {
|
|
1285
|
+
const c = r['1'] ?? 0, xs = Object.keys(r).filter(x => x !== '1');
|
|
1286
|
+
if (Math.abs(c) <= 1_000_000)
|
|
1287
|
+
for (const d of xs.length === 1 ? [c / Math.abs(r[xs[0]])] : [c])
|
|
1288
|
+
if (Number.isInteger(d)) {
|
|
1289
|
+
consts.add(d);
|
|
1290
|
+
consts.add(-d);
|
|
1291
|
+
consts.add(d + 1);
|
|
1292
|
+
consts.add(d - 1);
|
|
1293
|
+
consts.add(-d + 1);
|
|
1294
|
+
consts.add(-d - 1);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
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()];
|
|
1299
|
+
// 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)))]);
|
|
1302
|
+
// the starts: random params (the precondition's), the state they begin in
|
|
1303
|
+
const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 }, rand = seeded(31);
|
|
1304
|
+
const starts = [];
|
|
1305
|
+
for (let s = 0; s < 400; s++) {
|
|
1306
|
+
const big = [2, 8, 64, 1000, 1_000_000][s % 5], ps = Object.fromEntries(l.params.map(p => [p, rand(big + 1)]));
|
|
1307
|
+
if (l.pre && evC(cx, l.pre, ps) !== true)
|
|
1308
|
+
continue;
|
|
1309
|
+
const st = { ...ps };
|
|
1310
|
+
for (const [x, e] of Object.entries(l.state))
|
|
1311
|
+
st[x] = ev(cx, e, ps) ?? 0;
|
|
1312
|
+
const n = rel.loc ? values.indexOf(st[rel.loc] ?? -1) : 0;
|
|
1313
|
+
if (n < 0)
|
|
1314
|
+
continue;
|
|
1315
|
+
starts.push([n, Object.fromEntries([...names].map(x => { const p = rel.ints.get(x); return [x, p ? st[p[0]] - st[p[1]] : st[x] ?? 0]; }))]);
|
|
1316
|
+
}
|
|
1317
|
+
const atStarts = (cs) => cs.map((c, n) => c.filter(h => starts.every(([m, env]) => m !== n || valueAt(h, env) <= 0)));
|
|
1318
|
+
const asLaws = (H) => {
|
|
1319
|
+
const out = [], texts = [];
|
|
1320
|
+
for (const [n, hs] of H.entries())
|
|
1321
|
+
for (const [i, h] of hs.entries()) {
|
|
1322
|
+
const atom = leC(rel, h);
|
|
1323
|
+
out.push({ name: `invariant ${n}.${i}`, holds: rel.loc ? { op: 'or', xs: [{ op: 'not', x: eqC(v(rel.loc), k(values[n])) }, atom] } : atom });
|
|
1324
|
+
texts.push(`${rel.loc ? `${rel.loc} = ${values[n]} → ` : ''}${showC(atom)}`);
|
|
1325
|
+
}
|
|
1326
|
+
return { laws: out, texts };
|
|
1327
|
+
};
|
|
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
|
+
};
|
|
1343
|
+
let H = [], found = { why: 'no invariant' };
|
|
1344
|
+
const t1 = clock();
|
|
1345
|
+
for (const [i, cands] of [bounds, withAtoms].entries()) {
|
|
1346
|
+
if (clock() > until)
|
|
1347
|
+
break;
|
|
1348
|
+
const closed = houdini(rel, atStarts(cands), locOf, i ? until : clock() + (until - clock()) / 2);
|
|
1349
|
+
if (!closed || !closed.some(h => h.length))
|
|
1350
|
+
continue;
|
|
1351
|
+
H = closed.map(tightest);
|
|
1352
|
+
found = relationRank(l, rel, until, H);
|
|
1353
|
+
if ('rank' in found)
|
|
1354
|
+
break;
|
|
1355
|
+
found = { why: `with ${H.flat().length} invariants: ${found.why}` };
|
|
1356
|
+
}
|
|
1357
|
+
if (!('rank' in found))
|
|
1358
|
+
return found;
|
|
1359
|
+
// fewer: a location's atoms at once, then one atom at a time, within ten times the first search's time
|
|
1360
|
+
const stop = Math.min(until, clock() + Math.max(500, 10 * (clock() - t1)));
|
|
1361
|
+
const without = (drop) => {
|
|
1362
|
+
const fewer = houdini(rel, H.map((g, n) => g.filter(h => !drop(n, h))), locOf, stop);
|
|
1363
|
+
if (!fewer || fewer.flat().length === H.flat().length)
|
|
1364
|
+
return false;
|
|
1365
|
+
const r = relationRank(l, rel, stop, fewer);
|
|
1366
|
+
if ('rank' in r) {
|
|
1367
|
+
H = fewer;
|
|
1368
|
+
found = r;
|
|
1369
|
+
return true;
|
|
1370
|
+
}
|
|
1371
|
+
return false;
|
|
1372
|
+
};
|
|
1373
|
+
for (const n of H.keys()) {
|
|
1374
|
+
if (clock() > stop)
|
|
1375
|
+
break;
|
|
1376
|
+
if (H[n].length)
|
|
1377
|
+
without(m => m === n);
|
|
1378
|
+
}
|
|
1379
|
+
for (const [n, hs] of H.map((h, n) => [n, [...h]]))
|
|
1380
|
+
for (const h of hs) {
|
|
1381
|
+
if (clock() > stop)
|
|
1382
|
+
break;
|
|
1383
|
+
if (H[n].includes(h))
|
|
1384
|
+
without((m, g) => m === n && g === h);
|
|
1385
|
+
}
|
|
1386
|
+
return { rank: found.rank, text: found.text, ...asLaws(H) };
|
|
1387
|
+
}
|
|
965
1388
|
const seeded = (seed) => { let x = seed; return (n) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * n); }; };
|
|
966
1389
|
const goalsProven = (goals) => {
|
|
967
1390
|
const trees = {};
|
|
@@ -977,13 +1400,13 @@ const goalsProven = (goals) => {
|
|
|
977
1400
|
// turn that stays in the loop an edge; then the kernel's halting goals, with invariants inferLaws finds for them where
|
|
978
1401
|
// the rank needs one.
|
|
979
1402
|
export function findRank(l, laws = [], opts = {}) {
|
|
980
|
-
const t0 =
|
|
1403
|
+
const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(23);
|
|
981
1404
|
const cx = { eqs: new Map(), arity: new Map(), values: {}, memo: new Map(), fuel: Infinity, depth: 0 };
|
|
982
1405
|
const state = Object.keys(l.state), names = [...state, ...l.params].sort();
|
|
983
1406
|
const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
|
|
984
1407
|
const points = new Map(), edges = new Map();
|
|
985
1408
|
for (const bound of [2, 4, 8, 16, 32])
|
|
986
|
-
for (let trial = 0; trial < 40 &&
|
|
1409
|
+
for (let trial = 0; trial < 40 && clock() < t0 + 1000; trial++) {
|
|
987
1410
|
const ps = Object.fromEntries(l.params.map(p => [p, rand(bound + 1)]));
|
|
988
1411
|
if (l.pre && evC(cx, l.pre, ps) !== true)
|
|
989
1412
|
continue;
|
|
@@ -1020,7 +1443,8 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1020
1443
|
}
|
|
1021
1444
|
}
|
|
1022
1445
|
const samples = [[...points.values()].map(env => ({ env, calls: new Set() }))];
|
|
1023
|
-
|
|
1446
|
+
// (the runs' LP within 10% of the time: the relation's search below has its share)
|
|
1447
|
+
const { comps, left } = lexRanks([0], [node], samples, [...edges.values()], shared, Math.min(until, t0 + 0.1 * (opts.ms ?? 10_000)));
|
|
1024
1448
|
// Ranks of degree 2 where the linear one leaves turns or the kernel refuses it (while i < N·M: N·M − i, where the runs
|
|
1025
1449
|
// alone give 299 − i): one product of two variables at a time. The products the loop's own terms read first (a rank
|
|
1026
1450
|
// of degree 2 measures what its terms of degree 2 bound), before the invariants; the others after them, within a
|
|
@@ -1031,7 +1455,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1031
1455
|
const quadratic = (ps, until) => {
|
|
1032
1456
|
const out = [];
|
|
1033
1457
|
for (const p of ps) {
|
|
1034
|
-
if (
|
|
1458
|
+
if (clock() > until)
|
|
1035
1459
|
break;
|
|
1036
1460
|
const d = withProducts([node], samples, [...edges.values()], [p]), r = lexRanks([0], d.nodes, d.samples, d.edges, shared, until);
|
|
1037
1461
|
if (!r.comps.length || r.left)
|
|
@@ -1055,12 +1479,52 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1055
1479
|
let tried = [];
|
|
1056
1480
|
if (comps.length && !left) {
|
|
1057
1481
|
seen.add(id(linear));
|
|
1058
|
-
|
|
1482
|
+
// (its check within 20% of the time: the relation's search below has its share)
|
|
1483
|
+
tried.push({ rank: linear, verdict: withDeadline(Math.min(until, t0 + 0.2 * (opts.ms ?? 10_000)), () => goalsProven(loopObligations(l, laws, linear))) });
|
|
1484
|
+
if ('trees' in tried[0].verdict)
|
|
1485
|
+
return done(linear, tried[0].verdict.trees);
|
|
1486
|
+
}
|
|
1487
|
+
// The relation's rank (per location, in phases), within half the time left; then degree 2 over the products the loop
|
|
1488
|
+
// reads; then the relation's rank with invariants. (A search that throws, a stack too deep for a large loop say,
|
|
1489
|
+
// gives way to the rest.)
|
|
1490
|
+
const safely = (f) => { try {
|
|
1491
|
+
return f();
|
|
1492
|
+
}
|
|
1493
|
+
catch (e) {
|
|
1494
|
+
return { why: `the relation's search threw: ${e.message.slice(0, 120)}` };
|
|
1495
|
+
} };
|
|
1496
|
+
const relT0 = clock(), rel = safely(() => rankOfRelation(l, laws, clock() + (until - clock()) / 2));
|
|
1497
|
+
let relWhy = 'rank' in rel ? `the kernel refused ${rel.text}` : rel.why;
|
|
1498
|
+
if (trace)
|
|
1499
|
+
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
|
+
if ('rank' in rel) {
|
|
1501
|
+
const verdict = withDeadline(until, () => goalsProven(loopObligations(l, laws, rel.rank)));
|
|
1502
|
+
if ('trees' in verdict)
|
|
1503
|
+
return done(rel.rank, verdict.trees);
|
|
1504
|
+
if (trace)
|
|
1505
|
+
console.error(`[cycles] ${l.name}: the kernel refused ${rel.text} at ${verdict.goal}`);
|
|
1506
|
+
relWhy = `the kernel refused ${rel.text.slice(0, 300)} at ${verdict.goal}`;
|
|
1059
1507
|
}
|
|
1060
1508
|
tried.push(...quadratic(read, until));
|
|
1061
1509
|
const won = tried.find(t => 'trees' in t.verdict);
|
|
1062
1510
|
if (won && 'trees' in won.verdict)
|
|
1063
1511
|
return done(won.rank, won.verdict.trees);
|
|
1512
|
+
if (!('rank' in rel)) {
|
|
1513
|
+
// invariants first: the relation's rank where they hold, with as few of them as it needs
|
|
1514
|
+
const inv = safely(() => rankWithInvariants(l, laws, clock() + (until - clock()) / 2));
|
|
1515
|
+
if (trace)
|
|
1516
|
+
console.error(`[cycles] ${l.name}: the relation's rank with invariants ${'rank' in inv ? `${inv.text} with ${inv.texts.join('; ')}` : inv.why}`);
|
|
1517
|
+
if ('rank' in inv) {
|
|
1518
|
+
const verdict = withDeadline(until, () => goalsProven(loopObligations(l, [...laws, ...inv.laws], inv.rank)));
|
|
1519
|
+
if ('trees' in verdict)
|
|
1520
|
+
return done(inv.rank, verdict.trees, inv.laws, inv.texts);
|
|
1521
|
+
if (trace)
|
|
1522
|
+
console.error(`[cycles] ${l.name}: the kernel refused ${inv.text} with ${inv.laws.length} invariants at ${verdict.goal}`);
|
|
1523
|
+
relWhy = `${relWhy}; with ${inv.laws.length} invariants, the kernel refused ${inv.text.slice(0, 300)} at ${verdict.goal}`;
|
|
1524
|
+
}
|
|
1525
|
+
else
|
|
1526
|
+
relWhy = `${relWhy}; ${inv.why}`;
|
|
1527
|
+
}
|
|
1064
1528
|
if (!tried.length && comps.length)
|
|
1065
1529
|
tried.push({ rank: linear, verdict: withDeadline(until, () => goalsProven(loopObligations(l, laws, linear))) });
|
|
1066
1530
|
// Invariants the rank needs: the descent as the loop's step laws, inferLaws's candidates chosen by its counterexamples
|
|
@@ -1068,7 +1532,7 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1068
1532
|
const base = tried[0];
|
|
1069
1533
|
if (base && !('trees' in base.verdict)) {
|
|
1070
1534
|
const rank = base.rank, m = loopMachine(l), { stay, cover, helps } = livenessParts(m, loopLiveness(l, rank));
|
|
1071
|
-
const ms = (until -
|
|
1535
|
+
const ms = (until - clock()) * (rest.length ? 0.5 : 1);
|
|
1072
1536
|
if (ms > 300) {
|
|
1073
1537
|
const inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
|
|
1074
1538
|
const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
|
|
@@ -1080,17 +1544,17 @@ export function findRank(l, laws = [], opts = {}) {
|
|
|
1080
1544
|
}
|
|
1081
1545
|
}
|
|
1082
1546
|
// (the products the loop doesn't read within a quarter of its time: a search that fails tries each of them)
|
|
1083
|
-
tried = quadratic(rest, Math.min(until,
|
|
1547
|
+
tried = quadratic(rest, Math.min(until, clock() + (opts.ms ?? 10_000) / 4));
|
|
1084
1548
|
const late = tried.find(t => 'trees' in t.verdict);
|
|
1085
1549
|
if (late && 'trees' in late.verdict)
|
|
1086
1550
|
return done(late.rank, late.verdict.trees);
|
|
1087
1551
|
if (!base || 'trees' in base.verdict)
|
|
1088
|
-
return { proven: false, checked: false, why: `no rank, linear or of degree 2, in order, drops on every turn of ${edges.size} sampled` };
|
|
1552
|
+
return { proven: false, checked: false, why: `no rank, linear or of degree 2, in order, drops on every turn of ${edges.size} sampled; the relation: ${relWhy}` };
|
|
1089
1553
|
const text = `(${base.rank.map(showE).join(', ')})`, first = base.verdict;
|
|
1090
|
-
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` };
|
|
1554
|
+
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}` };
|
|
1091
1555
|
}
|
|
1092
1556
|
export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
1093
|
-
const t0 =
|
|
1557
|
+
const t0 = clock(), until = t0 + (opts.ms ?? 10_000), rand = seeded(29), run = interpret(m);
|
|
1094
1558
|
const names = [...Object.keys(m.state), ...m.params].sort(), helpful = livenessHelpful(l);
|
|
1095
1559
|
const node = { name: l.name, hyps: [], concl: yes, vars: names, level: 0, given: true };
|
|
1096
1560
|
const env = (ps, st) => ({ ...ps, ...st.scalars });
|
|
@@ -1103,7 +1567,7 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1103
1567
|
const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
|
|
1104
1568
|
const points = new Map(), strong = new Map(), weak = new Map();
|
|
1105
1569
|
for (const bound of [2, 4, 8, 16])
|
|
1106
|
-
for (let trial = 0; trial < 20 &&
|
|
1570
|
+
for (let trial = 0; trial < 20 && clock() < t0 + 1000; trial++) {
|
|
1107
1571
|
let ps;
|
|
1108
1572
|
try {
|
|
1109
1573
|
ps = sample.params(rand, bound);
|
|
@@ -1146,15 +1610,36 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1146
1610
|
st = next;
|
|
1147
1611
|
}
|
|
1148
1612
|
}
|
|
1613
|
+
// The trivial ranks first, where the runs allow them: the constant 0 (every helpful step in its region reaches `to` at
|
|
1614
|
+
// once: none sampled stays pending, which leaves the fit below nothing to fit), then each state variable alone (every
|
|
1615
|
+
// helpful step sampled that stays pending lowers it, and no other raises it), up to four of them. Rank 0 may take half
|
|
1616
|
+
// of what is left, each variable a quarter.
|
|
1617
|
+
const zero = { op: 'const', value: 0 }, tried = new Map();
|
|
1618
|
+
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]);
|
|
1619
|
+
const trivial = [...(strong.size ? [] : [[zero]]), ...Object.keys(m.state).filter(x => keeps(x) && lowers(x)).slice(0, 4).map(name => [{ op: 'var', name }])];
|
|
1620
|
+
const rankText = (rank) => `(${rank.map(showE).join(', ')})`;
|
|
1621
|
+
for (const [i, rank] of trivial.entries()) {
|
|
1622
|
+
const ms = until - performance.now();
|
|
1623
|
+
if (ms < 200)
|
|
1624
|
+
break;
|
|
1625
|
+
const v = withDeadline(performance.now() + ms * (i === 0 && !strong.size ? 0.5 : 0.25), () => proveLiveness(m, laws, { ...l, rank }));
|
|
1626
|
+
if (v.proven && v.checked)
|
|
1627
|
+
return { proven: true, checked: true, rank, laws: [], found: { rank: rankText(rank), laws: [] } };
|
|
1628
|
+
tried.set(id(rank), v);
|
|
1629
|
+
}
|
|
1149
1630
|
const samples = [[...points.values()].map(env => ({ env, calls: new Set() }))];
|
|
1150
1631
|
const { comps, left } = lexRanks([0], [node], samples, [...strong.values()], shared, until, false, [...weak.values()]);
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
const
|
|
1632
|
+
const noRank = `no linear rank, in order, that ${strong.size} helpful steps sampled lower and ${weak.size} others keep`;
|
|
1633
|
+
const fitted = comps.length && !left ? comps.map(c => compE(c, 0, node, shared)) : undefined;
|
|
1634
|
+
// Past the fit, the invariants a rank needs: the fitted one's, or else rank 0's where the runs allow it.
|
|
1635
|
+
const rank = fitted ?? (strong.size ? undefined : [zero]);
|
|
1636
|
+
if (!rank)
|
|
1637
|
+
return { proven: false, checked: false, why: noRank };
|
|
1638
|
+
const text = rankText(rank), lv = { ...l, rank };
|
|
1639
|
+
const first = tried.get(id(rank)) ?? withDeadline(until, () => proveLiveness(m, laws, lv));
|
|
1155
1640
|
if (first.proven && first.checked)
|
|
1156
1641
|
return { proven: true, checked: true, rank, laws: [], found: { rank: text, laws: [] } };
|
|
1157
|
-
const ms = until -
|
|
1642
|
+
const ms = until - clock();
|
|
1158
1643
|
if (ms > 300) {
|
|
1159
1644
|
const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(m, laws, [stay, cover, ...helps], { ms });
|
|
1160
1645
|
const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
|
|
@@ -1164,10 +1649,13 @@ export function findLeadsTo(m, laws, l, sample, opts = {}) {
|
|
|
1164
1649
|
return { proven: true, checked: true, rank, laws: more, found: { rank: text, laws: kept.map(f => f.text) } };
|
|
1165
1650
|
}
|
|
1166
1651
|
}
|
|
1167
|
-
|
|
1652
|
+
const failed = first.failed ? { goal: first.failed.goal, stuck: first.failed.stuck, ...(first.failed.witness ? { witness: first.failed.witness } : {}) } : {};
|
|
1653
|
+
if (!fitted)
|
|
1654
|
+
return { proven: false, checked: false, ...failed, why: `${noRank}; rank ${text}, which the runs allow, not proven, nor with the invariants found` };
|
|
1655
|
+
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` };
|
|
1168
1656
|
}
|
|
1169
1657
|
export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
|
|
1170
|
-
const until =
|
|
1658
|
+
const until = clock() + (opts.ms ?? 10_000);
|
|
1171
1659
|
const fns = Object.entries(m.fns ?? {}).filter(([, f]) => !f.recur && (f.arity ?? 1) === 1);
|
|
1172
1660
|
const fns2 = Object.entries(m.fns ?? {}).filter(([, f]) => !f.recur && f.arity === 2 && f.call);
|
|
1173
1661
|
if ((!fns.length && !fns2.length) || !m.facts?.length)
|
|
@@ -1260,16 +1748,16 @@ export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
|
|
|
1260
1748
|
const unique = [...new Map(claims.map(c => [c.name, c])).values()], two = (c) => m.fns?.[readsOf(c.concl)[0]?.map ?? '']?.arity === 2;
|
|
1261
1749
|
const proofs = new Map();
|
|
1262
1750
|
for (const c of unique.filter(two)) {
|
|
1263
|
-
if (
|
|
1751
|
+
if (clock() >= until)
|
|
1264
1752
|
break;
|
|
1265
|
-
const o = findCycles(facts, [c], { ms: Math.min(1000, (until -
|
|
1753
|
+
const o = findCycles(facts, [c], { ms: Math.min(1000, (until - clock()) * 0.1), values, houdini: true, generalize: false });
|
|
1266
1754
|
if (o.proven && o.checked && o.proof)
|
|
1267
1755
|
proofs.set(c.name, o.proof);
|
|
1268
1756
|
}
|
|
1269
1757
|
const ones = unique.filter(c => !two(c));
|
|
1270
1758
|
if (!ones.length && !proofs.size)
|
|
1271
1759
|
return { proven: false, checked: false, found: [], why: unique.length ? 'no lemma proven' : 'no lemma fits the values' };
|
|
1272
|
-
const out = ones.length ? findCycles(facts, ones, { ms: Math.max(0, until -
|
|
1760
|
+
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: [] };
|
|
1273
1761
|
if ((!out.proven || !out.checked || !out.kept?.length) && !proofs.size)
|
|
1274
1762
|
return { proven: false, checked: false, found: [], why: out.why ?? 'no lemma proven' };
|
|
1275
1763
|
const kept = [...(out.proven && out.checked ? out.kept ?? [] : []), ...proofs.keys()];
|
|
@@ -1294,7 +1782,7 @@ export function cycleLemmas(m, laws, stepLaws = [], opts = {}) {
|
|
|
1294
1782
|
if (!best.ok)
|
|
1295
1783
|
return { proven: false, checked: false, found: [], why: `lemmas proven (${found.map(f => f.text).join('; ')}), the laws not with them` };
|
|
1296
1784
|
for (const f of [...found]) {
|
|
1297
|
-
if (
|
|
1785
|
+
if (clock() >= until)
|
|
1298
1786
|
break;
|
|
1299
1787
|
const rest = found.filter(g => g !== f), again = proveWith(rest);
|
|
1300
1788
|
if (again.ok)
|