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
@@ -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,14 +59,54 @@ 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`).
65
102
  export const work = { n: 0 };
103
+ // What the searches did, by kind, beside work.n (research/query reads them: the cost of each query's parts).
104
+ export const costs = { solves: 0, solveRows: 0, fm: 0, fpivots: 0, fcells: 0, cdclNodes: 0, cdclRows: 0, scan: 0, pivots: 0, pivotRows: 0, plainNodes: 0, plainRows: 0,
105
+ values: 0, copies: 0, edges: 0, unitRows: 0, unfoldRows: 0, goalNodes: 0, translateRows: 0 };
66
106
  export function solve(constraints, maxRows = 20_000, integral = true) {
67
107
  work.n += constraints.length;
108
+ costs.solves++;
109
+ costs.solveRows += constraints.length;
68
110
  const steps = [];
69
111
  const lins = [], stricts = [];
70
112
  const push = (step, lin, strict = false) => (steps.push(step), lins.push(lin), stricts.push(strict), lins.length - 1);
@@ -189,6 +231,7 @@ export function solve(constraints, maxRows = 20_000, integral = true) {
189
231
  if (choice.pos.length * choice.neg.length > 5 * maxRows)
190
232
  return { kind: 'unknown' };
191
233
  work.n += choice.pos.length * choice.neg.length;
234
+ costs.fm += choice.pos.length * choice.neg.length;
192
235
  exact &&= choice.isExact;
193
236
  eliminated.push({ x: choice.x, rows: [...choice.pos, ...choice.neg] });
194
237
  const next = rows.filter(r => (lins[r][choice.x] ?? 0) === 0);
@@ -304,6 +347,41 @@ function prune(steps, last) {
304
347
  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
348
  });
306
349
  }
350
+ // A float simplex's steps (refuteFast's, cycles.ts's floatSolve): the row leaving where a column enters, the least ratio
351
+ // (Bland's tie-break by basis index; -1: unbounded), and its pivot, the reduced costs z with it.
352
+ export const ratioRow = (T, basis, enter, cols, eps) => {
353
+ let leave = -1, best = Infinity;
354
+ for (let r = 0; r < T.length; r++) {
355
+ const a = T[r][enter];
356
+ if (a > eps) {
357
+ const ratio = T[r][cols] / a;
358
+ if (ratio < best - eps || (Math.abs(ratio - best) <= eps && basis[r] < basis[leave])) {
359
+ best = ratio;
360
+ leave = r;
361
+ }
362
+ }
363
+ }
364
+ return [leave, best];
365
+ };
366
+ export function pivot(T, z, basis, leave, enter, cols) {
367
+ const p = T[leave], pv = p[enter];
368
+ for (let j = 0; j <= cols; j++)
369
+ p[j] /= pv;
370
+ for (let r = 0; r < T.length; r++)
371
+ if (r !== leave) {
372
+ const f = T[r][enter];
373
+ if (f !== 0) {
374
+ const row = T[r];
375
+ for (let j = 0; j <= cols; j++)
376
+ row[j] -= f * p[j];
377
+ }
378
+ }
379
+ const f = z ? z[enter] : 0;
380
+ if (f !== 0)
381
+ for (let j = 0; j <= cols; j++)
382
+ z[j] -= f * p[j];
383
+ basis[leave] = enter;
384
+ }
307
385
  // A refutation found fast, where there is one over the rationals: Farkas' lemma says rows a·x + c <= 0 (x free) have no
308
386
  // rational solution exactly when some λ >= 0 has Σ λ·a = 0 and Σ λ·c > 0. A floating-point simplex looks for such λ
309
387
  // (phase one on Σ λ·a = 0, Σ λ·c = 1), and elimination on the rows it uses alone (usually a handful) gives the
@@ -345,6 +423,8 @@ export function refuteFast(constraints, maxRows = 2_000, integral = true) {
345
423
  const eps = 1e-9;
346
424
  for (let iter = 0; iter < 50 * (R + m); iter++) {
347
425
  work.n += 1 + ((R * cols) >> 8);
426
+ costs.fpivots++;
427
+ costs.fcells += (R * cols) >> 8;
348
428
  // Bland's rule: the first column with a negative reduced cost enters (no cycling on degenerate systems).
349
429
  let enter = -1;
350
430
  for (let j = 0; j < cols; j++)
@@ -354,36 +434,10 @@ export function refuteFast(constraints, maxRows = 2_000, integral = true) {
354
434
  }
355
435
  if (enter < 0)
356
436
  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
- }
437
+ const [leave] = ratioRow(T, basis, enter, cols, eps);
368
438
  if (leave < 0)
369
439
  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;
440
+ pivot(T, z, basis, leave, enter, cols);
387
441
  }
388
442
  if (-z[cols] > 1e-7)
389
443
  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) => {
@@ -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, costs, env, refuteFast, scale, solve } from "./solver.js";
2
14
  import { checkRefutation } from "./check.js";
3
- 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";
15
+ import { canon, canonFlip, columnTerm, factorsOf, isCell, isMonomial, leafConstraints, leafConstraintsReusing, linear, substE, truth, withProducts } from "../kernel/kernel.js";
16
+ import { cellProducts, clock, grow, leafRowsOf, parseKey } from "../kernel/prove.js";
17
+ import { Reader, 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) => {
@@ -106,6 +89,45 @@ const known = (lin, wp) => {
106
89
  const b = wp.get(canonFlip(lin));
107
90
  return b ? !b.holds : undefined;
108
91
  };
92
+ const trailed = new WeakMap();
93
+ function rowsAt(g, wp) {
94
+ // (a path with an atom about a term column, a cut's, read by kernel.ts: the reader's columns aren't kept for those)
95
+ for (const a of wp.values())
96
+ for (const key in a.lin)
97
+ if (key.startsWith('⟦'))
98
+ return leafConstraintsReusing(g, wp);
99
+ let t = trailed.get(g);
100
+ if (!t) {
101
+ const stack = [], on = new Map(), stamps = [];
102
+ t = { stack, on, stamps, n: 0, reader: new Reader(g, { get: name => on.get(name), stamp: at => stamps[at], size: () => stack.length, lin: at => stack[at] }) };
103
+ trailed.set(g, t);
104
+ }
105
+ const s = t, ps = [...wp];
106
+ let k = 0;
107
+ while (k < s.stack.length && k < ps.length && s.stack[k].name === ps[k][0] && s.stack[k].holds === ps[k][1].holds)
108
+ k++;
109
+ while (s.stack.length > k) {
110
+ const name = s.stack.pop().name;
111
+ s.on.delete(name);
112
+ s.reader.touch(name);
113
+ }
114
+ for (const [name, a] of ps.slice(k)) {
115
+ s.on.set(name, { val: a.holds, at: s.stack.length });
116
+ s.stamps[s.stack.length] = ++s.n;
117
+ s.stack.push({ name, lin: a.lin, holds: a.holds });
118
+ s.reader.touch(name);
119
+ }
120
+ s.reader.begin();
121
+ const rows = s.reader.leafRows();
122
+ if (env.GDP_CDCL_VERIFY === '1') {
123
+ const kr = leafConstraints(g, wp);
124
+ if (kr.length !== rows.length || kr.some((r, j) => canon(r.lin) !== canon(rows[j].lin))) {
125
+ const j = kr.findIndex((r, j2) => canon(r.lin) !== canon(rows[j2]?.lin ?? {}));
126
+ throw new Error(`reader.ts's rows differ from kernel.ts's at a translated leaf of ${g.name}: ${kr.length} vs ${rows.length}, at ${j}: ${JSON.stringify(kr[j])} vs ${JSON.stringify(rows[j]?.lin)}; path ${JSON.stringify([...wp].map(([key, a]) => [key, a.holds]))}`);
127
+ }
128
+ }
129
+ return rows;
130
+ }
109
131
  // The node's goal grown at a path (cell products on, as every cyclic goal is), within the deadline.
110
132
  function regrow(whole, wp, until) {
111
133
  const was = cellProducts.on;
@@ -149,18 +171,29 @@ export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp
149
171
  const no = yes && translate(part, whole, tree.no, ren0, st, until, new Map(pp).set(id, { lin: tree.split, holds: false }), new Map(wp).set(wid, { lin: wl, holds: false }), swaps);
150
172
  return yes && no ? { split: wl, yes, no } : undefined;
151
173
  }
152
- const rp = leafConstraintsReusing(part, pp), rw = leafConstraintsReusing(whole, wp), at = new Map();
174
+ // (past its budget, no translation: each leaf reads the two goals' rows whole, counted, so a large tree's stops there)
175
+ if (clock() > until)
176
+ return undefined;
177
+ // (the usual leaf's rows as its search kept them, where it did: kernel/prove.ts's leafRowsOf; else read again)
178
+ const kept = !tree.products && !tree.squares ? leafRowsOf.get(tree) : undefined;
179
+ const rp = kept ? undefined : leafConstraintsReusing(part, pp), rw = rowsAt(whole, wp), at = new Map();
180
+ const np = kept ? kept.n : rp.length, linP = (i) => (kept ? kept.at.get(i).lin : rp[i].lin);
181
+ const pairP = (i) => { if (kept) {
182
+ const s = kept.at.get(i)?.src;
183
+ return Array.isArray(s) ? s : undefined;
184
+ } const s = rp[i].src; return s && 'pair' in s ? s.pair : undefined; };
185
+ costs.translateRows += (rp?.length ?? 0) + rw.length;
153
186
  rw.forEach((r, i) => { const key = canon(r.lin); if (!at.has(key))
154
187
  at.set(key, i); });
155
188
  // Two cells the usual path proves equal (a row of the leaf's from their pair) are cells over time here, at keys
156
189
  // (t − 1) + a·Ω and (t − 1) + b·Ω: the path has a = b, and the keys' difference (a − b)·Ω is split (each other side
157
190
  // refuted by (a − b)·Ω = 0, the product of a − b <= 0 or b − a <= 0 with Ω >= 0), the leaf then read again.
158
- const usedRows = [...tree.leaf.flatMap(x => (x.kind === 'input' ? [x.index] : [])), ...(tree.products ?? []).flat()].filter(i => i < rp.length);
191
+ const usedRows = [...tree.leaf.flatMap(x => (x.kind === 'input' ? [x.index] : [])), ...(tree.products ?? []).flat()].filter(i => i < np);
159
192
  for (const i of usedRows) {
160
- const src = rp[i].src;
161
- if (!src || !('pair' in src))
193
+ const pair = pairP(i);
194
+ if (!pair)
162
195
  continue;
163
- const a = ren({ [src.pair[0]]: 1 }, wp), b = ren({ [src.pair[1]]: 1 }, wp), [ca] = Object.keys(a ?? {}), [cb] = Object.keys(b ?? {});
196
+ const a = ren({ [pair[0]]: 1 }, wp), b = ren({ [pair[1]]: 1 }, wp), [ca] = Object.keys(a ?? {}), [cb] = Object.keys(b ?? {});
164
197
  if (!ca || !cb || !isCell(ca) || !isCell(cb))
165
198
  continue;
166
199
  const d = add(keyOf(ca), scale(keyOf(cb), -1)), q0 = {};
@@ -184,8 +217,8 @@ export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp
184
217
  }
185
218
  }
186
219
  st.leaves++;
187
- const map = (i) => { if (i >= rp.length)
188
- return i - rp.length + rw.length; const l = ren(rp[i].lin, wp); return l && at.get(canon(l)); };
220
+ const map = (i) => { if (i >= np)
221
+ return i - np + rw.length; const l = ren(linP(i), wp); return l && at.get(canon(l)); };
189
222
  const leaf = [], products = [], squares = (tree.squares ?? []).map(s => ren(s, wp));
190
223
  let ok = squares.every(Boolean);
191
224
  for (const s of ok ? tree.leaf : []) {
@@ -211,8 +244,8 @@ export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp
211
244
  if (ok && checkRefutation(withProducts(rw, products, squares), leaf))
212
245
  return { leaf, ...(tree.products ? { products } : {}), ...(tree.squares ? { squares: squares } : {}) };
213
246
  if (debugOn()) {
214
- const missing = tree.leaf.flatMap(s => (s.kind === 'input' && s.index < rp.length && map(s.index) === undefined ? [s.index] : []));
215
- console.error(`[leaf] ${whole.name}: ${ok ? 'rows found, refutation refused' : `${missing.length} rows missing`}${missing.slice(0, 3).map(i => `; ${JSON.stringify(rp[i].lin)} as ${JSON.stringify(ren(rp[i].lin, wp) ?? 'no form')}${rp[i].src ? ` (${JSON.stringify(rp[i].src)})` : ''}`).join('')}`);
247
+ const missing = tree.leaf.flatMap(s => (s.kind === 'input' && s.index < np && map(s.index) === undefined ? [s.index] : []));
248
+ console.error(`[leaf] ${whole.name}: ${ok ? 'rows found, refutation refused' : `${missing.length} rows missing`}${missing.slice(0, 3).map(i => `; ${JSON.stringify(linP(i))} as ${JSON.stringify(ren(linP(i), wp) ?? 'no form')}`).join('')}`);
216
249
  }
217
250
  return close(whole, wp, st, until);
218
251
  }
@@ -246,7 +279,7 @@ export function readsFirst(whole, reads, ren, inner, st, until, wp = new Map(),
246
279
  // A path where l >= 1 (two cells' keys apart by l = q·Ω) while q <= 0 is a row: refuted by q·Ω <= 0, the product of
247
280
  // that row and Ω >= 0.
248
281
  function apart(whole, wp, l, q, st, until) {
249
- const rows = leafConstraintsReusing(whole, wp), find = (x) => { const c = canon(x); return rows.findIndex(r => canon(r.lin) === c); };
282
+ const rows = rowsAt(whole, wp), find = (x) => { const c = canon(x); return rows.findIndex(r => canon(r.lin) === c); };
250
283
  const iq = find(q), io = find({ [omega]: -1 }), ia = find(add({ 1: 1 }, scale(l, -1)));
251
284
  if (iq >= 0 && io >= 0 && ia >= 0) {
252
285
  const leaf = [{ kind: 'input', index: ia }, { kind: 'input', index: rows.length }, { kind: 'combine', a: 0, b: 1, ma: 1, mb: 1 }], products = [[iq, io]];
@@ -302,7 +335,7 @@ export function decide(whole, conds, inner, st, until, wp = new Map()) {
302
335
  }
303
336
  // A leaf of `g` at the path: a hypothesis false there (its row 1 <= 0), or with `solveIt` the rows refuted by the solver.
304
337
  function leafAt(g, wp, solveIt, st) {
305
- const rows = leafConstraintsReusing(g, wp), absurd = rows.findIndex(r => Object.keys(r.lin).every(key => key === '1') && (r.lin['1'] ?? 0) > 0);
338
+ const rows = rowsAt(g, wp), absurd = rows.findIndex(r => Object.keys(r.lin).every(key => key === '1') && (r.lin['1'] ?? 0) > 0);
306
339
  if (absurd >= 0) {
307
340
  st.leaves++;
308
341
  return { leaf: [{ kind: 'input', index: absurd }] };
@@ -335,7 +368,7 @@ const open = (c, wp) => atomsOf(c, wp)?.find(l => known(l, wp) === undefined);
335
368
  // Two reads of one function at keys the path doesn't yet prove equal or apart, keys linear (keys through a choice's
336
369
  // column after the others: such a column is often one the path decides later).
337
370
  function cellAtom(g, wp) {
338
- const rows = leafConstraintsReusing(g, wp), names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
371
+ const rows = rowsAt(g, wp), names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
339
372
  let later;
340
373
  for (const [i, p] of names.entries())
341
374
  for (const q of names.slice(i + 1)) {
@@ -368,7 +401,7 @@ const choiceOf = (e, wp) => {
368
401
  return Object.keys(d).some(key => key !== '1') && known(d, wp) === undefined ? d : undefined;
369
402
  };
370
403
  function choiceAtom(g, wp) {
371
- const rows = leafConstraintsReusing(g, wp);
404
+ const rows = rowsAt(g, wp);
372
405
  for (const name of new Set(rows.flatMap(r => Object.keys(r.lin)))) {
373
406
  const e = name.startsWith('⟦') ? columnTerm(name) : undefined;
374
407
  const l = e && e.op === 'if' ? choiceOf(e, wp) : undefined;
@@ -391,25 +424,20 @@ function choiceAtom(g, wp) {
391
424
  // The cells of the conclusion refuted at the path (reads it gives no rows of yet among them).
392
425
  function conclCells(g, wp) {
393
426
  const out = [];
394
- const walk = (x) => {
395
- if (!x || typeof x !== 'object')
396
- return;
427
+ walk(g.hyps.at(-1), x => {
397
428
  const o = x;
398
429
  if (o.op === 'get' && o.map.endsWith('@')) {
399
430
  const l = linear(o, wp);
400
431
  if (l)
401
432
  out.push(...Object.keys(l));
402
433
  }
403
- for (const val of Object.values(o))
404
- walk(val);
405
- };
406
- walk(g.hyps.at(-1));
434
+ });
407
435
  return out;
408
436
  }
409
437
  // Two cells over time at keys u + a·Ω and u + b·Ω: a = b decided first, then the keys' difference, its other side
410
438
  // refuted by the product (`apart`).
411
439
  function omegaPair(g, wp) {
412
- const rows = leafConstraintsReusing(g, wp), names = [...new Set([...rows.flatMap(r => Object.keys(r.lin)), ...conclCells(g, wp)])].filter(isCell);
440
+ const rows = rowsAt(g, wp), names = [...new Set([...rows.flatMap(r => Object.keys(r.lin)), ...conclCells(g, wp)])].filter(isCell);
413
441
  for (const [i, p] of names.entries())
414
442
  for (const q of names.slice(i + 1)) {
415
443
  if (p.slice(0, p.indexOf('[')) !== q.slice(0, q.indexOf('[')))
@@ -452,7 +480,7 @@ export function close(g, wp, st, until) {
452
480
  return y && n ? { split: next, yes: y, no: n } : undefined;
453
481
  }
454
482
  st.regrown++;
455
- if (globalThis.process?.env?.GDP_CYCLIC_DEBUG)
483
+ if (env.GDP_CYCLIC_DEBUG)
456
484
  console.error(`[close] ${g.name}: grown again at ${[...wp.values()].map(a => `${JSON.stringify(a.lin)} ${a.holds}`).join('; ')}`);
457
485
  return regrow(g, wp, until);
458
486
  }
@@ -487,18 +515,13 @@ export function carry(g, nFacts, nUses, st, until) {
487
515
  // The times before (t ∸ 1, x ∸ 1, y ∸ 1, each a choice until c <= v is decided), decided after the guards: then the
488
516
  // cells at t − 1 and at (t − 1) + 1 are the same reads.
489
517
  const prev = [], seenPrev = new Set();
490
- const walk = (x) => {
491
- if (!x || typeof x !== 'object')
492
- return;
518
+ walk(g.hyps, x => {
493
519
  const o = x;
494
520
  if (o.op === 'sub' && o.a.op === 'var' && o.b.op === 'const' && !seenPrev.has(`${o.a.name}-${o.b.value}`)) {
495
521
  seenPrev.add(`${o.a.name}-${o.b.value}`);
496
522
  prev.push({ op: '<=', a: o.b, b: o.a });
497
523
  }
498
- for (const val of Object.values(o))
499
- walk(val);
500
- };
501
- walk(g.hyps);
524
+ });
502
525
  const guardsIn = (c, wp, out) => {
503
526
  if (c.op === 'and') {
504
527
  for (const x of c.xs)
@@ -572,7 +595,7 @@ export function carry(g, nFacts, nUses, st, until) {
572
595
  const y = side(yes), n = y && side(no);
573
596
  return y && n ? { split: next, yes: y, no: n } : undefined;
574
597
  };
575
- const quick = (wp) => { const rows = leafConstraintsReusing(g, wp), v = refuteFast(rows); if (v?.kind !== 'refuted')
598
+ const quick = (wp) => { const rows = rowsAt(g, wp), v = refuteFast(rows); if (v?.kind !== 'refuted')
576
599
  return undefined; st.leaves++; return { leaf: v.steps }; };
577
600
  return node(new Map(), false);
578
601
  }
@@ -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;