gdp-wired 0.22.0 → 0.23.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.
@@ -1,11 +1,16 @@
1
- // Linear arithmetic over the integers, inside the library. A conjunction of constraints `lin <= 0` is decided by
2
- // Fourier–Motzkin elimination with integer cuts, and every answer carries evidence that a small checker verifies:
1
+ // Linear arithmetic over the integers and over the rationals, inside the library. A conjunction of constraints
2
+ // `lin <= 0` (or `lin < 0`, strict) is decided by Fourier–Motzkin elimination with integer cuts, and every answer
3
+ // carries evidence that a small checker verifies:
3
4
  // refuted a derivation: input rows, positive combinations of two rows, and cuts (divide a row's variable
4
5
  // coefficients by their common divisor g and round the constant up), ending in `positive <= 0`
5
6
  // sat an integer witness, checked by evaluating every input constraint at it
6
7
  // unknown elimination was inexact for the integers and no witness was found (never a wrong answer)
7
8
  // Elimination of x is exact for the integers when every pair it combines has a coefficient ±1 on x (the Omega test's
8
9
  // exact shadow). Then a rational solution of the rest extends to an integer x, so back-substitution finds a witness.
10
+ // Over the rationals (`integral` false) the same elimination is exact with no cut at all (a combination of a strict
11
+ // row is strict), so the answer is refuted or sat, the witness exact (`rational`), the derivation one check.ts takes
12
+ // with no cut: the integers are this with the cut rule, and a strict row over them is lin + 1 <= 0.
13
+ import { Q0, Q1, q, qadd, qcmp, qdiv, qneg, qnum, qrow, qsub } from "./q.js";
9
14
  export const v = (name) => ({ [name]: 1 });
10
15
  export const k = (value) => (value === 0 ? {} : { 1: value });
11
16
  // (Plain loops, no intermediate arrays: these run millions of times in a proof. Each keeps the keys in the order they
@@ -58,13 +63,15 @@ const vars = (lin) => Object.keys(lin).filter(key => key !== '1');
58
63
  // five times as many before merging them, it gives up with `unknown`.
59
64
  // The rows the solver has read and made, which a counted search reads as its clock (kernel/prove.ts's `counted`).
60
65
  export const work = { n: 0 };
