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.
Files changed (60) hide show
  1. package/README.md +27 -2
  2. package/dist/core/bmc.d.ts +49 -0
  3. package/dist/core/bmc.js +509 -0
  4. package/dist/core/check.d.ts +1 -1
  5. package/dist/core/check.js +19 -6
  6. package/dist/core/cycles.d.ts +38 -0
  7. package/dist/core/cycles.js +531 -43
  8. package/dist/core/data.d.ts +25 -1
  9. package/dist/core/data.js +984 -215
  10. package/dist/core/discover.js +8 -3
  11. package/dist/core/dsl.d.ts +17 -3
  12. package/dist/core/dsl.js +81 -15
  13. package/dist/core/extract-check.d.ts +77 -0
  14. package/dist/core/extract-check.js +785 -0
  15. package/dist/core/extract-ir.d.ts +139 -0
  16. package/dist/core/extract-ir.js +198 -0
  17. package/dist/core/extract-print.d.ts +30 -0
  18. package/dist/core/extract-print.js +426 -0
  19. package/dist/core/extract-read.d.ts +298 -0
  20. package/dist/core/extract-read.js +1298 -0
  21. package/dist/core/extract-shapes.d.ts +13 -0
  22. package/dist/core/extract-shapes.js +993 -0
  23. package/dist/core/extract-xstate.d.ts +34 -0
  24. package/dist/core/extract-xstate.js +320 -0
  25. package/dist/core/extract.d.ts +31 -0
  26. package/dist/core/extract.js +249 -0
  27. package/dist/core/infer.js +518 -5
  28. package/dist/core/kind.d.ts +30 -0
  29. package/dist/core/kind.js +81 -0
  30. package/dist/core/nonterm.d.ts +34 -0
  31. package/dist/core/nonterm.js +610 -0
  32. package/dist/core/q.d.ts +17 -0
  33. package/dist/core/q.js +52 -0
  34. package/dist/core/rationals.d.ts +112 -0
  35. package/dist/core/rationals.js +281 -0
  36. package/dist/core/relation.d.ts +28 -0
  37. package/dist/core/relation.js +483 -0
  38. package/dist/core/solver.d.ts +5 -2
  39. package/dist/core/solver.js +65 -20
  40. package/dist/core/transfer.d.ts +3 -3
  41. package/dist/core/transfer.js +69 -42
  42. package/dist/core/xstate.d.ts +6 -0
  43. package/dist/core/xstate.js +70 -12
  44. package/dist/kernel/cdcl.d.ts +13 -0
  45. package/dist/kernel/cdcl.js +307 -236
  46. package/dist/kernel/kernel.d.ts +106 -0
  47. package/dist/kernel/kernel.js +342 -0
  48. package/dist/kernel/prove.js +14 -3
  49. package/dist/kernel/qprove.d.ts +18 -0
  50. package/dist/kernel/qprove.js +157 -0
  51. package/dist/kernel/reader.d.ts +14 -0
  52. package/dist/kernel/reader.js +102 -14
  53. package/dist/kernel/simplex.d.ts +4 -0
  54. package/dist/kernel/simplex.js +38 -11
  55. package/dist/lean-kernel/emit.d.ts +46 -1
  56. package/dist/lean-kernel/emit.js +125 -16
  57. package/dist/lean-kernel/library.js +4 -1
  58. package/dist/lean-kernel/qlean.d.ts +26 -0
  59. package/dist/lean-kernel/qlean.js +105 -0
  60. package/package.json +16 -3
