gdp-wired 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +20 -1
  3. package/dist/core/accel.js +797 -220
  4. package/dist/core/bmc.d.ts +12 -1
  5. package/dist/core/bmc.js +275 -106
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +103 -74
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +65 -27
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +29 -25
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +55 -4
  17. package/dist/core/extract-check.js +248 -122
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +98 -4
  21. package/dist/core/extract-read.js +306 -43
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +609 -79
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.d.ts +1 -0
  27. package/dist/core/extract.js +81 -30
  28. package/dist/core/infer.d.ts +1 -0
  29. package/dist/core/infer.js +126 -64
  30. package/dist/core/machine.d.ts +6 -0
  31. package/dist/core/machine.js +35 -4
  32. package/dist/core/nonterm.d.ts +5 -1
  33. package/dist/core/nonterm.js +133 -45
  34. package/dist/core/q.d.ts +1 -0
  35. package/dist/core/q.js +2 -2
  36. package/dist/core/relation.d.ts +1 -0
  37. package/dist/core/relation.js +20 -36
  38. package/dist/core/solver.d.ts +33 -0
  39. package/dist/core/solver.js +84 -30
  40. package/dist/core/transfer.js +22 -13
  41. package/dist/core/translate.d.ts +1 -1
  42. package/dist/core/translate.js +88 -65
  43. package/dist/core/xstate.d.ts +6 -1
  44. package/dist/core/xstate.js +336 -55
  45. package/dist/kernel/cdcl.js +212 -79
  46. package/dist/kernel/prove.d.ts +36 -5
  47. package/dist/kernel/prove.js +212 -104
  48. package/dist/kernel/reader.d.ts +75 -5
  49. package/dist/kernel/reader.js +533 -76
  50. package/dist/kernel/simplex.d.ts +27 -2
  51. package/dist/kernel/simplex.js +160 -14
  52. package/package.json +3 -2
package/dist/core/data.js CHANGED
@@ -1,7 +1,36 @@
1
+ // Recursive datatypes as values, proven by cyclic proofs. Untrusted: this file states facts and nodes, kernel/prove.ts
2
+ // grows a tree for every goal, and kernel/cyclic.ts checks the whole, as for every cyclic proof (nothing here is new to
3
+ // the kernel). Lean's twin of a proof (lean-kernel/Data.lean and the export's own definitions) is about the datatype as
4
+ // declared: a Lean `inductive`, the functions by pattern matching, the law over them.
5
+ //
6
+ // The encoding: every natural is a value of every datatype (a bijection between the naturals and the datatype's values,
7
+ // which Lean's twin defines and proves), so a value is a natural and two values are equal exactly when they are the same
8
+ // natural. A datatype D is read through maps: `D.tag[x]` (which constructor), `D.<ctor>.<field>[x]` (its fields, 0 under
9
+ // another constructor), `D.size[x]` (1 plus the sizes of its fields of D's group: the rank). A field is a natural, a value
10
+ // of D, of another datatype of D's group (declared together: a rose tree and its forest), or of one declared before (a
11
+ // list of lists); every datatype has its own codes. A constructor of no field is
12
+ // the constant of its tag; one with fields is a map read at its fields (`D.<ctor>[key]`); a function is a map read at
13
+ // its arguments; several arguments are read at their pairing, left-nested (a + b)² + b, as the library reads a function
14
+ // of several arguments (core/dsl.ts's argsKey). The facts, each at every value of its keys:
15
+ // - the shape: D.tag[x] is a constructor's tag, and under tag j, D.size[x] = 1 + the sizes of x's fields of type D,
16
+ // and the fields of every other constructor 0
17
+ // - eta: under tag j, x is constructor j at its own fields (every natural is a value)
18
+ // - each constructor: D.tag[C[key]] = j and each field of C[key] is its argument
19
+ // - each function: f[key] = its body, a match read as ifs on the tag, a field bound by a case read from its map
20
+ // - congruence of each map read at a pairing: equal arguments, equal cells (the kernel compares a pairing's
21
+ // monomials, not its arguments)
22
+ // A law is a node at rank (level, D.size[x]) for an argument x; its uses read it at x's fields (structural induction),
23
+ // or at the arguments of a function's own recursive calls (recursion induction, other arguments changing with them; on a
24
+ // natural n, at n − 1, its rank n), each where the tag is the case's. On a datatype of a group, the law has a companion
25
+ // for each other datatype x's fields reach (the law lifted through each function's own call at such a field), each node
26
+ // using the others at the fields of their datatypes (mutual induction). Lemmas the law needs are found by the values
27
+ // (theory exploration: equations between terms the random values agree on, then the shapes of a predicate kept), proven
28
+ // the same way at lower levels, and used at the terms of the law they match.
29
+ import { argsKey, atMost as leC, get, n as k, same as eqC, walk, x as ev } from "./machine.js";
1
30
  import { substC, substE } from "../kernel/kernel.js";