61
- export function solve(constraints, maxRows = 20_000) {
66
+ export function solve(constraints, maxRows = 20_000, integral = true) {
62
67
  work.n += constraints.length;
63
68
  const steps = [];
64
- const lins = [];
65
- const push = (step, lin) => (steps.push(step), lins.push(lin), lins.length - 1);
66
- // A row after its cut, if its variables share a divisor.
69
+ const lins = [], stricts = [];
70
+ const push = (step, lin, strict = false) => (steps.push(step), lins.push(lin), stricts.push(strict), lins.length - 1);
71
+ // A row after its cut, if its variables share a divisor (over the integers only).
67
72
  const tighten = (index) => {
73
+ if (!integral)
74
+ return index;
68
75
  const lin = lins[index];
69
76
  let g = 0;
70
77
  for (const key in lin)
@@ -82,10 +89,15 @@ export function solve(constraints, maxRows = 20_000) {
82
89
  const constant = Math.ceil((lin['1'] ?? 0) / g);
83
90
  return push({ kind: 'cut', of: index, g }, add(cut, k(constant)));
84
91
  };
85
- let rows = constraints.map((c, index) => tighten(push({ kind: 'input', index }, c.lin)));
86
- // A row with no variable and a positive constant (kept per row: a row never changes once pushed).
92
+ let rows = constraints.map((c, index) => tighten(push({ kind: 'input', index }, c.lin, !integral && c.strict === true)));
93
+ // A row with no variable and a positive constant, or a strict one with a constant >= 0 (kept per row: a row never
94
+ // changes once pushed).
87
95
  const contra = [];
88
- const isContra = (r) => (contra[r] ??= (lins[r]['1'] ?? 0) > 0 && Object.keys(lins[r]).every(key => key === '1'));
96
+ const isContra = (r) => (contra[r] ??= ((lins[r]['1'] ?? 0) > 0 || (stricts[r] && (lins[r]['1'] ?? 0) >= 0)) && Object.keys(lins[r]).every(key => key === '1'));
97
+ // Over the rationals every coefficient must stay a safe integer (none is rounded); past that, unknown.
98
+ let inexact = false;
99
+ const pushExact = (step, lin, strict) => { if (!integral && !Object.values(lin).every(c => Number.isSafeInteger(c)))
100
+ inexact = true; return push(step, lin, strict); };
89
101
  const contradiction = () => rows.find(isContra);
90
102
  const eliminated = [];
91
103
  let exact = true;
@@ -101,7 +113,7 @@ export function solve(constraints, maxRows = 20_000) {
101
113
  const byKey = new Map(rows.map(r => [key(r), r]));
102
114
  for (const r of rows) {
103
115
  const neg = byKey.get(negKey(r));
104
- if (neg === undefined || neg === r)
116
+ if (neg === undefined || neg === r || stricts[r] || stricts[neg])
105
117
  continue;
106
118
  let x;
107
119
  for (const name in lins[r])
@@ -121,7 +133,7 @@ export function solve(constraints, maxRows = 20_000) {
121
133
  if (c === 0)
122
134
  next.push(o);
123
135
  else
124
- next.push(tighten(push({ kind: 'combine', a: o, b: c > 0 ? down : up, ma: 1, mb: Math.abs(c) }, add(lins[o], scale(lins[c > 0 ? down : up], Math.abs(c))))));
136
+ next.push(tighten(pushExact({ kind: 'combine', a: o, b: c > 0 ? down : up, ma: 1, mb: Math.abs(c) }, add(lins[o], scale(lins[c > 0 ? down : up], Math.abs(c))), stricts[o])));
125
137
  }
126
138
  eliminated.push({ x, rows: [up, down] });
127
139
  rows = next;
@@ -183,27 +195,29 @@ export function solve(constraints, maxRows = 20_000) {
183
195
  for (const p of choice.pos)
184
196
  for (const n of choice.neg) {
185
197
  const a = lins[p][choice.x], b = -lins[n][choice.x];
186
- const combined = push({ kind: 'combine', a: p, b: n, ma: b / gcd(a, b), mb: a / gcd(a, b) }, add(scale(lins[p], b / gcd(a, b)), scale(lins[n], a / gcd(a, b))));
198
+ const combined = pushExact({ kind: 'combine', a: p, b: n, ma: b / gcd(a, b), mb: a / gcd(a, b) }, add(scale(lins[p], b / gcd(a, b)), scale(lins[n], a / gcd(a, b))), stricts[p] || stricts[n]);
187
199
  next.push(tighten(combined));
188
200
  }
189
- // Rows with the same variable part: only the tightest (largest constant) matters; rows with no variables that hold
190
- // say nothing.
201
+ // Rows with the same variable part: only the tightest (largest constant, strict before not at the same) matters;
202
+ // rows with no variables that hold say nothing.
191
203
  const best = new Map();
192
204
  for (const r of next) {
193
205
  const lin = lins[r], sig = sigOf(r);
194
- if (sig === '[]' && (lin['1'] ?? 0) <= 0)
206
+ if (sig === '[]' && !isContra(r))
195
207
  continue;
196
208
  const seen = best.get(sig);
197
- if (seen === undefined || (lins[seen]['1'] ?? 0) < (lin['1'] ?? 0))
209
+ if (seen === undefined || (lins[seen]['1'] ?? 0) < (lin['1'] ?? 0) || (stricts[r] && !stricts[seen] && (lins[seen]['1'] ?? 0) === (lin['1'] ?? 0)))
198
210
  best.set(sig, r);
199
211
  }
200
212
  rows = [...best.values()];
201
- if (rows.length > maxRows)
213
+ if (rows.length > maxRows || inexact)
202
214
  return { kind: 'unknown' };
203
215
  }
204
216
  const found = contradiction();
205
217
  if (found !== undefined)
206
- return { kind: 'refuted', steps: prune(steps, found) };
218
+ return inexact ? { kind: 'unknown' } : { kind: 'refuted', steps: prune(steps, found) };
219
+ if (!integral)
220
+ return inexact ? { kind: 'unknown' } : satOverQ(constraints, eliminated, lins, stricts);
207
221
  // A rational solution the same way (cuts only remove non-integer points, so bounds never cross): where to split.
208
222
  const rational = {};
209
223
  for (const { x, rows: bounds } of [...eliminated].reverse()) {
@@ -240,6 +254,35 @@ export function solve(constraints, maxRows = 20_000) {
240
254
  void exact;
241
255
  return holds ? { kind: 'sat', witness: point } : { kind: 'unknown', point: rational };
242
256
  }
257
+ // Over the rationals elimination is exact: back-substitution, last eliminated first, gives each variable an exact value
258
+ // within its bounds (strict ones kept strict): 0 where it may be, else the integer nearest its bounds that fits, else
259
+ // the midpoint. The witness is checked on every input exactly; a miss (none should happen) is unknown, never sat.
260
+ function satOverQ(constraints, eliminated, lins, stricts) {
261
+ const at = {};
262
+ for (const { x, rows: bounds } of [...eliminated].reverse()) {
263
+ let lo, hi;
264
+ for (const r of bounds) {
265
+ const lin = lins[r], a = lin[x];
266
+ // a·x + rest (<|<=) 0: x (<|<=) −rest/a when a > 0, x (>|>=) −rest/a when a < 0.
267
+ const rest = qrow(Object.fromEntries(Object.entries(lin).filter(([key]) => key !== x)), at), b = qdiv(qneg(rest), q(a)), strict = stricts[r];
268
+ if (a > 0) {
269
+ if (!hi || qcmp(b, hi.v) < 0 || (qcmp(b, hi.v) === 0 && strict))
270
+ hi = { v: b, strict };
271
+ }
272
+ else if (!lo || qcmp(b, lo.v) > 0 || (qcmp(b, lo.v) === 0 && strict))
273
+ lo = { v: b, strict };
274
+ }
275
+ const fits = (v) => (!lo || qcmp(v, lo.v) > 0 || (!lo.strict && qcmp(v, lo.v) === 0)) && (!hi || qcmp(v, hi.v) < 0 || (!hi.strict && qcmp(v, hi.v) === 0));
276
+ const floor = (v) => q(v.num >= 0n ? v.num / v.den : -((-v.num + v.den - 1n) / v.den));
277
+ const tries = [Q0, ...(lo ? [floor(lo.v), qadd(floor(lo.v), Q1)] : []), ...(hi ? [floor(hi.v), qsub(floor(hi.v), Q1)] : [])];
278
+ at[x] = tries.find(fits) ?? (lo && hi ? qdiv(qadd(lo.v, hi.v), q(2)) : lo ? qadd(lo.v, Q1) : qsub(hi.v, Q1));
279
+ }
280
+ for (const c of constraints)
281
+ for (const key of vars(c.lin))
282
+ at[key] ??= Q0;
283
+ const holds = constraints.every(c => { const s = qcmp(qrow(c.lin, at), Q0); return c.strict ? s < 0 : s <= 0; });
284
+ return holds ? { kind: 'sat', witness: Object.fromEntries(Object.entries(at).map(([key, v]) => [key, qnum(v)])), rational: at } : { kind: 'unknown' };
285
+ }
243
286
  // Only the steps the contradiction depends on, renumbered.
244
287
  function prune(steps, last) {
245
288
  const keep = new Set();
@@ -267,7 +310,9 @@ function prune(steps, last) {
267
310
  // derivation, renumbered to the whole system's rows. Floating point only picks the rows: the derivation is exact, and
268
311
  // the checker sees nothing else. Undefined when no λ turns up (a system with a rational solution, or one the floats
269
312
  // misjudge): the caller goes on as without it.
270
- export function refuteFast(constraints, maxRows = 2_000) {
313
+ // (Over the rationals, `integral` false, the elimination on the support has no cut; a refutation that needs a strict
314
+ // row's strictness, Σ λ·c = 0, isn't looked for here: the caller's own elimination finds it.)
315
+ export function refuteFast(constraints, maxRows = 2_000, integral = true) {
271
316
  const m = constraints.length;
272
317
  if (m === 0)
273
318
  return undefined;
@@ -348,7 +393,7 @@ export function refuteFast(constraints, maxRows = 2_000) {
348
393
  support.push(basis[r]);
349
394
  if (!support.length)
350
395
  return undefined;
351
- const sub = solve(support.sort((a, b) => a - b).map(i => constraints[i]));
396
+ const sub = solve(support.sort((a, b) => a - b).map(i => constraints[i]), 20_000, integral);
352
397
  if (sub.kind !== 'refuted')
353
398
  return undefined;
354
399
  return { kind: 'refuted', steps: sub.steps.map(st => (st.kind === 'input' ? { ...st, index: support[st.index] } : st)) };
@@ -1,10 +1,10 @@
1
1
  import { type DataLaw, type DataVerdict, type Options, type X } from './data.js';
2
2
  type Op = {
3
3
  name: string;
4
- args: 1 | 2;
4
+ args: number;
5
5
  ret: 'nat' | 'bool';
6
- x: (a: X, b: X) => X;
7
- at: (a: number, b: number) => number;
6
+ x: (as: X[]) => X;
7
+ at: (ns: number[]) => number;
8
8
  };
9
9
  export type Plan = {
10
10
  bridges: Map<string, Op>;
@@ -1,48 +1,72 @@
1
- import { Bool, Integer, Nat, Val, argsOf, bindName, define, encX, encY, evalX, factsOf, fnNamed, programOf, schemesOf, searchIn } from "./data.js";
1
+ import { Bool, Integer, Nat, Val, argsOf, bindName, define, encX, encY, evalX, factsOf, fnNamed, programOf, rankWidth, schemesOf, searchIn } from "./data.js";
2
2
  import { proveCyclic } from "./cyclic.js";
3
3
  import { clock, pairedKeys, withDeadline } from "../kernel/prove.js";
4
4
  import { substE } from "../kernel/kernel.js";
5
5
  const nat = (value) => ({ op: 'nat', value });
6
6
  const cond = (c) => ({ op: 'bool', c });
7
7
  const OPS = [
8
- { name: '+', args: 2, ret: 'nat', x: (a, b) => ({ op: 'add', a, b }), at: (a, b) => a + b },
9
- { name: '∸', args: 2, ret: 'nat', x: (a, b) => ({ op: 'sub', a, b }), at: (a, b) => Math.max(0, a - b) },
10
- { name: 'min', args: 2, ret: 'nat', x: (a, b) => ({ op: 'min', a, b }), at: Math.min },
11
- { name: 'max', args: 2, ret: 'nat', x: (a, b) => ({ op: 'max', a, b }), at: Math.max },
12
- { name: '≤', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<=', a, b }), at: (a, b) => +(a <= b) },
13
- { name: '<', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<', a, b }), at: (a, b) => +(a < b) },
14
- { name: '=', args: 2, ret: 'bool', x: (a, b) => cond({ op: '=', a, b }), at: (a, b) => +(a === b) },
15
- { name: '≥', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<=', a: b, b: a }), at: (a, b) => +(a >= b) },
16
- { name: '>', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<', a: b, b: a }), at: (a, b) => +(a > b) },
17
- { name: '≠', args: 2, ret: 'bool', x: (a, b) => cond({ op: 'not', x: { op: '=', a, b } }), at: (a, b) => +(a !== b) },
18
- { name: 'x + 1', args: 1, ret: 'nat', x: a => ({ op: 'add', a, b: nat(1) }), at: a => a + 1 },
19
- { name: 'x ∸ 1', args: 1, ret: 'nat', x: a => ({ op: 'sub', a, b: nat(1) }), at: a => Math.max(0, a - 1) },
20
- { name: '2·x', args: 1, ret: 'nat', x: a => ({ op: 'mul', k: 2, a }), at: a => 2 * a },
21
- { name: 'x = 0', args: 1, ret: 'bool', x: a => cond({ op: '=', a, b: nat(0) }), at: a => +(a === 0) },
8
+ { name: '+', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'add', a: a, b: b }), at: ([a, b]) => a + b },
9
+ { name: '∸', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'sub', a: a, b: b }), at: ([a, b]) => Math.max(0, a - b) },
10
+ { name: 'min', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'min', a: a, b: b }), at: ([a, b]) => Math.min(a, b) },
11
+ { name: 'max', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'max', a: a, b: b }), at: ([a, b]) => Math.max(a, b) },
12
+ { name: '≤', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<=', a: a, b: b }), at: ([a, b]) => +(a <= b) },
13
+ { name: '<', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<', a: a, b: b }), at: ([a, b]) => +(a < b) },
14
+ { name: '=', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '=', a: a, b: b }), at: ([a, b]) => +(a === b) },
15
+ { name: '≥', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<=', a: b, b: a }), at: ([a, b]) => +(a >= b) },
16
+ { name: '>', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<', a: b, b: a }), at: ([a, b]) => +(a > b) },
17
+ { name: '≠', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: 'not', x: { op: '=', a: a, b: b } }), at: ([a, b]) => +(a !== b) },
18
+ { name: 'x + 1', args: 1, ret: 'nat', x: ([a]) => ({ op: 'add', a: a, b: nat(1) }), at: ([a]) => a + 1 },
19
+ { name: 'x ∸ 1', args: 1, ret: 'nat', x: ([a]) => ({ op: 'sub', a: a, b: nat(1) }), at: ([a]) => Math.max(0, a - 1) },
20
+ { name: '2·x', args: 1, ret: 'nat', x: ([a]) => ({ op: 'mul', k: 2, a: a }), at: ([a]) => 2 * a },
21
+ { name: 'x = 0', args: 1, ret: 'bool', x: ([a]) => cond({ op: '=', a: a, b: nat(0) }), at: ([a]) => +(a === 0) },
22
22
  ];
23
+ // A sum Σ cᵢ·xᵢ + c₀ of naturals (cᵢ, c₀ ≥ 0): the built-in of a function of three or four naturals (add3, add3acc), or
24
+ // of one or two that none of OPS is.
25
+ const linear = (cs, c0) => {
26
+ const names = ['x', 'y', 'z', 'w'], name = [...cs.flatMap((c, i) => (c ? [`${c === 1 ? '' : `${c}·`}${names[i]}`] : [])), ...(c0 || cs.every(c => !c) ? [String(c0)] : [])].join(' + ');
27
+ const term = (a, c) => (c === 1 ? a : { op: 'mul', k: c, a });
28
+ return { name, args: cs.length, ret: 'nat', at: ns => cs.reduce((t, c, i) => t + c * ns[i], c0),
29
+ x: as => { const parts = [...cs.flatMap((c, i) => (c ? [term(as[i], c)] : [])), ...(c0 || cs.every(c => !c) ? [nat(c0)] : [])]; return parts.slice(1).reduce((t, x) => ({ op: 'add', a: t, b: x }), parts[0]); } };
30
+ };
23
31
  const fnOf = (name) => { const f = fnNamed(name); if (!f)
24
32
  throw new Error(`no function ${name}`); return f; };
25
33
  const recursive = (f) => f.decreases !== undefined;
26
- // The built-in a recursive function of naturals computes at every argument up to 6 (one argument: up to 12), if one.
34
+ // Recursive at all (structural, or well-founded): never unfolded at a call.
35
+ const taken = (f) => recursive(f) || f.measure !== undefined;
36
+ // The built-in a recursive function of naturals (structural, or well-founded: its termination proven) computes at every
37
+ // argument up to 6 (one argument: up to 12; three: up to 5; four: up to 3), if one.
27
38
  function builtinOf(f) {
28
- if (!recursive(f) || f.paramFns.length || !(f.ret === 'nat' || f.ret === 'bool') || !f.params.every(q => q.sort === 'nat'))
39
+ if (!taken(f) || f.paramFns.length || !(f.ret === 'nat' || f.ret === 'bool') || !f.params.every(q => q.sort === 'nat'))
29
40
  return undefined;
30
41
  const n = f.params.length;
31
- return OPS.find(op => {
32
- if (op.args !== n || op.ret !== f.ret)
33
- return false;
34
- try {
35
- for (let a = 0; a <= (n === 1 ? 12 : 6); a++)
36
- for (let b = 0; b <= (n === 1 ? 0 : 6); b++) {
37
- if (evalX({ op: 'call', fn: f.name, args: [nat(a), nat(b)].slice(0, n) }, new Map(), {}) !== op.at(a, b))
38
- return false;
39
- }
40
- }
41
- catch {
42
- return false;
42
+ if (n < 1 || n > 4)
43
+ return undefined;
44
+ const top = [12, 6, 5, 3][n - 1], points = [[]];
45
+ for (let i = 0; i < n; i++)
46
+ points.splice(0, points.length, ...points.flatMap(p => Array.from({ length: top + 1 }, (_, a) => [...p, a])));
47
+ const values = new Map();
48
+ const at = (ns) => {
49
+ const key = ns.join(',');
50
+ if (!values.has(key)) {
51
+ try {
52
+ values.set(key, evalX({ op: 'call', fn: f.name, args: ns.map(nat) }, new Map(), {}));
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
43
57
  }
44
- return true;
45
- });
58
+ return values.get(key);
59
+ };
60
+ const agrees = (op) => points.every(ns => at(ns) === op.at(ns));
61
+ const named = OPS.find(op => op.args === n && op.ret === f.ret && agrees(op));
62
+ if (named || f.ret !== 'nat')
63
+ return named;
64
+ // (its value at zero and at each unit point, then checked at every point)
65
+ const c0 = at(Array(n).fill(0)), cs = Array.from({ length: n }, (_, i) => { const e = Array(n).fill(0); e[i] = 1; const v = at(e); return v === undefined || c0 === undefined ? -1 : v - c0; });
66
+ if (c0 === undefined || cs.some(c => c < 0))
67
+ return undefined;
68
+ const op = linear(cs, c0);
69
+ return agrees(op) ? op : undefined;
46
70
  }
47
71
  // Whether `y` is f's bridge law: f at distinct variables equal (either side) to the built-in at them.
48
72
  function isBridge(y, f, op) {
@@ -50,7 +74,7 @@ function isBridge(y, f, op) {
50
74
  return false;
51
75
  const sides = [[y.a, y.b], [y.b, y.a]];
52
76
  return sides.some(([c, x]) => c.op === 'call' && c.fn === f.name && c.args.every(a => a.op === 'var') && new Set(c.args.map(a => JSON.stringify(a))).size === c.args.length
53
- && JSON.stringify(x) === JSON.stringify(op.x(c.args[0], c.args[1] ?? nat(0))));
77
+ && JSON.stringify(x) === JSON.stringify(op.x(c.args)));
54
78
  }
55
79
  const callsOf = (t) => { const out = []; walkO(t, o => { if (o.op === 'call')
56
80
  out.push(o.fn); }); return out; };
@@ -72,7 +96,7 @@ export function transferPlan(l) {
72
96
  if (op && !isBridge(l.holds, f, op))
73
97
  bridges.set(f.name, op);
74
98
  }
75
- const unfolds = p.fns.some(f => !recursive(f));
99
+ const unfolds = p.fns.some(f => !taken(f));
76
100
  return bridges.size || unfolds ? { bridges, unfolds } : undefined;
77
101
  }
78
102
  // --- the law said another way ------------------------------------------------------------------------------------------
@@ -136,8 +160,8 @@ function rewriter(bridges, copies, unfold, ren = new Map()) {
136
160
  case 'call': {
137
161
  const op = bridges.get(x.fn);
138
162
  if (op)
139
- return op.x(rx(x.args[0]), x.args[1] ? rx(x.args[1]) : nat(0));
140
- if (unfold && !recursive(fnOf(x.fn))) {
163
+ return op.x(x.args.map(rx));
164
+ if (unfold && !taken(fnOf(x.fn))) {
141
165
  if (++unfolded > 400)
142
166
  throw new RangeError('unfolded past 400 calls');
143
167
  return rx(instantiate(fnOf(x.fn), x.args));
@@ -175,7 +199,7 @@ const freshName = (base) => { let n = base; for (let i = 2; fnNamed(n); i++)
175
199
  function build(l, bridged, unfold) {
176
200
  // Copied: a function that calls a bridged one, or (unfolding) one that isn't recursive, or a copied one; a function
177
201
  // that isn't recursive is unfolded where it is called instead.
178
- const p0 = programOf([l]), reach = new Set(), unfolded = (n) => unfold && !recursive(fnOf(n));
202
+ const p0 = programOf([l]), reach = new Set(), unfolded = (n) => unfold && !taken(fnOf(n));
179
203
  for (let changed = true; changed;) {
180
204
  changed = false;
181
205
  for (const f of p0.fns)
@@ -236,7 +260,7 @@ function build(l, bridged, unfold) {
236
260
  const p1 = programOf([lstar]), back = new Map([...copies].map(([a, b]) => [b, a]));
237
261
  const bridges = [...bridged].map(([f, op]) => {
238
262
  const fn = fnOf(f), vs = fn.params.map(q => q.name);
239
- return { fn, op, law: { name: `${f} is ${op.name}`, vars: fn.params.map(q => ({ name: q.name, sort: q.sort })), holds: { op: '=', a: { op: 'call', fn: f, args: vs.map(v) }, b: op.x(v(vs[0]), vs[1] ? v(vs[1]) : nat(0)) }, params: [] } };
263
+ return { fn, op, law: { name: `${f} is ${op.name}`, vars: fn.params.map(q => ({ name: q.name, sort: q.sort })), holds: { op: '=', a: { op: 'call', fn: f, args: vs.map(v) }, b: op.x(vs.map(v)) }, params: [] } };
240
264
  });
241
265
  const equivs = p1.fns.filter(f => back.has(f.name)).map(c => {
242
266
  const fn = fnOf(back.get(c.name)), vs = fn.params.map(q => q.name), params = [...new Set(fn.paramFns)];
@@ -332,7 +356,7 @@ export function proveThrough(l, plan, opts, until) {
332
356
  const v = verify(fs, specs, Math.max(until, clock() + 3000));
333
357
  if (!v.proven || !v.checked)
334
358
  return undefined;
335
- const through = [...b.bridges.map(x => `${x.fn.name} is ${x.op.name}`), ...b.equivs.map(x => x.law.name), ...(b.unfolded ? [`unfolded: ${programOf([l]).fns.filter(f => !recursive(f)).map(f => f.name).join(', ')}`] : [])];
359
+ const through = [...b.bridges.map(x => `${x.fn.name} is ${x.op.name}`), ...b.equivs.map(x => x.law.name), ...(b.unfolded ? [`unfolded: ${programOf([l]).fns.filter(f => !taken(f)).map(f => f.name).join(', ')}`] : [])];
336
360
  return { law: l.name, proven: true, checked: true, proof: v, lemmas: [...b.bridges.map(x => x.law.name), ...b.equivs.map(x => x.law.name), ...r.verdict.lemmas], scheme: `${r.verdict.scheme ?? 'no induction'}, through the law ${b.lstar.name}`, tried, program: b.p, node: specs.length - 1, ms: Math.round(performance.now() - t0), through };
337
361
  }
338
362
  }
@@ -367,9 +391,9 @@ function walker(b, fs, nodeOf, own) {
367
391
  if (br) {
368
392
  if (!use(br.law.name, Object.fromEntries(f.params.map((q, i) => [q.name, as[i]]))))
369
393
  return undefined;
370
- return substE(encX(p, br.op.x({ op: 'var', name: 'a$' }, { op: 'var', name: 'b$' }), new Map()), { vars: { 'a$': as[0], 'b$': as[1] ?? k(0) }, maps: {}, flags: {} });
394
+ return substE(encX(p, br.op.x(as.map((_, i) => ({ op: 'var', name: `a$${i}` }))), new Map()), { vars: Object.fromEntries(as.map((a, i) => [`a$${i}`, a])), maps: {}, flags: {} });
371
395
  }
372
- if (!recursive(f) && b.unfolded)
396
+ if (!taken(f) && b.unfolded)
373
397
  return inst(`fn ${f.name}`, as) ? factBody(f, as) : undefined;
374
398
  const copy = b.copies.get(f.name);
375
399
  if (!copy)
@@ -447,12 +471,15 @@ function walker(b, fs, nodeOf, own) {
447
471
  };
448
472
  return { walkC, walkE, insts, uses, inst };
449
473
  }
474
+ // A node's rank is (level, the measure's place, 0 or 1), the measure's place as wide as the program's widest measure
475
+ // (core/data.ts's attempt): the zeros after the `n` components given, so every node's rank has one length.
476
+ const pad = (p, n) => Array.from({ length: rankWidth(p) - n }, () => k(0));
450
477
  // The law's node: its conclusion, using the law said through the bridges (at its own variables) and the walk's reasons.
451
478
  function lawNode(l, b, fs, nodeOf, lnode, level) {
452
479
  const w = walker(b, fs, nodeOf), concl = encY(b.p, l.holds, new Map());
453
480
  if (!w.walkC(concl, encY(b.p, b.lstar.holds, new Map())))
454
481
  return undefined;
455
- return { name: `${l.name} (through ${b.lstar.name})`, hyps: [], concl, rank: [k(level), k(0), k(0)], insts: w.insts, uses: [{ node: lnode, subst: {}, guard: yes }, ...w.uses] };
482
+ return { name: `${l.name} (through ${b.lstar.name})`, hyps: [], concl, rank: [k(level), ...pad(b.p, 0), k(0)], insts: w.insts, uses: [{ node: lnode, subst: {}, guard: yes }, ...w.uses] };
456
483
  }
457
484
  // A copy's law, f(xs) = f'(xs), as one node at index `self`: both definitions' facts at xs, their bodies walked together
458
485
  // (f's own recursive calls its copy's by the node itself, at the uses of f's recursion scheme), the shape of the argument
@@ -471,6 +498,6 @@ function copyNode(x, b, fs, nodeOf, self, level) {
471
498
  const on = scheme?.on, size = !on ? k(0) : on.d === 'nat' ? { op: 'var', name: on.v } : { op: 'get', map: `${on.d.name}.size`, key: { op: 'var', name: on.v } };
472
499
  if (on && on.d !== 'nat')
473
500
  w.inst(`shape ${on.d.name}`, [{ op: 'var', name: on.v }]);
474
- return { name: `${x.law.name} (its copy, made)`, hyps: [], concl: encY(b.p, x.law.holds, new Map()), rank: [k(level), size, k(0)], insts: w.insts,
501
+ return { name: `${x.law.name} (its copy, made)`, hyps: [], concl: encY(b.p, x.law.holds, new Map()), rank: [k(level), size, ...pad(b.p, 1), k(0)], insts: w.insts,
475
502
  uses: [...(scheme?.uses ?? []).map(u => ({ node: self, subst: u.subst, guard: u.guard })), ...w.uses] };
476
503
  }
@@ -32,9 +32,12 @@ export declare const cdclStats: {
32
32
  nodes: number;
33
33
  boundRounds: number;
34
34
  };
35
+ export declare const REFUTED = "refuted, not unfolded";
35
36
  export declare function growCdcl(goal: Goal, root: Path, budget: {
36
37
  nodes: number;
37
38
  until?: number;
38
39
  }, opts?: {
39
40
  maxLeaves?: number;
41
+ model?: boolean;
42
+ wall?: number;
40
43
  }): Outcome;
@@ -45,6 +45,9 @@ const env = globalThis.process?.env ?? {};
45
45
  const lpFill = Number(env.GDP_CDCL_FILL ?? 8), useLp = env.GDP_CDCL_LP !== '0', verify = env.GDP_CDCL_VERIFY === '1';
46
46
  // Counters research/step reads (times only while `on`).
47
47
  export const cdclStats = { on: false, runs: 0, proven: 0, conflicts: 0, decisions: 0, solveMs: 0, rowsMs: 0, coreMs: 0, unfoldMs: 0, leaves: 0, resolved: 0, coreSize: 0, pathSize: 0, lpMisses: 0, resolved2: 0, unfoldWhy: '', orderMs: 0, boundMs: 0, openMisses: 0, lpMs: 0, lpUnknown: 0, fmCalls: 0, pivots: 0, lpRebuilds: 0, lpRows: 0, lpNnz: 0, lpVars: 0, lpLoad: 0, nodes: 0, boundRounds: 0 };
48
+ // `opts.model`: only whether the goal has a model is wanted (core/bmc.ts): a refutation isn't unfolded into a tree, its
49
+ // outcome `unknown` with `why` REFUTED; each decision's phase is the simplex's point's (phaseAtPoint); past `opts.wall` (wall time) the search stops as past its budget.
50
+ export const REFUTED = 'refuted, not unfolded';
48
51
  export function growCdcl(goal, root, budget, opts = {}) {
49
52
  const until = budget.until ?? Infinity, st = cdclStats, timing = st.on;
50
53
  const t = (f, add) => { if (!timing)
@@ -220,10 +223,23 @@ export function growCdcl(goal, root, budget, opts = {}) {
220
223
  }, ms => { st.coreMs += ms; });
221
224
  const luby = (i) => { let n = 1; while ((1 << n) - 1 < i + 1)
222
225
  n++; return (1 << n) - 1 === i + 1 ? 1 << (n - 1) : luby(i + 1 - (1 << (n - 1))); };
226
+ // With a model wanted: each open atom's phase (no term column's) set to its value at the simplex's point, which meets
227
+ // every row read (over the rationals), so a decision tends to stay feasible (runs/unsat/bmc-only-phase: 320 of
228
+ // CHC-COMP's 475 unsat tasks, 280 without; each atom decided at once at the point instead, 271).
229
+ const phaseAtPoint = (cands, lp) => {
230
+ for (const lin of cands) {
231
+ const x = vars.get(ensure(lin));
232
+ if (x.val !== undefined || x.terms.some(([key]) => key.startsWith('⟦')))
233
+ continue;
234
+ const at = lp.holds(x.lin);
235
+ if (at !== undefined)
236
+ x.phase = at;
237
+ }
238
+ };
223
239
  let restartAt = 32, nRestart = 0, sinceRestart = 0;
224
240
  const stuck = (kind, why, extra = {}) => ({ stuck: kind, path: pathOf(), why, ...extra });
225
241
  for (;;) {
226
- if (++budget.nodes > 200_000 || clock() > until)
242
+ if (++budget.nodes > 200_000 || clock() > until || (opts.wall !== undefined && performance.now() > opts.wall))
227
243
  return stuck('unknown', budget.nodes > 200_000 ? 'nodes' : 'time');
228
244
  let conflict;
229
245
  const ci = propagate();
@@ -328,7 +344,7 @@ export function growCdcl(goal, root, budget, opts = {}) {
328
344
  continue;
329
345
  }
330
346
  }
331
- let steps;
347
+ let steps, lpSat = false;
332
348
  let verdict;
333
349
  t(() => {
334
350
  // The simplex first (warm from the node before): a conflict's rows, refuted exactly, are the leaf. With a case
@@ -361,6 +377,7 @@ export function growCdcl(goal, root, budget, opts = {}) {
361
377
  else
362
378
  st.lpMisses++;
363
379
  }
380
+ lpSat = lp.kind === 'sat';
364
381
  if (steps || (open && lp.kind === 'sat'))
365
382
  return;
366
383
  }
@@ -384,6 +401,8 @@ export function growCdcl(goal, root, budget, opts = {}) {
384
401
  if (steps)
385
402
  conflict = leafAt(rowsR, steps);
386
403
  else {
404
+ if (opts.model && lpSat && sx && open)
405
+ phaseAtPoint(cands, sx);
387
406
  // A decision: the open atom of highest activity (the first candidate among equals).
388
407
  let pick, best = -1;
389
408
  for (const lin of cands) {
@@ -426,6 +445,8 @@ export function growCdcl(goal, root, budget, opts = {}) {
426
445
  let c = conflict;
427
446
  for (;;) {
428
447
  if (!c.lits.size) {
448
+ if (opts.model)
449
+ return { stuck: 'unknown', path: new Map(), why: REFUTED };
429
450
  const tree = t(() => unfold(goal, nodes, c.node, root, opts.maxLeaves ?? 20_000, until), ms => { st.unfoldMs += ms; });
430
451
  if (!tree)
431
452
  return stuck('unknown', 'unfold');
@@ -91,6 +91,15 @@ export type Loop = {
91
91
  export declare const loopMachine: (l: Loop) => Machine;
92
92
  export declare const loopLiveness: (l: Loop, rank: E | E[]) => Liveness;
93
93
  export declare function loopObligations(l: Loop, laws: Law[], rank: E | E[]): Goal[];
94
+ export type Recur = {
95
+ start: Record<string, number>;
96
+ stem: Record<string, number>[];
97
+ set: C;
98
+ wit: Record<string, E>;
99
+ tree: Tree;
100
+ };
101
+ export declare function recurGoal(l: Loop, r: Pick<Recur, 'set' | 'wit'>): Goal;
102
+ export declare function checkRecur(l: Loop, r: Recur): boolean;
94
103
  export declare function progressObligations(m: Machine, laws: Law[], instances: Instances, p: {
95
104
  name: string;
96
105
  when: C;
@@ -149,4 +158,86 @@ export type Fold = {
149
158
  assume?: C;
150
159
  };
151
160
  export declare function foldObligations(f: Fold, laws: Law[]): Goal[];
161
+ export type Rat = {
162
+ num: bigint;
163
+ den: bigint;
164
+ };
165
+ export type QE = {
166
+ op: 'var';
167
+ name: string;
168
+ } | {
169
+ op: 'const';
170
+ q: Rat;
171
+ } | {
172
+ op: 'add' | 'sub' | 'min' | 'max';
173
+ a: QE;
174
+ b: QE;
175
+ } | {
176
+ op: 'mul';
177
+ k: Rat;
178
+ a: QE;
179
+ } | {
180
+ op: 'if';
181
+ c: QC;
182
+ then: QE;
183
+ else: QE;
184
+ };
185
+ export type QC = {
186
+ op: '<=' | '<' | '=';
187
+ a: QE;
188
+ b: QE;
189
+ } | {
190
+ op: 'and' | 'or';
191
+ a: QC;
192
+ b: QC;
193
+ } | {
194
+ op: 'not';
195
+ x: QC;
196
+ };
197
+ export type QGoal = {
198
+ name: string;
199
+ hyps: QC[];
200
+ };
201
+ export type QRow = {
202
+ cs: Map<string, bigint>;
203
+ c: bigint;
204
+ };
205
+ export type LF = {
206
+ row: QRow;
207
+ den: bigint;
208
+ };
209
+ export declare const ratNorm: (q: Rat) => Rat;
210
+ export declare const qdif: (a: LF, b: LF) => QRow;
211
+ export declare const qLin: (r: QRow) => Lin | undefined;
212
+ export declare function qdec(path: Path, r: QRow): boolean | undefined;
213
+ export declare function qlinear(e: QE, path: Path): LF | undefined;
214
+ export declare function qtruth(c: QC, path: Path): boolean | undefined;
215
+ export declare function qfacts(c: QC, path: Path, pos?: boolean): [QRow, boolean][];
216
+ export declare function qLeafRows(goal: QGoal, path: Path): Constraint[];
217
+ export declare function checkQTree(goal: QGoal, tree: Tree, path?: Path): boolean;
218
+ export type QMachine = {
219
+ name: string;
220
+ params: string[];
221
+ inputs: string[];
222
+ state: Record<string, QE>;
223
+ step: Record<string, QE>;
224
+ pre?: QC;
225
+ assume?: QC;
226
+ };
227
+ export type QLaw = {
228
+ name: string;
229
+ holds: QC;
230
+ };
231
+ export declare const qTrue: QC;
232
+ export declare function qSubstE(e: QE, s: Record<string, QE>): QE;
233
+ export declare function qSubstC(c: QC, s: Record<string, QE>): QC;
234
+ export declare function qOccurs(t: QE | QC, names: string[]): boolean;
235
+ export declare function qObligations(m: QMachine, laws: QLaw[], law: QLaw): {
236
+ start: QGoal;
237
+ step: QGoal;
238
+ };
239
+ export declare function checkQMachine(m: QMachine, laws: QLaw[], trees: Record<string, {
240
+ start: Tree;
241
+ step: Tree;
242
+ }>): boolean;
152
243
  export {};