gdp-wired 0.24.0 → 0.26.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 +44 -0
  3. package/dist/core/accel.js +955 -0
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +409 -174
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +9 -1
  11. package/dist/core/data.js +872 -168
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  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 +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +364 -40
  29. package/dist/core/machine.d.ts +6 -0
  30. package/dist/core/machine.js +35 -3
  31. package/dist/core/nonterm.d.ts +9 -2
  32. package/dist/core/nonterm.js +173 -9
  33. package/dist/core/q.d.ts +1 -0
  34. package/dist/core/q.js +2 -2
  35. package/dist/core/relation.d.ts +1 -0
  36. package/dist/core/relation.js +95 -39
  37. package/dist/core/solver.d.ts +12 -0
  38. package/dist/core/solver.js +76 -30
  39. package/dist/core/transfer.js +23 -14
  40. package/dist/core/translate.d.ts +1 -1
  41. package/dist/core/translate.js +22 -49
  42. package/dist/core/xstate.d.ts +6 -1
  43. package/dist/core/xstate.js +336 -55
  44. package/dist/kernel/cdcl.d.ts +5 -0
  45. package/dist/kernel/cdcl.js +44 -8
  46. package/dist/kernel/prove.d.ts +6 -1
  47. package/dist/kernel/prove.js +101 -85
  48. package/dist/kernel/reader.d.ts +1 -0
  49. package/dist/kernel/reader.js +4 -3
  50. package/dist/kernel/simplex.d.ts +1 -1
  51. package/dist/kernel/simplex.js +13 -1
  52. package/package.json +3 -2
@@ -11,6 +11,8 @@
11
11
  // row is strict), so the answer is refuted or sat, the witness exact (`rational`), the derivation one check.ts takes
12
12
  // with no cut: the integers are this with the cut rule, and a strict row over them is lin + 1 <= 0.
13
13
  import { Q0, Q1, q, qadd, qcmp, qdiv, qneg, qnum, qrow, qsub } from "./q.js";
14
+ // The process's environment (the switches and traces the searches read), empty where there is none.
15
+ export const env = globalThis.process?.env ?? {};
14
16
  export const v = (name) => ({ [name]: 1 });
15
17
  export const k = (value) => (value === 0 ? {} : { 1: value });
16
18
  // (Plain loops, no intermediate arrays: these run millions of times in a proof. Each keeps the keys in the order they