@@ -0,0 +1,610 @@
1
+ import { checkRecur, recurGoal, substC, trueC } from "../kernel/kernel.js";
2
+ import { clock, counted, grow } from "../kernel/prove.js";
3
+ import { work } from "./solver.js";
4
+ const K = (value) => ({ op: 'const', value }), V = (name) => ({ op: 'var', name });
5
+ const T = trueC, F = { op: '<', a: K(0), b: K(0) };
6
+ const isT = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
7
+ const isF = (c) => (c.op === '<' && c.a.op === 'const' && c.b.op === 'const' && c.a.value >= c.b.value) || (c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value > c.b.value);
8
+ const and = (xs) => { const ys = xs.flatMap(x => (x.op === 'and' ? x.xs : [x])).filter(x => !isT(x)); return ys.some(isF) ? F : ys.length === 0 ? T : ys.length === 1 ? ys[0] : { op: 'and', xs: ys }; };
9
+ const or = (xs) => { const ys = xs.flatMap(x => (x.op === 'or' ? x.xs : [x])).filter(x => !isF(x)); return ys.some(isT) ? T : ys.length === 0 ? F : ys.length === 1 ? ys[0] : { op: 'or', xs: ys }; };
10
+ const eq = (a, b) => ({ op: '=', a, b });
11
+ const plus = (a, b) => (a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? K(a.value + b.value) : { op: 'add', a, b });
12
+ const minus = (a, b) => (b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? K(Math.max(0, a.value - b.value)) : { op: 'sub', a, b });
13
+ const times = (k, a) => (k === 0 ? K(0) : k === 1 ? a : a.op === 'const' ? K(k * a.value) : { op: 'mul', k, a });
14
+ const ite = (c, a, b) => (isT(c) ? a : isF(c) ? b : a === b || JSON.stringify(a) === JSON.stringify(b) ? a : { op: 'if', c, then: a, else: b });
15
+ // Constants folded: a term or condition with the same value everywhere, smaller (a policy's conditions read the mode as
16
+ // its constants, which decides most of a translated loop's cases; core/bmc.ts, a run's start and its fixed requests).
17
+ // Each shared part is folded once.
18
+ const simpMemo = new WeakMap();
19
+ const memo = (x, f) => { const hit = simpMemo.get(x); if (hit)
20
+ return hit; const out = f(x); simpMemo.set(x, out); return out; };
21
+ export const simpE = (e) => memo(e, simpE0);
22
+ export const simpC = (c) => memo(c, simpC0);
23
+ function simpE0(e) {
24
+ switch (e.op) {
25
+ case 'var':
26
+ case 'const': return e;
27
+ case 'add': return plus(simpE(e.a), simpE(e.b));
28
+ case 'sub': return minus(simpE(e.a), simpE(e.b));
29
+ case 'mul': return times(e.k, simpE(e.a));
30
+ case 'prod': {
31
+ const a = simpE(e.a), b = simpE(e.b);
32
+ return a.op === 'const' ? times(a.value, b) : b.op === 'const' ? times(b.value, a) : { op: 'prod', a, b };
33
+ }
34
+ case 'min':
35
+ case 'max': {
36
+ const a = simpE(e.a), b = simpE(e.b);
37
+ return a.op === 'const' && b.op === 'const' ? K(Math[e.op](a.value, b.value)) : { op: e.op, a, b };
38
+ }
39
+ case 'if': return ite(simpC(e.c), simpE(e.then), simpE(e.else));
40
+ case 'get': return { op: 'get', map: e.map, key: simpE(e.key) };
41
+ }
42
+ }
43
+ function simpC0(c) {
44
+ switch (c.op) {
45
+ case '<=':
46
+ case '<':
47
+ case '=': {
48
+ const a = simpE(c.a), b = simpE(c.b);
49
+ if (a.op === 'const' && b.op === 'const')
50
+ return (c.op === '<=' ? a.value <= b.value : c.op === '<' ? a.value < b.value : a.value === b.value) ? T : F;
51
+ return { op: c.op, a, b };
52
+ }
53
+ case 'and': return and(c.xs.map(simpC));
54
+ case 'or': return or(c.xs.map(simpC));
55
+ case 'not': {
56
+ const x = simpC(c.x);
57
+ return isT(x) ? F : isF(x) ? T : { op: 'not', x };
58
+ }
59
+ case 'flag':
60
+ case 'all': return c;
61
+ }
62
+ }
63
+ // A goal's size as the kernel reads it: its terms written out (shared parts counted at each use). A closure goal past
64
+ // GOAL_MAX is not tried: the witness's ifs read inside the body's multiply, and the kernel would not finish within the
65
+ // budget (one task's goal was 163 million nodes).
66
+ const sizeMemo = new WeakMap();
67
+ export function goalSize(x) {
68
+ if (typeof x !== 'object' || x === null)
69
+ return 1;
70
+ const m = sizeMemo.get(x);
71
+ if (m !== undefined)
72
+ return m;
73
+ let n = 1;
74
+ for (const v of Object.values(x))
75
+ n += goalSize(v);
76
+ sizeMemo.set(x, n);
77
+ return n;
78
+ }
79
+ const GOAL_MAX = 300_000;
80
+ // --- running the loop ---------------------------------------------------------------------------------------------------
81
+ class Overflow extends Error {
82
+ }
83
+ const BIG = 2 ** 48;
84
+ const big = (x) => { if (x > BIG)
85
+ throw new Overflow(); return x; };
86
+ function cE(e) {
87
+ switch (e.op) {
88
+ case 'var': {
89
+ const n = e.name;
90
+ return env => env[n] ?? 0;
91
+ }
92
+ case 'const': {
93
+ const v = e.value;
94
+ return () => v;
95
+ }
96
+ case 'add': {
97
+ const a = cE(e.a), b = cE(e.b);
98
+ return env => big(a(env) + b(env));
99
+ }
100
+ case 'sub': {
101
+ const a = cE(e.a), b = cE(e.b);
102
+ return env => Math.max(0, a(env) - b(env));
103
+ }
104
+ case 'mul': {
105
+ const a = cE(e.a), k = e.k;
106
+ return env => big(k * a(env));
107
+ }
108
+ case 'prod': {
109
+ const a = cE(e.a), b = cE(e.b);
110
+ return env => big(a(env) * b(env));
111
+ }
112
+ case 'min': {
113
+ const a = cE(e.a), b = cE(e.b);
114
+ return env => Math.min(a(env), b(env));
115
+ }
116
+ case 'max': {
117
+ const a = cE(e.a), b = cE(e.b);
118
+ return env => Math.max(a(env), b(env));
119
+ }
120
+ case 'if': {
121
+ const c = cC(e.c), a = cE(e.then), b = cE(e.else);
122
+ return env => (c(env) ? a(env) : b(env));
123
+ }
124
+ case 'get': return () => 0;
125
+ }
126
+ }
127
+ function cC(c) {
128
+ switch (c.op) {
129
+ case '<=': {
130
+ const a = cE(c.a), b = cE(c.b);
131
+ return env => a(env) <= b(env);
132
+ }
133
+ case '<': {
134
+ const a = cE(c.a), b = cE(c.b);
135
+ return env => a(env) < b(env);
136
+ }
137
+ case '=': {
138
+ const a = cE(c.a), b = cE(c.b);
139
+ return env => a(env) === b(env);
140
+ }
141
+ case 'and': {
142
+ const xs = c.xs.map(cC);
143
+ return env => xs.every(x => x(env));
144
+ }
145
+ case 'or': {
146
+ const xs = c.xs.map(cC);
147
+ return env => xs.some(x => x(env));
148
+ }
149
+ case 'not': {
150
+ const x = cC(c.x);
151
+ return env => !x(env);
152
+ }
153
+ case 'flag':
154
+ case 'all': throw new Error('a loop reads no flag');
155
+ }
156
+ }
157
+ function observables(names) {
158
+ const out = [], twin = new Set();
159
+ for (const x of names)
160
+ for (const s of ['$n', '$neg'])
161
+ if (names.includes(x + s))
162
+ twin.add(x + s);
163
+ for (const x of names)
164
+ if (!twin.has(x)) {
165
+ const n = names.includes(`${x}$n`) ? `${x}$n` : names.includes(`${x}$neg`) ? `${x}$neg` : undefined;
166
+ out.push({ name: x, p: x, ...(n ? { n } : {}) });
167
+ }
168
+ return out;
169
+ }
170
+ const valueOf = (o, env) => (env[o.p] ?? 0) - (o.n ? env[o.n] ?? 0 : 0);
171
+ const iObs = (o) => ({ p: V(o.p), n: o.n ? V(o.n) : K(0) });
172
+ const iConst = (c) => (c >= 0 ? { p: K(c), n: K(0) } : { p: K(0), n: K(-c) });
173
+ const iAdd = (x, c) => (c >= 0 ? { p: plus(x.p, K(c)), n: x.n } : { p: x.p, n: plus(x.n, K(-c)) });
174
+ // The value written into a pair (normal: at most one part nonzero) or a natural (its value, 0 below).
175
+ const iInto = (x, o) => (o.n ? { [o.p]: minus(x.p, x.n), [o.n]: minus(x.n, x.p) } : { [o.p]: minus(x.p, x.n) });
176
+ // The constants a condition compares a name with (`t = 2`, `x + 1 <= 100`): where the loop's cases are.
177
+ function constantsOf(c, out = new Set()) {
178
+ JSON.stringify(c, (k, v) => { if (k === 'value' && typeof v === 'number')
179
+ out.add(v); return v; });
180
+ return out;
181
+ }
182
+ function atomC(a, obs) {
183
+ let pos = K(0), neg = K(0);
184
+ for (const [i, c] of a.coefs) {
185
+ const o = obs[i], k = Math.abs(c);
186
+ if (c > 0) {
187
+ pos = plus(pos, times(k, V(o.p)));
188
+ if (o.n)
189
+ neg = plus(neg, times(k, V(o.n)));
190
+ }
191
+ else {
192
+ neg = plus(neg, times(k, V(o.p)));
193
+ if (o.n)
194
+ pos = plus(pos, times(k, V(o.n)));
195
+ }
196
+ }
197
+ const lhs = plus(neg, K(Math.max(a.d, 0))), rhs = plus(pos, K(Math.max(-a.d, 0)));
198
+ return a.eq ? eq(lhs, rhs) : { op: '<=', a: lhs, b: rhs };
199
+ }
200
+ const atomValue = (a, vals) => a.coefs.reduce((s, [i, c]) => s + c * vals[i], 0);
201
+ const atomHolds = (a, vals) => (a.eq ? atomValue(a, vals) === a.d : atomValue(a, vals) >= a.d);
202
+ // The pool for one mode: the facts true at every state of the run in that mode, scored (0: an equality; 1: a bound
203
+ // whose slack never shrinks along the run; 2: the rest), one value before two.
204
+ function pool(runVals, nObs) {
205
+ const out = [];
206
+ const add = (coefs) => {
207
+ const vs = runVals.map(vals => coefs.reduce((s, [i, c]) => s + c * vals[i], 0));
208
+ const lo = Math.min(...vs), hi = Math.max(...vs), arity = coefs.length;
209
+ if (lo === hi) {
210
+ out.push({ coefs, d: lo, eq: true, score: 0, arity });
211
+ return;
212
+ }
213
+ const steady = (sign) => vs.every((v, j) => j === 0 || sign * (v - vs[j - 1]) >= 0) ? 1 : 2;
214
+ out.push({ coefs, d: lo, eq: false, score: steady(1), arity });
215
+ out.push({ coefs: coefs.map(([i, c]) => [i, -c]), d: -hi, eq: false, score: steady(-1), arity });
216
+ };
217
+ for (let i = 0; i < nObs; i++)
218
+ add([[i, 1]]);
219
+ for (let i = 0; i < nObs; i++)
220
+ for (let j = i + 1; j < nObs; j++) {
221
+ add([[i, 1], [j, -1]]);
222
+ add([[i, 1], [j, 1]]);
223
+ }
224
+ return out.sort((a, b) => a.score - b.score || a.arity - b.arity);
225
+ }
226
+ // --- the search ---------------------------------------------------------------------------------------------------------
227
+ export function findNeverEnds(l, opts = {}) {
228
+ return opts.counted ? counted(opts.counted, () => search(l, opts)) : search(l, opts);
229
+ }
230
+ function search(l, opts) {
231
+ const wall0 = performance.now(), now = clock, t0 = now(), until = t0 + (opts.ms ?? 10_000), maxTurns = opts.maxTurns ?? 400;
232
+ let seed = opts.seed ?? 7;
233
+ const rand = (k) => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return Math.floor(seed / 2 ** 31 * k); };
234
+ const stats = { runs: 0, turns: 0, policies: 0, rounds: 0, ms: 0, lassoTried: 0, goalSize: 0 };
235
+ const done = (v) => ({ ...v, stats: { ...stats, ms: Math.round(performance.now() - wall0) } });
236
+ const stateNames = Object.keys(l.state), kept = [...l.params, ...stateNames];
237
+ const allObs = observables(kept), inObs = observables(l.inputs);
238
+ // The modes: state variables compared with a constant by `=` in the loop's conditions (a translated task's pc).
239
+ const modeVars = stateNames.filter(n => [l.while, l.assume ?? T].some(c => JSON.stringify(c).includes(`{"op":"=","a":{"op":"var","name":${JSON.stringify(n)}},"b":{"op":"const"`)));
240
+ const modeOf = (env) => modeVars.map(n => env[n] ?? 0).join(',');
241
+ const modeCond = (key) => and(key === '' ? [] : key.split(',').map((x, i) => eq(V(modeVars[i]), K(Number(x)))));
242
+ const consts = [...constantsOf(l.while), ...constantsOf(l.assume ?? T)].filter(x => x <= 1_000_000);
243
+ const near = [...new Set(consts.flatMap(c => [c, c + 1, c - 1]))];
244
+ const literal = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
245
+ const inConsts = new Map(l.inputs.map(i => [i, [...new Set([0, 1, ...[l.assume ?? T, l.while].flatMap(c => [...JSON.stringify(c).matchAll(new RegExp(literal(`{"op":"=","a":{"op":"var","name":${JSON.stringify(i)}},"b":{"op":"const","value":`) + '(\\d+)', 'g'))].map(m => Number(m[1])))])]]));
246
+ let wh, as, init, body, pre;
247
+ try {
248
+ wh = cC(l.while);
249
+ as = cC(l.assume ?? T);
250
+ pre = cC(l.pre ?? T);
251
+ init = Object.entries(l.state).map(([n, e]) => [n, cE(e)]);
252
+ body = Object.entries(l.body).map(([n, e]) => [n, cE(e)]);
253
+ }
254
+ catch (e) {
255
+ return done({ proven: false, checked: false, why: e.message });
256
+ }
257
+ const start = (ps) => { const env = { ...ps }; for (const [n, f] of init)
258
+ env[n] = f(ps); return env; };
259
+ const turn = (st, input) => {
260
+ work.n++;
261
+ const at = { ...st, ...input };
262
+ if (!wh(at) || !as(at))
263
+ return undefined;
264
+ const out = { ...at };
265
+ for (const [n, f] of body)
266
+ out[n] = f(at);
267
+ return out;
268
+ };
269
+ const keyOf = (env) => kept.map(n => env[n] ?? 0).join(',');
270
+ // A value into an observable: a pair takes any integer, a natural the integer's value below 0 cut to 0 (as the
271
+ // witness's terms write it); a random draw for a natural takes its size.
272
+ const setInt = (o, x, env) => { if (o.n) {
273
+ env[o.p] = Math.max(x, 0);
274
+ env[o.n] = Math.max(-x, 0);
275
+ }
276
+ else
277
+ env[o.p] = Math.max(x, 0); };
278
+ const setDraw = (o, x, env) => setInt(o, o.n ? x : Math.abs(x), env);
279
+ const drawInt = (bound) => (rand(3) === 0 && near.length ? near[rand(near.length)] * (rand(4) === 0 ? -1 : 1) : rand(2 * bound + 1) - bound);
280
+ const drawParams = (bound) => {
281
+ for (let tries = 0; tries < 20; tries++) {
282
+ const ps = {};
283
+ for (const o of observables(l.params))
284
+ setDraw(o, drawInt(bound), ps);
285
+ if (pre(ps))
286
+ return ps;
287
+ }
288
+ return undefined;
289
+ };
290
+ const drawInput = (st, bound) => {
291
+ const input = {};
292
+ for (const o of inObs) {
293
+ const cs = inConsts.get(o.p) ?? [0];
294
+ const x = !o.n && rand(2) === 0 ? cs[rand(cs.length)] : rand(4) === 0 && allObs.length ? valueOf(allObs[rand(allObs.length)], st) * (rand(2) ? 1 : -1) : drawInt(bound);
295
+ setDraw(o, x, input);
296
+ }
297
+ return input;
298
+ };
299
+ const stemOf = (v) => v.trail.slice(0, v.at);
300
+ const certify = (r, by, ms = 8000) => {
301
+ const goal = recurGoal(l, r);
302
+ stats.goalSize = Math.max(stats.goalSize, goalSize(goal.hyps));
303
+ if (goalSize(goal.hyps) > GOAL_MAX)
304
+ return undefined;
305
+ const out = grow(goal, new Map(), { nodes: 0, until: Math.min(until, now() + ms) });
306
+ if (!('tree' in out))
307
+ return undefined;
308
+ const recur = { ...r, tree: out.tree };
309
+ let ok = false;
310
+ try {
311
+ ok = checkRecur(l, recur);
312
+ }
313
+ catch {
314
+ ok = false;
315
+ }
316
+ return ok ? done({ proven: true, checked: true, recur, by }) : undefined;
317
+ };
318
+ const asStem = (inputs) => inputs.map(x => Object.fromEntries(l.inputs.map(n => [n, x[n] ?? 0])));
319
+ const params = (ps) => Object.fromEntries(l.params.map(n => [n, ps[n] ?? 0]));
320
+ // A lasso: the set is the cycle's states (the params and the state), each turn's inputs given at its state.
321
+ const lassoRecur = (v, cycle, by) => {
322
+ if (cycle.length > 64 || cycle.length * kept.length > 600)
323
+ return undefined;
324
+ stats.lassoTried++;
325
+ const at = (st) => and(kept.map(n => eq(V(n), K(st[n] ?? 0))));
326
+ const set = or(cycle.map(c => at(c.st)));
327
+ const wit = {};
328
+ for (const n of l.inputs)
329
+ wit[n] = cycle.slice(0, -1).reduceRight((acc, c) => ite(at(c.st), K(c.input[n] ?? 0), acc), K(cycle.at(-1).input[n] ?? 0));
330
+ const out = certify({ start: params(v.params), stem: asStem(stemOf(v)), set, wit }, by);
331
+ return out && { ...out, lasso: { params: params(v.params), stem: asStem(stemOf(v)), cycle: asStem(cycle.map(c => c.input)) } };
332
+ };
333
+ // 1. Random runs: the states they reach, each with its stem; a lasso on the way is tried at once.
334
+ const visits = [], bounds = [1, 2, 4, 8, 16, 64];
335
+ try {
336
+ // (a fifth of the time, at most 1.5 s, unless only lassos are asked for; at most 4,000 states kept, then only a
337
+ // run's last)
338
+ while (now() < (opts.lassos ? until : Math.min(t0 + (until - t0) * 0.2, t0 + 1500))) {
339
+ const bound = bounds[stats.runs++ % bounds.length], ps = drawParams(bound);
340
+ if (!ps)
341
+ continue;
342
+ let st = start(ps);
343
+ const stem = [], seen = new Map(), trail = [], run = { n: 0 };
344
+ if (visits.length < 4000)
345
+ visits.push({ params: ps, trail: stem, at: 0, st, run });
346
+ for (let n = 0; n < 3000 && now() < until; n++) {
347
+ const key = keyOf(st), back = seen.get(key);
348
+ if (back !== undefined) {
349
+ const cycle = trail.slice(back).map((s, j) => ({ st: s, input: stem[back + j] }));
350
+ const v = lassoRecur({ params: ps, trail: stem, at: back, st: trail[back] }, cycle, 'lasso');
351
+ if (v)
352
+ return v;
353
+ break;
354
+ }
355
+ seen.set(key, n);
356
+ trail.push(st);
357
+ let next, input;
358
+ for (let tries = 0; tries < 40 && !next; tries++) {
359
+ input = drawInput(st, bound);
360
+ next = turn(st, input);
361
+ }
362
+ if (!next)
363
+ break;
364
+ stem.push(input);
365
+ stats.turns++;
366
+ run.n++;
367
+ st = next;
368
+ if ((n % 50 === 49 || n < 8) && visits.length < 4000)
369
+ visits.push({ params: ps, trail: stem, at: stem.length, st, run });
370
+ }
371
+ if (visits.length < 20000 || run.n >= 100)
372
+ visits.push({ params: ps, trail: stem, at: stem.length, st, run });
373
+ }
374
+ }
375
+ catch (e) {
376
+ if (!(e instanceof Overflow))
377
+ return done({ proven: false, checked: false, why: e.message.slice(0, 200) });
378
+ }
379
+ if (opts.lassos)
380
+ return done({ proven: false, checked: false, why: `no lasso in ${stats.runs} runs` });
381
+ // 2. Policies from the states reached.
382
+ const pools = inObs.map(o => {
383
+ const terms = [iConst(0), iConst(1)];
384
+ if (o.n)
385
+ terms.push(iConst(-1));
386
+ for (const c of inConsts.get(o.p) ?? [])
387
+ if (c > 1)
388
+ terms.push(iConst(c));
389
+ for (const x of allObs)
390
+ for (const c of [0, 1, -1])
391
+ terms.push(iAdd(iObs(x), c));
392
+ return terms;
393
+ });
394
+ const compiled = new Map();
395
+ const evalT = (t, env) => { let f = compiled.get(t); if (!f) {
396
+ f = [cE(t.p), cE(t.n)];
397
+ compiled.set(t, f);
398
+ } return f[0](env) - f[1](env); };
399
+ const fuzzy = (c) => {
400
+ if (c.op === 'and') {
401
+ const xs = c.xs.map(fuzzy);
402
+ return env => xs.reduce((s, x) => s + x(env), 0) / xs.length;
403
+ }
404
+ if (c.op === 'or') {
405
+ const xs = c.xs.map(fuzzy);
406
+ return env => Math.max(...xs.map(x => x(env)));
407
+ }
408
+ const b = cC(c);
409
+ return env => (b(env) ? 1 : 0);
410
+ };
411
+ const turnDegree = fuzzy({ op: 'and', xs: [l.while, l.assume ?? T] });
412
+ const degree = (st, input) => { work.n++; try {
413
+ return turnDegree({ ...st, ...input });
414
+ }
415
+ catch {
416
+ return 0;
417
+ } };
418
+ const inputOf = (a, st) => { const out = {}; inObs.forEach((o, i) => setInt(o, evalT(pools[i][a[i]], st), out)); return out; };
419
+ const allowedC = (a, mode) => {
420
+ const sub = {};
421
+ inObs.forEach((o, i) => Object.assign(sub, iInto(pools[i][a[i]], o)));
422
+ if (mode !== '')
423
+ mode.split(',').forEach((x, i) => { sub[modeVars[i]] = K(Number(x)); });
424
+ return simpC(substC({ op: 'and', xs: [l.while, l.assume ?? T] }, { vars: sub, maps: {}, flags: {} }));
425
+ };
426
+ // The seeds: states of the longest runs, the shallowest first (a short stem), then the rest by depth.
427
+ const longest = Math.max(0, ...visits.map(v => v.run?.n ?? 0));
428
+ const order = visits.map((v, i) => ({ v, i, d: v.at, long: (v.run?.n ?? 0) >= Math.min(200, longest) ? 0 : 1 }))
429
+ .sort((a, b) => a.long - b.long || a.d - b.d || a.i - b.i);
430
+ // (and, in turn, the deepest: a run that went on is past the choices its start needed)
431
+ const deep = [...order].sort((a, b) => b.d - a.d || a.i - b.i), seeds = [];
432
+ for (let j = 0; j < order.length; j++)
433
+ seeds.push(order[j].v, deep[j].v);
434
+ for (let s = 0; s < seeds.length * 3 && now() < until; s++) {
435
+ const v = seeds[s % seeds.length];
436
+ stats.policies++;
437
+ const policy = new Map();
438
+ let st = v.st;
439
+ const states = [], inputs = [], seen = new Map();
440
+ let stop = 'stuck', back = -1;
441
+ try {
442
+ for (let n = 0; n < maxTurns && now() < until; n++) {
443
+ const key = keyOf(st);
444
+ if (seen.has(key)) {
445
+ stop = 'repeat';
446
+ back = seen.get(key);
447
+ break;
448
+ }
449
+ seen.set(key, n);
450
+ states.push(st);
451
+ const mode = modeOf(st), chain = policy.get(mode) ?? [];
452
+ let next, input;
453
+ for (const a of chain) {
454
+ input = inputOf(a, st);
455
+ next = turn(st, input);
456
+ if (next)
457
+ break;
458
+ }
459
+ if (!next && chain.length < 4) {
460
+ // A local search on how much of the turn's condition an assignment meets (a conjunction the share of its
461
+ // parts, a disjunction its best part), one input at a time, from a few random starts.
462
+ for (let restart = 0; restart < 6 && !next && now() < until; restart++) {
463
+ const zero = restart === 0 && rand(3) === 0, a = pools.map(p => (zero ? 0 : rand(p.length)));
464
+ let best = degree(st, inputOf(a, st));
465
+ for (let sweep = 0; sweep < 4 && best < 1 && now() < until; sweep++) {
466
+ let moved = false;
467
+ for (const i of pools.map((_, j) => j).sort(() => rand(2) - 0.5)) {
468
+ // (a wide pool is tried at 24 of its terms, drawn afresh each sweep)
469
+ const tries = pools[i].length <= 24 ? pools[i].map((_, j) => j) : Array.from({ length: 24 }, () => rand(pools[i].length));
470
+ for (const j of tries) {
471
+ if (best >= 1)
472
+ break;
473
+ const was = a[i];
474
+ a[i] = j;
475
+ const d = degree(st, inputOf(a, st));
476
+ if (d > best) {
477
+ best = d;
478
+ moved = true;
479
+ }
480
+ else
481
+ a[i] = was;
482
+ }
483
+ }
484
+ if (!moved)
485
+ break;
486
+ }
487
+ input = inputOf(a, st);
488
+ next = turn(st, input);
489
+ if (next) {
490
+ chain.push(a);
491
+ policy.set(mode, chain);
492
+ }
493
+ }
494
+ }
495
+ if (!next) {
496
+ states.pop();
497
+ break;
498
+ }
499
+ inputs.push(input);
500
+ stats.turns++;
501
+ st = next;
502
+ if (n === maxTurns - 1)
503
+ stop = 'long';
504
+ }
505
+ }
506
+ catch (e) {
507
+ if (e instanceof Overflow)
508
+ stop = states.length >= 40 ? 'long' : 'stuck';
509
+ else
510
+ continue;
511
+ }
512
+ if (stop === 'repeat') {
513
+ const cycle = states.slice(back).map((x, j) => ({ st: x, input: inputs[back + j] }));
514
+ const out = lassoRecur({ params: v.params, trail: [...stemOf(v), ...inputs.slice(0, back)], at: v.at + back, st: states[back] }, cycle, 'policy lasso');
515
+ if (out)
516
+ return out;
517
+ }
518
+ if (stop === 'stuck' && states.length < 40)
519
+ continue;
520
+ // The witness: each input by mode, then the first allowed of the mode's assignments.
521
+ const modes = [...policy.keys()];
522
+ const wit = {};
523
+ const allowed = new Map(modes.map(m => [m, policy.get(m).map(a => allowedC(a, m))]));
524
+ inObs.forEach((o, i) => {
525
+ for (const part of o.n ? [o.p, o.n] : [o.p]) {
526
+ const byMode = (m) => {
527
+ const chain = policy.get(m), cs = allowed.get(m);
528
+ const val = (a) => iInto(pools[i][a[i]], o)[part];
529
+ return chain.slice(0, -1).reduceRight((acc, a, j) => ite(cs[j], val(a), acc), val(chain.at(-1)));
530
+ };
531
+ wit[part] = modes.slice(0, -1).reduceRight((acc, m) => ite(modeCond(m), byMode(m), acc), modes.length ? byMode(modes.at(-1)) : K(0));
532
+ }
533
+ });
534
+ // The set: from a burn-in on, the run's states by mode; the constant facts first, then one atom per counterexample.
535
+ const burn = Math.min(Math.floor(states.length / 4), 8), sample = states.slice(burn);
536
+ const byMode = new Map();
537
+ for (const x of sample) {
538
+ const m = modeOf(x);
539
+ if (!policy.has(m))
540
+ continue;
541
+ byMode.set(m, [...(byMode.get(m) ?? []), allObs.map(o => valueOf(o, x))]);
542
+ }
543
+ if ([...byMode.keys()].length === 0)
544
+ continue;
545
+ const atoms = new Map(), pools2 = new Map();
546
+ // (an equality of two values goes in only where neither is constant: the constants' equalities imply it)
547
+ for (const [m, vals] of byMode) {
548
+ const p = pool(vals, allObs.length), fixed = new Set(p.filter(a => a.score === 0 && a.arity === 1).map(a => a.coefs[0][0]));
549
+ pools2.set(m, p);
550
+ atoms.set(m, p.filter(a => a.score === 0 && (a.arity === 1 || a.coefs.every(([i]) => !fixed.has(i)))));
551
+ }
552
+ const setOf = () => {
553
+ const ms = [...byMode.keys()];
554
+ if (modeVars.length === 0)
555
+ return and(atoms.get('').map(a => atomC(a, allObs)));
556
+ return and([or(ms.map(modeCond)), ...ms.map(m => or([{ op: 'not', x: modeCond(m) }, and(atoms.get(m).map(a => atomC(a, allObs)))]))]);
557
+ };
558
+ const first = burn;
559
+ const stemTo = { start: params(v.params), stem: asStem([...stemOf(v), ...inputs.slice(0, first)]) };
560
+ for (let round = 0; round < 40 && now() < until; round++) {
561
+ stats.rounds++;
562
+ const set = setOf();
563
+ const goal = recurGoal(l, { set, wit });
564
+ stats.goalSize = Math.max(stats.goalSize, goalSize(goal.hyps));
565
+ if (goalSize(goal.hyps) > GOAL_MAX)
566
+ break;
567
+ const out = grow(goal, new Map(), { nodes: 0, until: Math.min(until, now() + 6000) });
568
+ if ('tree' in out) {
569
+ // The stem: to the first state of the run (from the start, through the seed's stem and the policy's turns) in
570
+ // the set.
571
+ const inSet = cC(set), all = [...stemOf(v), ...inputs];
572
+ let at = start(v.params), cut = stemTo.stem.length;
573
+ for (let j = 0; j <= all.length; j++) {
574
+ if (inSet(at)) {
575
+ cut = j;
576
+ break;
577
+ }
578
+ if (j === all.length)
579
+ break;
580
+ const nx = turn(at, all[j]);
581
+ if (!nx)
582
+ break;
583
+ at = nx;
584
+ }
585
+ const recur = { ...stemTo, stem: asStem(all.slice(0, cut)), set, wit, tree: out.tree };
586
+ let ok = false;
587
+ try {
588
+ ok = checkRecur(l, recur);
589
+ }
590
+ catch {
591
+ ok = false;
592
+ }
593
+ if (ok)
594
+ return done({ proven: true, checked: true, recur, by: 'recurrent set' });
595
+ break;
596
+ }
597
+ if (out.stuck !== 'sat' || !out.witness)
598
+ break;
599
+ // The counterexample: a state of the set; an atom of its mode false there, true along the run.
600
+ const w = out.witness, rho = Object.fromEntries([...kept, ...l.inputs].map(n => [n, Math.round(w[n] ?? 0)]));
601
+ const m = modeVars.length ? modeOf(rho) : '';
602
+ const cand = pools2.get(m), vals = allObs.map(o => valueOf(o, rho)), have = atoms.get(m);
603
+ const pick = cand?.find(a => !have.includes(a) && !atomHolds(a, vals));
604
+ if (!pick)
605
+ break;
606
+ have.push(pick);
607
+ }
608
+ }
609
+ return done({ proven: false, checked: false, why: `no run found that never ends (${stats.runs} runs, ${stats.policies} policies, ${stats.rounds} rounds)` });
610
+ }
@@ -0,0 +1,17 @@
1
+ import type { Rat } from '../kernel/kernel.js';
2
+ export type { Rat };
3
+ export declare const q: (num: bigint | number, den?: bigint | number) => Rat;
4
+ export declare const Q0: Rat, Q1: Rat;
5
+ export declare const qadd: (a: Rat, b: Rat) => Rat;
6
+ export declare const qsub: (a: Rat, b: Rat) => Rat;
7
+ export declare const qmul: (a: Rat, b: Rat) => Rat;
8
+ export declare const qdiv: (a: Rat, b: Rat) => Rat;
9
+ export declare const qneg: (a: Rat) => Rat;
10
+ export declare const qcmp: (a: Rat, b: Rat) => number;
11
+ export declare const qeq: (a: Rat, b: Rat) => boolean;
12
+ export declare const qmin: (a: Rat, b: Rat) => Rat;
13
+ export declare const qmax: (a: Rat, b: Rat) => Rat;
14
+ export declare const qnum: (a: Rat) => number;
15
+ export declare const qshow: (a: Rat) => string;
16
+ export declare function qparse(x: number | string | bigint | Rat): Rat;
17
+ export declare const qrow: (lin: Record<string, number>, at: Record<string, Rat>) => Rat;
package/dist/core/q.js ADDED
@@ -0,0 +1,52 @@
1
+ const gcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b)
2
+ [a, b] = [b, a % b]; return a; };
3
+ export const q = (num, den = 1n) => {
4
+ let n = BigInt(num), d = BigInt(den);
5
+ if (d === 0n)
6
+ throw new RangeError('a rational with denominator 0');
7
+ if (d < 0n) {
8
+ n = -n;
9
+ d = -d;
10
+ }
11
+ const g = gcd(n, d) || 1n;
12
+ return { num: n / g, den: d / g };
13
+ };
14
+ export const Q0 = q(0), Q1 = q(1);
15
+ export const qadd = (a, b) => q(a.num * b.den + b.num * a.den, a.den * b.den);
16
+ export const qsub = (a, b) => q(a.num * b.den - b.num * a.den, a.den * b.den);
17
+ export const qmul = (a, b) => q(a.num * b.num, a.den * b.den);
18
+ export const qdiv = (a, b) => q(a.num * b.den, a.den * b.num);
19
+ export const qneg = (a) => ({ num: -a.num, den: a.den });
20
+ export const qcmp = (a, b) => { const d = a.num * b.den - b.num * a.den; return d < 0n ? -1 : d > 0n ? 1 : 0; };
21
+ export const qeq = (a, b) => a.num === b.num && a.den === b.den;
22
+ export const qmin = (a, b) => (qcmp(a, b) <= 0 ? a : b);
23
+ export const qmax = (a, b) => (qcmp(a, b) <= 0 ? b : a);
24
+ export const qnum = (a) => Number(a.num) / Number(a.den);
25
+ export const qshow = (a) => (a.den === 1n ? String(a.num) : `${a.num}/${a.den}`);
26
+ // A decimal as written ("12.50", "-0.1", "1e-3"), a fraction ("1/3"), an integer, or a number read as its shortest
27
+ // decimal text (0.1 is 1/10, not the double nearest it).
28
+ export function qparse(x) {
29
+ if (typeof x === 'object')
30
+ return q(x.num, x.den);
31
+ if (typeof x === 'bigint')
32
+ return q(x);
33
+ if (typeof x === 'number' && !Number.isFinite(x))
34
+ throw new RangeError(`${x} is not a rational`);
35
+ const text = String(x).trim();
36
+ const frac = /^(-?\d+)\s*\/\s*(\d+)$/.exec(text);
37
+ if (frac)
38
+ return q(BigInt(frac[1]), BigInt(frac[2]));
39
+ const m = /^(-?)(\d*)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(text);
40
+ if (!m || (!m[2] && !m[3]))
41
+ throw new RangeError(`${text} is not a rational (a decimal like 12.5, or a fraction like 1/3)`);
42
+ const digits = BigInt(`${m[2] || '0'}${m[3] ?? ''}`), exp = Number(m[4] ?? 0) - (m[3]?.length ?? 0);
43
+ const v = exp >= 0 ? q(digits * 10n ** BigInt(exp)) : q(digits, 10n ** BigInt(-exp));
44
+ return m[1] ? qneg(v) : v;
45
+ }
46
+ // The value of a sum Σ c·x + c₀ with integer coefficients (a solver's row) at a rational point.
47
+ export const qrow = (lin, at) => {
48
+ let out = Q0;
49
+ for (const [key, c] of Object.entries(lin))
50
+ out = qadd(out, qmul(q(c), key === '1' ? Q1 : (at[key] ?? Q0)));
51
+ return out;
52
+ };