2
- import { proveCyclic } from "./cyclic.js";
31
+ import { and as andC, implies, proveCyclic } from "./cyclic.js";
3
32
  import { clock, counted, pairedKeys, withDeadline } from "../kernel/prove.js";
4
- import { work } from "./solver.js";
33
+ import { env, work } from "./solver.js";
5
34
  import { rankOfPaths, ranksOfCalls, showC } from "./cycles.js";
6
35
  import { proveThrough, transferPlan } from "./transfer.js";
7
36
  // --- sorts and the AST ------------------------------------------------------------------------------------------------
@@ -302,18 +331,6 @@ export function define(name, params, ret, body, opts = {}) {
302
331
  export const fnParam = (name) => Object.assign((x) => new Nat({ op: 'apply', param: name, arg: natX(x) }), { param: name });
303
332
  const paramsIn = (t) => { const out = []; walk(t, o => { if (o.op === 'apply')
304
333
  out.push(o.param); }); return out; };
305
- function walk(t, f) {
306
- if (Array.isArray(t)) {
307
- t.forEach(x => walk(x, f));
308
- return;
309
- }
310
- if (!t || typeof t !== 'object')
311
- return;
312
- const o = t;
313
- f(o);
314
- for (const v of Object.values(o))
315
- walk(v, f);
316
- }
317
334
  // Each object once, in walk's order (a term shared within another is visited where walk first reaches it).
318
335
  function walkOnce(t, f, seen = new WeakSet()) {
319
336
  if (!t || typeof t !== 'object' || seen.has(t))
@@ -1062,16 +1079,8 @@ export function samples(vars, paramNames, n, seed = 1) {
1062
1079
  return out;
1063
1080
  }
1064
1081
  // --- the encoding -----------------------------------------------------------------------------------------------------
1065
- const ev = (name) => ({ op: 'var', name });
1066
- const k = (value) => ({ op: 'const', value });
1067
- const get = (map, key) => ({ op: 'get', map, key });
1068
- const eqC = (a, b) => ({ op: '=', a, b });
1069
- const leC = (a, b) => ({ op: '<=', a, b });
1070
- const andC = (...xs) => (xs.length === 1 ? xs[0] : { op: 'and', xs });
1071
- const implies = (a, b) => ({ op: 'or', xs: [{ op: 'not', x: a }, b] });
1072
1082
  const yesC = leC(k(0), k(0));
1073
- const pairE = (a, b) => { const s = { op: 'add', a, b }; return { op: 'add', a: { op: 'prod', a: s, b: s }, b }; };
1074
- export const keyOf = (args) => args.slice(1).reduce(pairE, args[0]);
1083
+ export const keyOf = argsKey;
1075
1084
  // The arguments of a key built by keyOf (n of them), read back from its shape.
1076
1085
  export function argsOf(key, n) {
1077
1086
  if (n === 1)
@@ -2636,11 +2645,11 @@ function casesOf(p, unfolded, vars, models) {
2636
2645
  // One attempt: the law's node (and the lemmas', proven before, with their own nodes) at a scheme and a depth. With
2637
2646
  // several cases, a main node uses a node per case (each its guards as hypotheses, its own instances), at rank
2638
2647
  // (level, size, 1) above theirs (level, size, 0); a case node uses the main node at the children.
2639
- const dataTrace = !!globalThis.process?.env?.DATA_TRACE;
2648
+ const dataTrace = !!env.DATA_TRACE;
2640
2649
  // Debugging: every congruence a model's closure makes, not only those explanations use.
2641
- const allCong = !!globalThis.process?.env?.DATA_ALLCONG;
2650
+ const allCong = !!env.DATA_ALLCONG;
2642
2651
  // Debugging: a failed attempt's node whose name the pattern matches, written out (hypotheses, uses, instances).
2643
- const nodeTrace = globalThis.process?.env?.DATA_NODE;
2652
+ const nodeTrace = env.DATA_NODE;
2644
2653
  function attempt(p, fs, l, scheme, depth, lemmas, level, pool) {
2645
2654
  const t0 = clock();
2646
2655
  anchoredAt.clear();
@@ -2856,43 +2865,50 @@ function reached(p, fs, insts, from, ms) {
2856
2865
  return reach.has(id(get(m, keyOf(q.at.slice(0, n))))) && reach.has(id(get(m, keyOf(q.at.slice(n)))));
2857
2866
  });
2858
2867
  }
2859
- // The uses of lemmas a goal's reads match: each lemma's largest reads (those inside no other) matched against the goal's
2860
- // reads of the same map at keys equal, by the instances' equations (every branch), to the read's key.
2861
- // `hits`: the lemmas (their nodes) with any use at all, gathered there (and no uses made): whether a goal reads each.
2862
- function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2863
- const id = tid, parent = new Map(), terms = new Map();
2868
+ // Classes of terms by text (`union`, each term given to `onUnion`), closed under congruence (`congruent`: two reads of a
2869
+ // map, each given to `cell`, at arguments of one class are one), by signatures.
2870
+ function congruence(fs, onUnion) {
2871
+ const parent = new Map(), cells = new Map();
2864
2872
  const find = (x) => { let r = x; while (parent.has(r))
2865
2873
  r = parent.get(r); return r; };
2866
- const union = (x, y) => { terms.set(id(x), x); terms.set(id(y), y); const a = find(id(x)), b = find(id(y)); if (a !== b)
2874
+ const union = (x, y) => { onUnion?.(x); onUnion?.(y); const a = find(tid(x)), b = find(tid(y)); if (a !== b)
2867
2875
  parent.set(a, b); };
2868
- const leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
2869
- for (const q of insts)
2870
- for (const [a, b] of equalities(holdsAt(fs, q)))
2871
- for (const leaf of leaves(b))
2872
- union(a, leaf);
2873
- // Closed under congruence (two reads of one map at arguments of one class), by signatures.
2874
- const cells = new Map(), classes = new Map();
2875
- const close = (t) => {
2876
- walkOnce(t, o => { if (o.op !== 'get')
2877
- return; const n = fs.arity.get(o.map), as = n ? argsOf(o.key, n) : undefined; if (as)
2878
- (cells.get(o.map) ?? cells.set(o.map, []).get(o.map)).push({ key: o.key, as }); });
2876
+ const cell = (o) => { const n = fs.arity.get(o.map), as = n ? argsOf(o.key, n) : undefined; if (as)
2877
+ (cells.get(o.map) ?? cells.set(o.map, []).get(o.map)).push({ key: o.key, as }); };
2878
+ const congruent = () => {
2879
2879
  for (let changed = true, rounds = 0; changed && rounds < 8; rounds++) {
2880
2880
  changed = false;
2881
2881
  for (const [map, list] of cells) {
2882
2882
  const bySig = new Map();
2883
2883
  for (const x of list) {
2884
- const sig = x.as.map(t2 => find(id(t2))).join('\u0001'), y = bySig.get(sig), cx = get(map, x.key);
2885
- if (!y) {
2884
+ const sig = x.as.map(t => find(tid(t))).join('\u0001'), y = bySig.get(sig), cx = get(map, x.key);
2885
+ if (!y)
2886
2886
  bySig.set(sig, cx);
2887
- continue;
2888
- }
2889
- if (find(id(y)) !== find(id(cx))) {
2887
+ else if (find(tid(y)) !== find(tid(cx))) {
2890
2888
  union(y, cx);
2891
2889
  changed = true;
2892
2890
  }
2893
2891
  }
2894
2892
  }
2895
2893
  }
2894
+ };
2895
+ return { find, union, cell, cells, congruent };
2896
+ }
2897
+ // The uses of lemmas a goal's reads match: each lemma's largest reads (those inside no other) matched against the goal's
2898
+ // reads of the same map at keys equal, by the instances' equations (every branch), to the read's key.
2899
+ // `hits`: the lemmas (their nodes) with any use at all, gathered there (and no uses made): whether a goal reads each.
2900
+ function lemmaUsesFor(p, fs, lemmas, from, insts, models = [], spare, hits) {
2901
+ const terms = new Map(), { find, union, cell, congruent } = congruence(fs, x => terms.set(tid(x), x));
2902
+ const leaves = (e) => (e.op === 'if' ? [...leaves(e.then), ...leaves(e.else)] : [e]);
2903
+ for (const q of insts)
2904
+ for (const [a, b] of equalities(holdsAt(fs, q)))
2905
+ for (const leaf of leaves(b))
2906
+ union(a, leaf);
2907
+ const classes = new Map();
2908
+ const close = (t) => {
2909
+ walkOnce(t, o => { if (o.op === 'get')
2910
+ cell(o); });
2911
+ congruent();
2896
2912
  classes.clear();
2897
2913
  for (const [key, e] of terms) {
2898
2914
  const r = find(key);
@@ -3078,11 +3094,7 @@ const matchedAt = new WeakMap();
3078
3094
  // is a step the case's own rewriting passes through, from one of its terms to another (ripple's fertilisation), where
3079
3095
  // a use that only matches one of its terms is one its models alone may agree with (app (t, []) for t).
3080
3096
  function caseJoins(fs, from, insts, hyps, ms) {
3081
- const parent = new Map();
3082
- const find = (x) => { let r = x; while (parent.has(r))
3083
- r = parent.get(r); return r; };
3084
- const union = (x, y) => { const a = find(tid(x)), b = find(tid(y)); if (a !== b)
3085
- parent.set(a, b); };
3097
+ const { find, union, cell, cells, congruent } = congruence(fs);
3086
3098
  const truth = (c) => { let v; for (const { m, env } of ms) {
3087
3099
  let t;
3088
3100
  try {
@@ -3119,25 +3131,10 @@ function caseJoins(fs, from, insts, hyps, ms) {
3119
3131
  eqs(holdsAt(fs, q));
3120
3132
  for (const h of hyps)
3121
3133
  eqs(h);
3122
- const cells = new Map(), seen = new Set();
3134
+ const seen = new Set();
3123
3135
  walkOnce([from, insts.map(q => holdsAt(fs, q)), hyps], o => { if (o.op !== 'get')
3124
- return; seen.add(tid(o)); const n = fs.arity.get(o.map), as = n ? argsOf(o.key, n) : undefined; if (as)
3125
- (cells.get(o.map) ?? cells.set(o.map, []).get(o.map)).push({ key: o.key, as }); });
3126
- for (let changed = true, rounds = 0; changed && rounds < 8; rounds++) {
3127
- changed = false;
3128
- for (const [map, list] of cells) {
3129
- const bySig = new Map();
3130
- for (const x of list) {
3131
- const sig = x.as.map(t => find(tid(t))).join('\u0001'), y = bySig.get(sig), cx = get(map, x.key);
3132
- if (!y)
3133
- bySig.set(sig, cx);
3134
- else if (find(tid(y)) !== find(tid(cx))) {
3135
- union(y, cx);
3136
- changed = true;
3137
- }
3138
- }
3139
- }
3140
- }
3136
+ return; seen.add(tid(o)); cell(o); });
3137
+ congruent();
3141
3138
  const bySig = new Map();
3142
3139
  for (const [map, list] of cells)
3143
3140
  for (const x of list)
@@ -3355,33 +3352,6 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
3355
3352
  vs.add(o.name); }); return vs.size; };
3356
3353
  eqs.sort((a, b) => a.size - b.size || nvars(b) - nvars(a));
3357
3354
  const rules = [];
3358
- const matchX = (pat, t, vs, sub) => {
3359
- if (pat.op === 'var' && vs.has(pat.name)) {
3360
- const had = sub.get(pat.name);
3361
- if (had)
3362
- return JSON.stringify(had) === JSON.stringify(t);
3363
- sub.set(pat.name, t);
3364
- return true;
3365
- }
3366
- if (pat.op !== t.op)
3367
- return false;
3368
- const po = pat, to = t;
3369
- for (const key of Object.keys(po)) {
3370
- const a2 = po[key], b2 = to[key];
3371
- if (Array.isArray(a2)) {
3372
- if (!Array.isArray(b2) || a2.length !== b2.length || !a2.every((x, i) => matchX(x, b2[i], vs, sub)))
3373
- return false;
3374
- }
3375
- else if (a2 && typeof a2 === 'object') {
3376
- if (!b2 || typeof b2 !== 'object' || !matchX(a2, b2, vs, sub))
3377
- return false;
3378
- }
3379
- else if (a2 !== b2)
3380
- return false;
3381
- }
3382
- return true;
3383
- };
3384
- const substX = (x, sub) => JSON.parse(JSON.stringify(x), (_, v) => (v && typeof v === 'object' && v.op === 'var' && sub.has(v.name) ? sub.get(v.name) : v));
3385
3355
  const norm = (x, depth = 0) => {
3386
3356
  if (depth > 30)
3387
3357
  return x;
@@ -3399,7 +3369,7 @@ export function conjectures(p, l, max = 24, maxSize = 6) {
3399
3369
  for (const r of rules) {
3400
3370
  const sub = new Map();
3401
3371
  if (matchX(r.l, t, r.vs, sub))
3402
- return norm(substX(r.r, sub), depth + 1);
3372
+ return norm(substXs(r.r, sub), depth + 1);
3403
3373
  }
3404
3374
  return t;
3405
3375
  };
@@ -3603,6 +3573,25 @@ function canonText(y, vars) {
3603
3573
  }
3604
3574
  const substXs = (x, sub) => (sub.size ? JSON.parse(JSON.stringify(x), (_, v) => (v && typeof v === 'object' && v.op === 'var' && sub.has(v.name) ? sub.get(v.name) : v)) : x);
3605
3575
  const sameX = (a, b) => JSON.stringify(a) === JSON.stringify(b);
3576
+ // Whether t is pat with each of `free` given a term (in `sub`, one term a name).
3577
+ const matchX = (pat, t, free, sub) => {
3578
+ if (pat && typeof pat === 'object' && pat.op === 'var' && free.has(pat.name)) {
3579
+ const n = pat.name, had = sub.get(n);
3580
+ if (had)
3581
+ return sameX(had, t);
3582
+ sub.set(n, t);
3583
+ return true;
3584
+ }
3585
+ if (Array.isArray(pat))
3586
+ return Array.isArray(t) && pat.length === t.length && pat.every((x, i) => matchX(x, t[i], free, sub));
3587
+ if (pat && typeof pat === 'object') {
3588
+ if (!t || typeof t !== 'object' || Array.isArray(t))
3589
+ return false;
3590
+ const po = pat, to = t;
3591
+ return Object.keys(po).length === Object.keys(to).length && Object.keys(po).every(key => matchX(po[key], to[key], free, sub));
3592
+ }
3593
+ return pat === t;
3594
+ };
3606
3595
  // A term with its definitions unfolded where they are decided: a call whose body, its parameters given, decides its
3607
3596
  // first choice (the match, natmatch or if at its top, and the ones in the case taken) is that case's term (else the
3608
3597
  // call stays); a match of a constructor, a natmatch of a constant or of a successor (x + k), an if whose condition the
@@ -3810,24 +3799,6 @@ function stepsOf(p, l) {
3810
3799
  const rewrite = (x, from, to) => { const f = JSON.stringify(from); return JSON.parse(JSON.stringify(x), (_, v) => (v && typeof v === 'object' && v.op && JSON.stringify(v) === f ? to : v)); };
3811
3800
  // The hypothesis at any values of the law's other variables (`free`): from's instances rewritten to to's, outermost
3812
3801
  // first (qrev (x, a :: y) to rev x ++ (a :: y), the hypothesis read at y := a :: y). Whether one was.
3813
- const matchP = (pat, t, free, sub) => {
3814
- if (pat && typeof pat === 'object' && pat.op === 'var' && free.has(pat.name)) {
3815
- const n = pat.name, had = sub.get(n);
3816
- if (had)
3817
- return sameX(had, t);
3818
- sub.set(n, t);
3819
- return true;
3820
- }
3821
- if (Array.isArray(pat))
3822
- return Array.isArray(t) && pat.length === t.length && pat.every((x, i) => matchP(x, t[i], free, sub));
3823
- if (pat && typeof pat === 'object') {
3824
- if (!t || typeof t !== 'object' || Array.isArray(t))
3825
- return false;
3826
- const po = pat, to = t;
3827
- return Object.keys(po).length === Object.keys(to).length && Object.keys(po).every(key => matchP(po[key], to[key], free, sub));
3828
- }
3829
- return pat === t;
3830
- };
3831
3802
  const rewriteP = (x, from, to, free) => {
3832
3803
  let hit = false;
3833
3804
  const go = (t) => {
@@ -3836,7 +3807,7 @@ function stepsOf(p, l) {
3836
3807
  if (Array.isArray(t))
3837
3808
  return t.map(go);
3838
3809
  const sub = new Map();
3839
- if (t.op && matchP(from, t, free, sub)) {
3810
+ if (t.op && matchX(from, t, free, sub)) {
3840
3811
  hit = true;
3841
3812
  return substXs(to, sub);
3842
3813
  }
@@ -11,9 +11,10 @@
11
11
  // out.verdict // the laws, proven of out.rule: r with its functions and lists made again with the lemmas
12
12
  // out.found // per function or list, the lemmas found, as source to paste into recur(...) or carriesList(...)
13
13
  import { quietly } from "./cyclic.js";
14
- import { any, atMost, compileFunction, evalC, evalE, n, plus, prod, same, times, x } from "./machine.js";
14
+ import { any, atMost, compileFunction, evalC, evalE, n, plus, prod, same, seeded, times, x } from "./machine.js";
15
15
  import { Unproven, lit, proveFold, proveSteps, recur, recurOf } from "./dsl.js";
16
- const seeded = (seed) => { let s = seed; return (k) => { s = (s * 1103515245 + 12345) % 2 ** 31; return Math.floor(s / 2 ** 31 * k); }; };
16
+ import { gcd, plus as addLin } from "./solver.js";
17
+ import { closedForm as fit, nfold, polyOf } from "./accel.js";
17
18
  const valueOf = (t) => (typeof t === 'number' ? t : t.val);
18
19
  const evalLin = (l, at) => Object.entries(l).reduce((s, [a, c]) => s + c * (a === '1' ? 1 : at[a]), 0);
19
20
  const holds = (c, at) => { const v = evalLin(c.lin, at); return c.rel === '=' ? v === 0 : v <= 0; };
@@ -85,39 +86,76 @@ function linearCands(target, forms, samples, show) {
85
86
  const dedupe = (cs) => [...new Map(cs.map(c => [c.name, c])).values()];
86
87
  // A statement whose coefficients are naturals a term can hold (a fit to values near 2^53 can make one that isn't).
87
88
  const exact = (c) => Object.values(c.lin).every(Number.isSafeInteger);
88
- // A polynomial in x of degree 3 at most, exact over the rationals, as d·f = a·x·x·x + b·x·x + c·x + e with whole
89
- // numbers: fitted to four points (Newton's differences), kept when every sample meets it.
90
- function closedForm(samples, show) {
89
+ // A polynomial in x of degree 2 or 3, exact over the rationals, as d·f = a·x·x·x + b·x·x + c·x + e with whole numbers,
90
+ // from core/accel.ts's closed forms: the recurrence's own where its step is affine in f and a polynomial in x (the
91
+ // engine on f and the powers of x, a triangular system), else the values' (the engine on the numbers: the shortest
92
+ // recurrence they all meet); kept when every sample meets it.
93
+ function closedForm(samples, show, rec) {
91
94
  const at = new Map();
92
95
  for (const s of samples) {
93
96
  if (at.has(s.x) && at.get(s.x) !== s.f)
94
97
  return [];
95
98
  at.set(s.x, s.f);
96
99
  }
97
- if (![0, 1, 2].every(x => at.has(x)))
100
+ const seq = [];
101
+ while (at.has(seq.length))
102
+ seq.push({ 1: at.get(seq.length) });
103
+ const p = (() => {
104
+ const next = rec && powers(rec.next), zero = rec?.zero.op === 'const' ? rec.zero.value : undefined;
105
+ const f = next && zero !== undefined ? nfold({ prev: 1 }, { x: { x: 1, 1: 1 }, xx: { xx: 1, x: 2, 1: 1 }, xxx: { xxx: 1, xx: 3, x: 3, 1: 1 }, prev: next }) : undefined;
106
+ const start = (c) => ({ 1: (c['1'] ?? 0) + (c.prev ?? 0) * zero });
107
+ if (f)
108
+ return { terms: f.terms.map(t => ({ ...t, c: start(t.c) })), den: f.den };
109
+ return seq.length >= 3 ? fit(seq, false) : undefined;
110
+ })();
111
+ const cs = p && polyOf(p);
112
+ if (!cs || cs.length < 3 || cs.length > 4)
98
113
  return [];
99
- const [f0, f1, f2] = [at.get(0), at.get(1), at.get(2)];
100
- const keep = (lin) => {
101
- const g = Object.values(lin).reduce((p, q) => gcd(p, Math.abs(q)), 0);
102
- const c = { name: '', rel: '=', lin: Object.fromEntries(Object.entries(lin).map(([a, k]) => [a, k / g]).filter(([, k]) => k !== 0)) };
103
- c.name = nameOf(c, show, 'f');
104
- return exact(c) && samples.every(s => holds(c, s)) ? [c] : [];
105
- };
106
- // f = a x² + b x + c: c = f0, a = (f2 - 2 f1 + f0) / 2, b = f1 - f0 - a; times 2 to keep whole numbers.
107
- const A = f2 - 2 * f1 + f0, B = 2 * (f1 - f0) - A, C = 2 * f0;
108
- const square = A === 0 ? [] : keep({ f: 2, xx: -A, x: -B, 1: -C });
109
- if (square.length || !at.has(3))
110
- return square;
111
- // f = Δ0 + Δ1·x + Δ2·x(x − 1)/2 + Δ3·x(x − 1)(x − 2)/6, times 6: x³ by Δ3, x² by 3Δ2 − 3Δ3, x by 6Δ1 − 3Δ2 + 2Δ3.
112
- const d1 = f1 - f0, d2 = f2 - 2 * f1 + f0, d3 = at.get(3) - 3 * f2 + 3 * f1 - f0;
113
- if (d3 === 0)
114
- return []; // degree 2 at most: above, or linear (the bounds find it)
115
- return keep({ f: 6, xxx: -d3, xx: -(3 * d2 - 3 * d3), x: -(6 * d1 - 3 * d2 + 2 * d3), 1: -6 * f0 });
114
+ // Σ c_k·C(x, k) / den, times 6·den: C(x, 2)·6 = 3·x·x − 3·x, C(x, 3)·6 = x·x·x − 3·x·x + 2·x
115
+ const [c0, c1, c2, c3] = [0, 1, 2, 3].map(k => cs[k]?.['1'] ?? 0);
116
+ const lin = { f: 6 * p.den, xxx: -c3, xx: -(3 * c2 - 3 * c3), x: -(6 * c1 - 3 * c2 + 2 * c3), 1: -6 * c0 };
117
+ const g = Object.values(lin).reduce((a, b) => gcd(a, Math.abs(b)), 0);
118
+ const c = { name: '', rel: '=', lin: Object.fromEntries(Object.entries(lin).map(([a, k]) => [a, k / g]).filter(([, k]) => k !== 0)) };
119
+ c.name = nameOf(c, show, 'f');
120
+ return exact(c) && samples.every(s => holds(c, s)) ? [c] : [];
121
+ }
122
+ // A step as a form over prev and the powers of x up to x·x·x (x, xx, xxx), or undefined where it isn't one.
123
+ function powers(e) {
124
+ switch (e.op) {
125
+ case 'var': return e.name === 'x' || e.name === 'prev' ? { [e.name]: 1 } : undefined;
126
+ case 'const': return { 1: e.value };
127
+ case 'add': {
128
+ const a = powers(e.a), b = powers(e.b);
129
+ return a && b && addLin(a, b);
130
+ }
131
+ case 'mul': {
132
+ const a = powers(e.a);
133
+ return a && Object.fromEntries(Object.entries(a).map(([k, c]) => [k, c * e.k]));
134
+ }
135
+ case 'prod': {
136
+ const a = powers(e.a), b = powers(e.b);
137
+ if (!a || !b)
138
+ return undefined;
139
+ let o = {};
140
+ for (const [u, c] of Object.entries(a))
141
+ for (const [w, d] of Object.entries(b)) {
142
+ if (u !== '1' && w !== '1' && (u === 'prev' || w === 'prev' || u.length + w.length > 3))
143
+ return undefined;
144
+ const m = u === '1' ? w : w === '1' ? u : 'x'.repeat(u.length + w.length);
145
+ o = addLin(o, { [m]: c * d });
146
+ }
147
+ return o;
148
+ }
149
+ case 'sub':
150
+ case 'min':
151
+ case 'max':
152
+ case 'if':
153
+ case 'get': return undefined;
154
+ }
116
155
  }
117
156
  // The law a goal is of (the kernel names each goal after its law: '<law> @step').
118
157
  const lawOfGoal = (goal) => goal.replace(/ @(start|step|step law|\d+ steps|leaf|node)$/, '');
119
158
  const isGoalOf = (goal) => (c) => { const law = lawOfGoal(goal); return law === c.name || law === `${c.name} at y`; };
120
- const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
121
159
  // --- recurrences ---------------------------------------------------------------------------------------------------
122
160
  const showRecur = (a) => (a === 'f' ? 'f(x)' : a === 'g' ? 'f(y)' : a === 'xx' ? 'x·x' : a === 'xxx' ? 'x·x·x' : a);
123
161
  const srcRecur = (a) => (a === 'xx' ? 'x.mul(x)' : a === 'xxx' ? 'x.mul(x).mul(x)' : a);
@@ -146,7 +184,7 @@ function recurSamples(d, args) {
146
184
  return out;
147
185
  }
148
186
  // Lemmas about every x and f(x), and laws between two points, that every value meets.
149
- function recurCands(samples, args) {
187
+ function recurCands(samples, args, rec) {
150
188
  const slopes = new Set();
151
189
  const byArgs = new Map();
152
190
  for (const s of samples) {
@@ -163,7 +201,7 @@ function recurCands(samples, args) {
163
201
  const sorted = [...slopes].sort((a, b) => a - b), picked = [...new Set([...sorted.slice(0, 3), ...sorted.slice(-1)])];
164
202
  const xs = [{}, ...picked.map(s => ({ x: s }))];
165
203
  const forms = xs.flatMap(fx => [fx, ...args.map(a => ({ ...fx, [a]: 1 }))]);
166
- const lemmas = [...linearCands('f', forms, samples, showRecur), ...(args.length ? [] : closedForm(samples, showRecur))];
204
+ const lemmas = [...linearCands('f', forms, samples, showRecur), ...(args.length ? [] : closedForm(samples, showRecur, rec))];
167
205
  const pairs = [];
168
206
  for (const run of byArgs.values())
169
207
  for (const a of run)
@@ -285,7 +323,7 @@ function discoverSearch(r, laws, stepLaws, first) {
285
323
  // fitted exactly) first with it alone: it decides the function, and the bounds beside it, which the closed form
286
324
  // implies only through products, are slow to prove by induction; the rest where the laws aren't proven with it.
287
325
  const cands = new Map(fns.flatMap(([n, d]) => { const src = recurOf(d); if (!src)
288
- return []; const args = [...(src.def.args ?? [])]; return [[n, recurCands(recurSamples(d, args), args)]]; }));
326
+ return []; const args = [...(src.def.args ?? [])]; return [[n, recurCands(recurSamples(d, args), args, d.recur)]]; }));
289
327
  const exact = (c) => c.rel === '=' && ('xx' in c.lin || 'xxx' in c.lin);
290
328
  const makeFns = (closedOnly) => {
291
329
  const out = {};
@@ -1,5 +1,6 @@
1
- import { type C, type E, type Law, type Recurrence, type Machine, type Request, type State } from './machine.js';
1
+ import { type C, type E, type Law, type Recurrence, type Machine, type Rand, type Request, type State } from './machine.js';
2
2
  import { type Fold, type Goal, type Liveness, type Loop, type Recur, type StepLaw, type Tree } from '../kernel/kernel.js';
3
+ import { type Report } from '../kernel/prove.js';
3
4
  export type TermLike = Term | number;
4
5
  export declare const termOf: (t: TermLike) => E;
5
6
  export declare class Term {
@@ -54,7 +55,6 @@ export declare const choose: (c: Cond, then: Cond, otherwise: Cond) => Cond;
54
55
  export declare function same(a: unknown, b: unknown): Cond;
55
56
  export declare const count: (c: Cond) => Term;
56
57
  export declare const sum: (first: TermLike, ...rest: TermLike[]) => Term;
57
- type Rand = (k: number) => number;
58
58
  export type Raw = number | boolean | string | null | undefined | RawObject | readonly Raw[];
59
59
  export type RawObject = {
60
60
  readonly [field: string]: Raw;
@@ -853,6 +853,7 @@ export declare class Unproven extends Error {
853
853
  readonly verdict: Verdict;
854
854
  constructor(what: string, verdict: Verdict);
855
855
  }
856
+ export declare const verdictOf: (out: Report) => Verdict;
856
857
  export declare function proveRule(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], opts?: ProveOptions): Verdict;
857
858
  export declare function proveSteps(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], stepLaws: StepLaw[], opts?: ProveOptions): Verdict;
858
859
  export type { StepLaw };