@@ -57,8 +59,43 @@ export const eq = (a, b, label) => [...le(a, b, label ?? `${show(a)} = ${show(b)
57
59
  export const nat = (...names) => names.flatMap(name => le(k(0), v(name), `${name} >= 0`));
58
60
  // not (lin <= 0) over the integers is lin >= 1, i.e. 1 − lin <= 0.
59
61
  export const negate = (c) => ({ lin: add(k(1), scale(c.lin, -1)), label: `not (${c.label})` });
60
- const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
61
- const vars = (lin) => Object.keys(lin).filter(key => key !== '1');
62
+ export const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
63
+ export const vars = (lin) => Object.keys(lin).filter(key => key !== '1');
64
+ // The relation's and the accelerations' arithmetic (a's keys first, then b's new ones, no zero kept).
65
+ export const plus = (a, b, f = 1) => { const o = { ...a }; for (const x in b) {
66
+ o[x] = (o[x] ?? 0) + f * b[x];
67
+ if (!o[x])
68
+ delete o[x];
69
+ } return o; };
70
+ export const times = (a, f) => { const o = {}; if (f)
71
+ for (const x in a)
72
+ o[x] = a[x] * f; return o; };
73
+ export const konst = (c) => (c ? { 1: c } : {});
74
+ // A term as a linear form where it is one (names, constants, sums and constant multiples).
75
+ export const linOfE = (e) => {
76
+ switch (e.op) {
77
+ case 'var': return { [e.name]: 1 };
78
+ case 'const': return konst(e.value);
79
+ case 'add': {
80
+ const a = linOfE(e.a), b = linOfE(e.b);
81
+ return a && b && plus(a, b);
82
+ }
83
+ case 'mul': {
84
+ const a = linOfE(e.a);
85
+ return a && times(a, e.k);
86
+ }
87
+ case 'sub':
88
+ case 'prod':
89
+ case 'min':
90
+ case 'max':
91
+ case 'if':
92
+ case 'get': return undefined;
93
+ }
94
+ };
95
+ // l with each name of m's replaced by its form there
96
+ export const subst = (l, m) => { let o = {}; for (const [x, c] of Object.entries(l))
97
+ o = plus(o, x !== '1' && m[x] ? times(m[x], c) : { [x]: c }); return o; };
98
+ export const canon = (l) => JSON.stringify(Object.keys(l).sort().map(x => [x, l[x]]));
62
99
  // maxRows: elimination can square the rows each round; past this many live rows, or a round that would make more than
63
100
  // five times as many before merging them, it gives up with `unknown`.
64
101
  // The rows the solver has read and made, which a counted search reads as its clock (kernel/prove.ts's `counted`).
@@ -304,6 +341,41 @@ function prune(steps, last) {
304
341
  return s.kind === 'combine' ? { ...s, a: at.get(s.a), b: at.get(s.b) } : s.kind === 'cut' ? { ...s, of: at.get(s.of) } : s;
305
342
  });
306
343
  }
344
+ // A float simplex's steps (refuteFast's, cycles.ts's floatSolve): the row leaving where a column enters, the least ratio
345
+ // (Bland's tie-break by basis index; -1: unbounded), and its pivot, the reduced costs z with it.
346
+ export const ratioRow = (T, basis, enter, cols, eps) => {
347
+ let leave = -1, best = Infinity;
348
+ for (let r = 0; r < T.length; r++) {
349
+ const a = T[r][enter];
350
+ if (a > eps) {
351
+ const ratio = T[r][cols] / a;
352
+ if (ratio < best - eps || (Math.abs(ratio - best) <= eps && basis[r] < basis[leave])) {
353
+ best = ratio;
354
+ leave = r;
355
+ }
356
+ }
357
+ }
358
+ return [leave, best];
359
+ };
360
+ export function pivot(T, z, basis, leave, enter, cols) {
361
+ const p = T[leave], pv = p[enter];
362
+ for (let j = 0; j <= cols; j++)
363
+ p[j] /= pv;
364
+ for (let r = 0; r < T.length; r++)
365
+ if (r !== leave) {
366
+ const f = T[r][enter];
367
+ if (f !== 0) {
368
+ const row = T[r];
369
+ for (let j = 0; j <= cols; j++)
370
+ row[j] -= f * p[j];
371
+ }
372
+ }
373
+ const f = z ? z[enter] : 0;
374
+ if (f !== 0)
375
+ for (let j = 0; j <= cols; j++)
376
+ z[j] -= f * p[j];
377
+ basis[leave] = enter;
378
+ }
307
379
  // A refutation found fast, where there is one over the rationals: Farkas' lemma says rows a·x + c <= 0 (x free) have no
308
380
  // rational solution exactly when some λ >= 0 has Σ λ·a = 0 and Σ λ·c > 0. A floating-point simplex looks for such λ
309
381
  // (phase one on Σ λ·a = 0, Σ λ·c = 1), and elimination on the rows it uses alone (usually a handful) gives the
@@ -354,36 +426,10 @@ export function refuteFast(constraints, maxRows = 2_000, integral = true) {
354
426
  }
355
427
  if (enter < 0)
356
428
  break;
357
- let leave = -1, best = Infinity;
358
- for (let r = 0; r < R; r++) {
359
- const a = T[r][enter];
360
- if (a > eps) {
361
- const ratio = T[r][cols] / a;
362
- if (ratio < best - eps || (Math.abs(ratio - best) <= eps && basis[r] < basis[leave])) {
363
- best = ratio;
364
- leave = r;
365
- }
366
- }
367
- }
429
+ const [leave] = ratioRow(T, basis, enter, cols, eps);
368
430
  if (leave < 0)
369
431
  return undefined; // unbounded: cannot happen in phase one; give up rather than guess
370
- const p = T[leave], pv = p[enter];
371
- for (let j = 0; j <= cols; j++)
372
- p[j] /= pv;
373
- for (let r = 0; r < R; r++)
374
- if (r !== leave) {
375
- const f = T[r][enter];
376
- if (f !== 0) {
377
- const row = T[r];
378
- for (let j = 0; j <= cols; j++)
379
- row[j] -= f * p[j];
380
- }
381
- }
382
- const f = z[enter];
383
- if (f !== 0)
384
- for (let j = 0; j <= cols; j++)
385
- z[j] -= f * p[j];
386
- basis[leave] = enter;
432
+ pivot(T, z, basis, leave, enter, cols);
387
433
  }
388
434
  if (-z[cols] > 1e-7)
389
435
  return undefined; // the artificials can't all leave: no λ, so a rational solution exists
@@ -1,3 +1,24 @@
1
+ // A datatype law said another way, proven that way, and the law read back from it (core/data.ts's proveData calls this
2
+ // where the law alone at one unfolding isn't proven). Untrusted, as the search is: each step is a node of the one
3
+ // cyclic proof kernel/cyclic.ts checks, and Lean's twin reads it as any other.
4
+ // - Unfolding: a call to a function that isn't recursive is its body at the call's arguments, in the law and in the
5
+ // copies below (each again, down to the recursive functions), so the induction is chosen on what the law means. A
6
+ // law that grows past eight times its size so (definitions unfolded into each other's arguments) isn't unfolded.
7
+ // - Bridges: a recursive function of one or two naturals that computes a built-in (+, ∸, min, max, ≤, <, =, ≥, >, ≠,
8
+ // x + 1, x ∸ 1, 2·x, x = 0) at every argument up to 6 (12 for one) is a candidate, unless its bridge law (the function
9
+ // is the built-in, at every argument) is the law itself; the bridge law is proven by the search first, and only a
10
+ // bridge proven is used.
11
+ // - Copies: a recursive function that calls a bridged one, one unfolded, or a copied one is copied with the built-in,
12
+ // the body or the copy in its place, and its copy law (it is its copy at every argument) proven: one node made from
13
+ // the two bodies walked together (its recursive calls by the node's own induction, at its recursion's uses), or,
14
+ // where the kernel refuses that, by the search with the bridges and its callees' copy laws as lemmas.
15
+ // - The law through them: the law unfolded, its bridged calls the built-ins, its other calls the copies, proven by
16
+ // the search (lemmas and all; through the bridges and unfolded, half the time left, then through the unfolding
17
+ // alone); then one node, the law as stated, using that proof's node, each bridge and copy law at the calls of the
18
+ // law (read at their arguments), each unfolded definition's fact at its call, and the congruences between a call
19
+ // and the same call at the arguments said another way. Its goal is equalities; nothing is assumed.
20
+ // The bridges and the copies' laws are nodes like any lemma's, at levels below the law's.
21
+ import { n as k, walk } from "./machine.js";
1
22
  import { Bool, Integer, Nat, Val, argsOf, bindName, define, encX, encY, evalX, factsOf, fnNamed, programOf, rankWidth, schemesOf, searchIn } from "./data.js";
2
23
  import { proveCyclic } from "./cyclic.js";
3
24
  import { clock, pairedKeys, withDeadline } from "../kernel/prove.js";
@@ -76,19 +97,8 @@ function isBridge(y, f, op) {
76
97
  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
77
98
  && JSON.stringify(x) === JSON.stringify(op.x(c.args)));
78
99
  }
79
- const callsOf = (t) => { const out = []; walkO(t, o => { if (o.op === 'call')
100
+ const callsOf = (t) => { const out = []; walk(t, o => { if (o.op === 'call')
80
101
  out.push(o.fn); }); return out; };
81
- function walkO(t, f) {
82
- if (Array.isArray(t)) {
83
- t.forEach(x => walkO(x, f));
84
- return;
85
- }
86
- if (!t || typeof t !== 'object')
87
- return;
88
- f(t);
89
- for (const v of Object.values(t))
90
- walkO(v, f);
91
- }
92
102
  export function transferPlan(l) {
93
103
  const p = programOf([l]), bridges = new Map();
94
104
  for (const f of p.fns) {
@@ -270,7 +280,6 @@ function build(l, bridged, unfold) {
270
280
  return { p, lstar, bridges, equivs, copies, unfolded: unfold };
271
281
  }
272
282
  // --- the proof ---------------------------------------------------------------------------------------------------------
273
- const k = (value) => ({ op: 'const', value });
274
283
  const yes = { op: '<=', a: k(0), b: k(0) };
275
284
  const top = (pr) => Math.max(0, ...pr.nodes.map(n => (n.rank[0]?.op === 'const' ? n.rank[0].value : 0)));
276
285
  const verify = (fs, specs, until) => {
@@ -331,7 +340,7 @@ export function proveThrough(l, plan, opts, until) {
331
340
  // (through the bridges and unfolded: half the time left, the other half through the unfolding alone, the functions
332
341
  // as written)
333
342
  const again = b.unfolded && bridged.size > 0;
334
- const r = searchIn(b.lstar, opts, again ? clock() + (until - clock()) / 2 : until, { p: b.p, fs, base: [], level: 0 });
343
+ const r = searchIn(b.lstar, opts, again ? clock() + (until - clock()) / 2 : until, { p: b.p, fs, base: [], level: 0, merge: true });
335
344
  tried += r.verdict.tried;
336
345
  if (!r.out && again && clock() < until) {
337
346
  bridged = new Map();
@@ -1,4 +1,4 @@
1
- import type { C, E } from './machine.js';
1
+ import { type C, type E } from './machine.js';
2
2
  import { type Lin } from './solver.js';
3
3
  import { type Goal, type Path, type Subst, type Tree } from '../kernel/kernel.js';
4
4
  export type Rename = {
@@ -1,41 +1,24 @@
1
- import { add, refuteFast, scale, solve } from "./solver.js";
1
+ // A usual proof's tree made a cyclic node's. Untrusted: kernel/cyclic.ts checks the proof it ends in.
2
+ //
3
+ // An instance's node after a step (core/cyclic.ts: a machine's law after a step from t − 1, a recurrence's lemma after
4
+ // a step to x, a fold's law from a node's children) is the usual rule's step goal read over the instance's cells: each
5
+ // state variable s as s@[t − 1], each map's cell M[k] as M@[(t − 1) + k·Ω], a fresh key k# as the node's own k. Its
6
+ // goal is built so that it holds every hypothesis of that goal read so (and more: the run's bounds, the naturals), and
7
+ // the usual goal's tree is then read over it: each column of the usual goal (a variable, a cell, a term column, a
8
+ // monomial) is a linear form of the node's goal (`renamer`), each split the renamed split, each leaf's rows found again
9
+ // among the node's rows at the renamed path. A leaf whose rows aren't all there (two cells the path proves equal, whose
10
+ // keys over Ω the node's path doesn't yet compare) is grown again on the node's goal at its path (`regrown`); a split the
11
+ // node's path already decides is followed, not made again.
12
+ import { walk } from "./machine.js";
13
+ import { add, env, refuteFast, scale, solve } from "./solver.js";
2
14
  import { checkRefutation } from "./check.js";
3
15
  import { canon, canonFlip, columnTerm, factorsOf, isCell, isMonomial, leafConstraintsReusing, linear, substE, truth, withProducts } from "../kernel/kernel.js";
4
- import { cellProducts, clock, grow } from "../kernel/prove.js";
16
+ import { cellProducts, clock, grow, parseKey } from "../kernel/prove.js";
17
+ import { times } from "../kernel/reader.js";
5
18
  const omega = 'O$';
6
- const debugOn = () => !!globalThis.process?.env?.GDP_CYCLIC_DEBUG;
7
- // The kernel's product of two linear forms (kernel.ts's `times`): each monomial its factors sorted, joined by '*'.
8
- function times(a, b) {
9
- const out = [];
10
- for (const [p, cp] of Object.entries(a))
11
- for (const [q, cq] of Object.entries(b)) {
12
- if (p.includes('⟦') || q.includes('⟦'))
13
- return undefined;
14
- const fs = [...(p === '1' ? [] : factorsOf(p)), ...(q === '1' ? [] : factorsOf(q))].sort();
15
- out.push({ [fs.length ? fs.join('*') : '1']: cp * cq });
16
- }
17
- return add(...out);
18
- }
19
+ const debugOn = () => !!env.GDP_CYCLIC_DEBUG;
19
20
  // A cell's key, from its name (`M[key]`, the key's canonical text, whose names may be cells themselves).
20
- function keyOf(cell) {
21
- const text = cell.slice(cell.indexOf('[') + 1, -1), out = {};
22
- let depth = 0, start = 0;
23
- for (let i = 0; i <= text.length; i++) {
24
- const ch = text[i];
25
- if (ch === '[')
26
- depth++;
27
- else if (ch === ']')
28
- depth--;
29
- else if ((ch === ',' && depth === 0) || i === text.length) {
30
- if (i > start) {
31
- const part = text.slice(start, i), at = part.lastIndexOf(':');
32
- out[part.slice(0, at)] = Number(part.slice(at + 1));
33
- }
34
- start = i + 1;
35
- }
36
- }
37
- return out;
38
- }
21
+ const keyOf = (cell) => parseKey(cell.slice(cell.indexOf('[') + 1, -1));
39
22
  export function renamer(r) {
40
23
  const terms = new Map(), memo = new WeakMap(), cells = r.cells ?? {};
41
24
  const col = (name, wp) => {
@@ -391,19 +374,14 @@ function choiceAtom(g, wp) {
391
374
  // The cells of the conclusion refuted at the path (reads it gives no rows of yet among them).
392
375
  function conclCells(g, wp) {
393
376
  const out = [];
394
- const walk = (x) => {
395
- if (!x || typeof x !== 'object')
396
- return;
377
+ walk(g.hyps.at(-1), x => {
397
378
  const o = x;
398
379
  if (o.op === 'get' && o.map.endsWith('@')) {
399
380
  const l = linear(o, wp);
400
381
  if (l)
401
382
  out.push(...Object.keys(l));
402
383
  }
403
- for (const val of Object.values(o))
404
- walk(val);
405
- };
406
- walk(g.hyps.at(-1));
384
+ });
407
385
  return out;
408
386
  }
409
387
  // Two cells over time at keys u + a·Ω and u + b·Ω: a = b decided first, then the keys' difference, its other side
@@ -452,7 +430,7 @@ export function close(g, wp, st, until) {
452
430
  return y && n ? { split: next, yes: y, no: n } : undefined;
453
431
  }
454
432
  st.regrown++;
455
- if (globalThis.process?.env?.GDP_CYCLIC_DEBUG)
433
+ if (env.GDP_CYCLIC_DEBUG)
456
434
  console.error(`[close] ${g.name}: grown again at ${[...wp.values()].map(a => `${JSON.stringify(a.lin)} ${a.holds}`).join('; ')}`);
457
435
  return regrow(g, wp, until);
458
436
  }
@@ -487,18 +465,13 @@ export function carry(g, nFacts, nUses, st, until) {
487
465
  // The times before (t ∸ 1, x ∸ 1, y ∸ 1, each a choice until c <= v is decided), decided after the guards: then the
488
466
  // cells at t − 1 and at (t − 1) + 1 are the same reads.
489
467
  const prev = [], seenPrev = new Set();
490
- const walk = (x) => {
491
- if (!x || typeof x !== 'object')
492
- return;
468
+ walk(g.hyps, x => {
493
469
  const o = x;
494
470
  if (o.op === 'sub' && o.a.op === 'var' && o.b.op === 'const' && !seenPrev.has(`${o.a.name}-${o.b.value}`)) {
495
471
  seenPrev.add(`${o.a.name}-${o.b.value}`);
496
472
  prev.push({ op: '<=', a: o.b, b: o.a });
497
473
  }
498
- for (const val of Object.values(o))
499
- walk(val);
500
- };
501
- walk(g.hyps);
474
+ });
502
475
  const guardsIn = (c, wp, out) => {
503
476
  if (c.op === 'and') {
504
477
  for (const x of c.xs)
@@ -1,4 +1,4 @@
1
- import { type Kind, type Cond } from './dsl.js';
1
+ import { type Kind, Cond } from './dsl.js';
2
2
  import { type Chart } from './chart.js';
3
3
  type Obj = Record<string, any>;
4
4
  type XAction = string | {
@@ -47,9 +47,11 @@ export type Bridge = {
47
47
  guards?: ReadonlyMap<unknown, Guard>;
48
48
  actions?: ReadonlyMap<unknown, Action>;
49
49
  };
50
+ ignore?: string[];
50
51
  };
51
52
  export type MachineLike = object;
52
53
  export declare function fromXState(machine: MachineLike, opts?: Bridge): Chart<Obj, Obj, Obj>;
54
+ export declare function eventsOf(machine: MachineLike): string[];
53
55
  export type XActor = {
54
56
  send: (e: never) => void;
55
57
  getSnapshot: () => {
@@ -65,6 +67,9 @@ export declare function conforms(c: Chart<Obj, Obj, Obj>, machine: MachineLike,
65
67
  seed?: number;
66
68
  params?: Obj;
67
69
  payload?: (event: string, rand: (n: number) => number) => Obj;
70
+ beforeSend?: (event: string, payload: Obj) => void;
71
+ context?: string[];
72
+ event?: (type: string, payload: Obj) => Obj;
68
73
  }): {
69
74
  checked: number;
70
75
  failure?: string;