gdp-wired 0.25.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 (50) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +1 -1
  3. package/dist/core/accel.js +336 -101
  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 +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  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.js +72 -18
  28. package/dist/core/machine.d.ts +6 -0
  29. package/dist/core/machine.js +35 -3
  30. package/dist/core/nonterm.d.ts +5 -1
  31. package/dist/core/nonterm.js +109 -41
  32. package/dist/core/q.d.ts +1 -0
  33. package/dist/core/q.js +2 -2
  34. package/dist/core/relation.d.ts +1 -0
  35. package/dist/core/relation.js +20 -36
  36. package/dist/core/solver.d.ts +12 -0
  37. package/dist/core/solver.js +76 -30
  38. package/dist/core/transfer.js +22 -13
  39. package/dist/core/translate.d.ts +1 -1
  40. package/dist/core/translate.js +22 -49
  41. package/dist/core/xstate.d.ts +6 -1
  42. package/dist/core/xstate.js +336 -55
  43. package/dist/kernel/cdcl.js +1 -2
  44. package/dist/kernel/prove.d.ts +6 -1
  45. package/dist/kernel/prove.js +96 -82
  46. package/dist/kernel/reader.d.ts +1 -0
  47. package/dist/kernel/reader.js +4 -3
  48. package/dist/kernel/simplex.d.ts +1 -1
  49. package/dist/kernel/simplex.js +13 -1
  50. package/package.json +3 -2
package/README.md CHANGED
@@ -63,21 +63,26 @@ All of these are proven automatically, and each proof is also a Lean theorem:
63
63
  - **Statecharts**: `chart(name).states({...}).on(event, {from, to, when, set})`, with states nested to any depth,
64
64
  parallel regions (at the top of the chart), a compound's history (deep), guards and extended state, compiled to a rule;
65
65
  `check()` shows every state reached by a run (or proves it unreachable), no state stuck and no event ambiguous, and its
66
- laws prove like any rule's (`examples/charts.ts`). Not yet: parallel regions inside a state, entry and exit actions,
67
- eventless and delayed transitions.
66
+ laws prove like any rule's (`examples/charts.ts`). Not yet: parallel regions inside a state (XState's entry and exit
67
+ actions, eventless and delayed transitions are read by `fromXState`, below).
68
68
  - **XState machines** (`gdp-wired/xstate`): `fromXState(machine, {guards, actions})` builds the chart an XState v5
69
69
  machine runs as, with each guard and action it names given again in gdp-wired's terms, and `conforms(chart, machine,
70
70
  createActor)` drives XState's own actor and the compiled rule with the same random events, comparing every state and
71
71
  context; what a chart can't run the same way, and any key it doesn't read, is refused when built, with the reason
72
- (`examples/xstate.ts`). A v4 machine's `cond` is read as its guard.
72
+ (`examples/xstate.ts`). A v4 machine's `cond` is read as its guard. An invoked actor's done and error and a timer
73
+ firing are events from outside, taken only where they can come (each once a visit; one timer at a time), and
74
+ eventless transitions and entry and exit actions that write the context are read into each transition as XState's
75
+ macrostep.
73
76
  - **Rules read from the code** (`gdp-wired/extract`): `extract(code, {entry})` reads a reducer, `useReducer`'s, functions
74
- over one record, or a class whose methods write its fields, and returns the rule that steps the same way, as a builder
75
- value and as source to keep (`toSource`); `extractXState` reads an XState machine's guards and actions, named or
77
+ over one record, a class whose methods write its fields (with the classes it extends), or the object of functions a
78
+ factory returns, and returns the rule that steps the same way, as a builder value and as source to keep
79
+ (`toSource`); `extractXState` reads an XState machine, or a function that makes one, its guards and actions named or
76
80
  inline, for `fromXState`. The extractor is untrusted: each rule is run beside the code it was read from (requests
77
- from the start, steps from drawn states and from the prover's counterexamples, every state, cell, result and refusal
78
- compared, the code's branches counted), and a difference refuses it. Its subset (integers, booleans, string-literal
79
- unions, records, Map and Record keyed state, branches and early returns, throws as refusals, `Date.now()` as an
80
- input) and what it refuses, each with the place and the reason, are in `core/extract.ts`.
81
+ from the start, steps from drawn states and from the prover's counterexamples, every state, cell, list, result and
82
+ refusal compared, the code's branches counted), and a difference refuses it. Its subset (integers, booleans, strings
83
+ and string-literal unions, values that may be null, records, Map and Record keyed state, arrays as lists, Dates as
84
+ their time, branches and early returns, throws as refusals, `Date.now()` as an input) and what it refuses, each with
85
+ the place and the reason, are in `core/extract.ts`.
81
86
  - **What nobody stated, looked for when the prover alone stops**: where `proveRule` or `proveSteps` doesn't prove the laws
82
87
  and no run breaks them, it looks for lemmas about the rule's recurrences and lists (`discover`), lemmas about the
83
88
  functions it knows by their facts (`cycleLemmas`, each proven by a cyclic proof) and then invariants (`inferLaws`),
@@ -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 { Loop } from '../kernel/kernel.js';
3
3
  import { type Lin } from './solver.js';
4
4
  export type Target = {
@@ -1,26 +1,35 @@
1
+ // Accelerated cycles: recurrent sets from a loop's relation, not its runs, and stems into them from runs whose loops are
2
+ // taken n times at once. Untrusted, like core/nonterm.ts, whose search calls this: what is found here is a candidate
3
+ // set, its witness and a stem, and the kernel proves the set closed and the stem into it (kernel.ts's checkRecur,
4
+ // NonTerm.lean's never_ends_of).
5
+ //
6
+ // - Cycles. The relation's paths (core/relation.ts: one turn as linear paths, each from a location to a location) as a
7
+ // graph; its closed walks (a location may come twice: x > 0 and x < 0 taken in turn), each by its least rotation, by
8
+ // how many choices they make among a location's paths (at most `maxLen`; a chain of locations with one path out, as a
9
+ // translated program's straight-line code, costs nothing) and at most 64 turns, a walk cut where its rows (each turn's
10
+ // inputs left open) are refuted; a self-loop also twice over (a period of two: x := −x). Then the cycles the random
11
+ // runs take, between two visits of a location, the commonest first.
12
+ // - A turn's inputs as terms of the state before it: a value a row pins (an equation in it), else a bound a row puts on
13
+ // it (x < i0 gives i0 := x + 1, i0 >= 3 gives 3), else 0; or constants from a model of two rounds of the cycle. The
14
+ // cycle is then one linear loop: its guard G (each turn's rows, read at the state the turns before it leave) and its
15
+ // update U (affine in the state at the cycle's start).
16
+ // - Its n-fold run in closed form: an atom g ≤ 0 of G holds after every number n of turns where its value along the
17
+ // run, g(Uⁿx), a polynomial in n for a translation or a triangular update (the differences core/discover.ts's
18
+ // closedForm fits), has its differences at n = 0 all ≤ 0: Δ⁰g = g, Δ^{k+1}g = Δ^k g∘U − Δ^k g, each linear in x
19
+ // (Σ C(n, k)·Δ^k g is g(Uⁿx)). For a geometric update (x := 2x) the differences repeat (Δ²g = Δ¹g) and the same set
20
+ // holds. So the set R is G with each atom's differences up to degree 3, and Houdini drops a difference that isn't kept
21
+ // by U (G's atoms are kept or the cycle is given up): R ∧ ¬a(Ux) refuted for each atom a, by the integer solver
22
+ // (core/solver.ts). A constant difference above 0 gives the cycle up at once: g grows past 0.
23
+ // - The set of the loop: per turn j of the cycle, at its location, the states from which the rest of the cycle's turns
24
+ // are allowed and end in R (R_j, the weakest precondition: the rest composed); the witness by location, or by R_j
25
+ // where the cycle passes a location twice, its commonest value with no condition.
26
+ // - Stems (`stemsTo`): from the start's location to a part's, a path at a time or a self-loop that is a translation
27
+ // taken n times at once, all linear, then run on the loop itself.
28
+ import { n as K, x as V } from "./machine.js";
1
29
  import { relationOf } from "./relation.js";
2
- import { solve } from "./solver.js";
3
- const K = (value) => ({ op: 'const', value }), V = (name) => ({ op: 'var', name });
4
- const vars = (l) => Object.keys(l).filter(x => x !== '1');
5
- const plus = (a, b, f = 1) => { const o = { ...a }; for (const x in b) {
6
- o[x] = (o[x] ?? 0) + f * b[x];
7
- if (!o[x])
8
- delete o[x];
9
- } return o; };
10
- const times = (a, f) => { const o = {}; if (f)
11
- for (const x in a)
12
- o[x] = a[x] * f; return o; };
13
- const konst = (c) => (c ? { 1: c } : {});
14
- const subst = (l, m) => {
15
- let o = konst(l['1'] ?? 0);
16
- for (const x of vars(l))
17
- o = plus(o, m[x] ?? { [x]: 1 }, l[x]);
18
- return o;
19
- };
20
- const canon = (l) => JSON.stringify(Object.keys(l).sort().map(x => [x, l[x]]));
30
+ import { canon, gcd, konst, linOfE, plus, solve, subst, times, vars } from "./solver.js";
21
31
  const isConst = (l) => vars(l).length === 0;
22
32
  // (a row's coefficients divided by their common divisor, its constant rounded up: an integer row as tight as it goes)
23
- const gcd = (a, b) => (b === 0 ? Math.abs(a) : gcd(b, a % b));
24
33
  const tight = (l) => {
25
34
  const g = vars(l).reduce((s, x) => gcd(s, l[x]), 0);
26
35
  if (g <= 1)
@@ -52,6 +61,8 @@ export function* accelerated(l, opts) {
52
61
  // (its least rotation), with at most `maxLen` choices among a location's paths (a chain of locations with one path out,
53
62
  // as a translated program's straight-line code, is free) and at most 64 turns; the shortest first.
54
63
  let cycles = [];
64
+ // (those with an inner loop apart, at most 60, after the rest)
65
+ const inners = [];
55
66
  const byFrom = new Map();
56
67
  rel.paths.forEach((_, i) => { const f = from(i); byFrom.set(f, [...(byFrom.get(f) ?? []), i]); });
57
68
  const cap = opts.maxCycles ?? 400;
@@ -79,13 +90,25 @@ export function* accelerated(l, opts) {
79
90
  return d;
80
91
  };
81
92
  const backs = new Map();
82
- // (each walk's turns composed with their inputs left open, u@k: a walk whose rows are refuted is cut where it chose)
83
- const open = (sigma, i, k) => {
84
- const p = rel.paths[i], insAt = Object.fromEntries(Object.entries(symbolic(p, k, Sset, P)).map(([u, t]) => [u, subst(t, sigma)]));
85
- const sub = { ...sigma, ...insAt };
86
- const rs = [...p.rows.map(f => subst(f, sub)), ...natState.map(x => times(sigma[x], -1)), ...Object.keys(insAt).filter(u => !rel.ints.has(u)).map(u => times(insAt[u], -1))];
87
- return { rs, post: Object.fromEntries(S.map(x => [x, subst(p.post[x] ?? { [x]: 1 }, sub)])) };
93
+ // (a self-loop that counts a value by ±1 towards a bound its rows put on it)
94
+ const counters = new Map();
95
+ const counter = (j) => {
96
+ if (counters.has(j))
97
+ return counters.get(j);
98
+ const p = rel.paths[j], bounds = boundsOf(p.rows);
99
+ let out;
100
+ for (const x of S) {
101
+ const e = p.post[x], delta = e?.['1'] ?? 0, b = bounds.get(x);
102
+ if (!e || vars(e).length !== 1 || e[x] !== 1 || Math.abs(delta) !== 1 || (delta > 0 ? b?.hi : b?.lo) === undefined)
103
+ continue;
104
+ out = { x, delta, ...(b.lo !== undefined ? { lo: b.lo } : {}), ...(b.hi !== undefined ? { hi: b.hi } : {}) };
105
+ break;
106
+ }
107
+ counters.set(j, out);
108
+ return out;
88
109
  };
110
+ // (each walk's turns composed with their inputs left open, u@k: a walk whose rows are refuted is cut where it chose)
111
+ const open = (sigma, i, k) => turn(rel, natState, i, sigma, symbolic(rel.paths[i], k, Sset, P), k);
89
112
  const id0 = Object.fromEntries(S.map(x => [x, { [x]: 1 }]));
90
113
  let nodes = 20_000;
91
114
  for (let budget = 0; budget <= maxLen && cycles.length < cap && nodes > 0; budget++) {
@@ -94,23 +117,46 @@ export function* accelerated(l, opts) {
94
117
  if (!backs.has(s0))
95
118
  backs.set(s0, back(s0));
96
119
  const d = backs.get(s0);
97
- const walk = (seq, at, cost, sigma, rows) => {
120
+ // (`inner`: the self-loop just taken as many times as its rows allow, not taken again at once)
121
+ const walk = (seq, at, cost, sigma, rows, inner) => {
98
122
  if (--nodes < 0 || cycles.length >= cap || now() > until)
99
123
  return;
100
- if (at === s0 && cost === budget && least(seq) && sat(rows))
101
- cycles.push(seq);
124
+ if (at === s0 && cost === budget && least(seq) && sat(rows)) {
125
+ if (!seq.some((x, q) => q > 0 && x === seq[q - 1] && to(x) === from(x)))
126
+ cycles.push(seq);
127
+ else if (inners.length < 60)
128
+ inners.push(seq);
129
+ }
102
130
  if (seq.length >= 64)
103
131
  return;
104
132
  const c = cost + costAt(at);
105
133
  if (c + (d.get(at) ?? Infinity) - costAt(at) > budget || c > budget)
106
134
  return;
107
135
  for (const j of byFrom.get(at) ?? []) {
108
- if (j < seq[0] || c + (d.get(to(j)) ?? Infinity) > budget)
136
+ if (j === inner || j < seq[0] || c + (d.get(to(j)) ?? Infinity) > budget)
109
137
  continue;
110
138
  const { rs, post } = open(sigma, j, seq.length), all = [...rows, ...rs];
111
139
  if (all.some(big) || (costAt(at) && !sat(all)))
112
140
  continue;
113
141
  walk([...seq, j], to(j), c, post, all);
142
+ // An inner loop: a self-loop that counts x by ±1 up or down to a bound of its rows, from a value the walk has
143
+ // set (x := 0, then x := x + 1 while x < 12: KnapsackDP's), taken as many times as that, as one choice, where
144
+ // that is 2 to 24 times; the walk goes on from there.
145
+ const cl = to(j) === at && j !== seq.at(-1) && inners.length < 60 ? counter(j) : undefined, k0 = cl && sigma[cl.x];
146
+ if (cl && k0 && isConst(k0)) {
147
+ const k = k0['1'] ?? 0, r = cl.delta > 0 ? (cl.hi ?? -Infinity) - k + 1 : k - (cl.lo ?? Infinity) + 1;
148
+ if (r >= 2 && r <= 24 && seq.length + r < 64) {
149
+ let sg = sigma, rws = rows;
150
+ for (let q = 0; q < r; q++) {
151
+ const more = open(sg, j, seq.length + q);
152
+ sg = more.post;
153
+ rws = [...rws, ...more.rs];
154
+ }
155
+ nodes--;
156
+ if (!rws.some(big) && sat(rws))
157
+ walk([...seq, ...Array.from({ length: r }, () => j)], at, c, sg, rws, j);
158
+ }
159
+ }
114
160
  }
115
161
  };
116
162
  const c0 = costAt(s0), first = open(id0, i, 0);
@@ -119,6 +165,7 @@ export function* accelerated(l, opts) {
119
165
  }
120
166
  }
121
167
  cycles = cycles.sort((x, y) => x.length - y.length).slice(0, cap);
168
+ cycles = [...cycles.filter(c => c.length <= 6), ...inners.sort((x, y) => x.length - y.length), ...cycles.filter(c => c.length > 6)];
122
169
  // the runs' cycles: between two visits of a location, the paths taken (as their least rotation), by how often; after
123
170
  // the enumerated ones of at most 4 turns (at most 20,000 turns read)
124
171
  if (opts.runs && opts.io) {
@@ -163,8 +210,13 @@ export function* accelerated(l, opts) {
163
210
  cycles = [...short, ...fromRuns.filter(c => !shortKeys.has(c.join(','))), ...cycles.filter(c => c.length > 4 && !keys.has(c.join(',')))];
164
211
  }
165
212
  const tried = new Set();
166
- for (const cyc of cycles) {
167
- for (const reps of cyc.length === 1 ? [1, 2] : [1]) {
213
+ for (const cyc0 of cycles) {
214
+ // (a cycle with a product: its turn first, where its product is read at the cycle's start; one such turn at most)
215
+ const prodAt = cyc0.flatMap((pi, j) => (readsPi(rel.paths[pi]) ? [j] : []));
216
+ if (prodAt.length > 1)
217
+ continue;
218
+ const cyc = prodAt.length ? [...cyc0.slice(prodAt[0]), ...cyc0.slice(0, prodAt[0])] : cyc0;
219
+ for (const reps of cyc.length === 1 && !prodAt.length ? [1, 2] : [1]) {
168
220
  const seq = Array.from({ length: reps }, () => cyc).flat();
169
221
  // the choices of inputs: constants from a model of two rounds of the cycle (the constants the same in each), then
170
222
  // each path's first choice of terms, then one path at a time its others
@@ -196,7 +248,8 @@ export function* accelerated(l, opts) {
196
248
  // The path a turn takes: its pins (the location, the rule) and its rows hold at the state and the turn's inputs.
197
249
  function pathAt(rel, among, st, input) {
198
250
  const at = { ...st, ...input };
199
- const value = (x) => { const pair = rel.ints.get(x); return pair ? (at[pair[0]] ?? 0) - (at[pair[1]] ?? 0) : (at[x] ?? 0); };
251
+ const value = (x) => { if (isPi(x))
252
+ return piValue(rel, x, at); const pair = rel.ints.get(x); return pair ? (at[pair[0]] ?? 0) - (at[pair[1]] ?? 0) : (at[x] ?? 0); };
200
253
  for (const i of among) {
201
254
  const p = rel.paths[i];
202
255
  if (Object.entries(p.pins).some(([n, v]) => !n.endsWith('′') && n in at && at[n] !== v))
@@ -210,21 +263,171 @@ const rels = new WeakMap();
210
263
  function relOf(l) {
211
264
  if (rels.has(l))
212
265
  return rels.get(l);
213
- // (a path that reads a product, which the relation stands for by a natural of its own, is left out: the search keeps
214
- // to the linear paths, and the kernel checks what it finds against the loop itself)
266
+ // (a path that reads a product, which the relation stands for by a natural of its own, is kept where each product is
267
+ // of two values of the state or params, x := x·y: a cycle may take it as its first turn, the product read at the
268
+ // cycle's start (`piFacts`); a product of a turn's input is left out. The kernel checks what is found against the loop
269
+ // itself.)
215
270
  let r = relationOf(l);
216
271
  if (r && !r.exact) {
217
- const lin = (p) => ![...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].some(x => x.startsWith('π('));
218
- const keep = r.paths.map(lin);
219
- r = { ...r, paths: r.paths.filter((_, i) => keep[i]), from: r.from.filter((_, i) => keep[i]), to: r.to.filter((_, i) => keep[i]), nats: r.nats.filter(x => !x.startsWith('π(')), exact: true };
272
+ const known = new Set([...l.params, ...Object.keys(l.state)]);
273
+ const ok = (x) => !isPi(x) || piParts(x)?.every(f => vars(f).every(n => known.has(n))) === true;
274
+ const keep = r.paths.map(p => [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].every(ok));
275
+ r = { ...r, paths: r.paths.filter((_, i) => keep[i]), from: r.from.filter((_, i) => keep[i]), to: r.to.filter((_, i) => keep[i]) };
220
276
  }
221
277
  const out = r && r.paths.length ? r : undefined;
222
278
  rels.set(l, out);
223
279
  return out;
224
280
  }
281
+ // --- products ---------------------------------------------------------------------------------------------------------
282
+ //
283
+ // A product the relation names π(a·b) (core/relation.ts: two of the loop's naturals, each one value or a part of an
284
+ // integer's pair) is, where the set decides the sign of each integer it reads, ±X·Y over the relation's integers, or 0
285
+ // (a pair's other part). Its facts are those of X·Y from the set's bounds on X and Y (McCormick's: (X − l)(Y − m) ≥ 0
286
+ // for lower bounds l, m, and likewise for the upper ones; a square's tangents (X − c)² ≥ 0), linear in the product's
287
+ // name: what a Houdini check of the set needs to keep x := x·y.
288
+ const isPi = (x) => x.startsWith('π(');
289
+ // (the two factors, linear in the loop's names)
290
+ const piParts = (x) => {
291
+ const m = /^π\((.*)·(.*)\)(#\d+)?$/.exec(x);
292
+ if (!m)
293
+ return undefined;
294
+ try {
295
+ return [JSON.parse(m[1]), JSON.parse(m[2])];
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ };
301
+ const piSeen = new WeakMap();
302
+ const readsPi = (p) => { let out = piSeen.get(p); if (out === undefined)
303
+ piSeen.set(p, (out = [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].some(isPi))); return out; };
304
+ // (a turn's products named for the turn: values of their own, as the search over several turns reads them)
305
+ const fresh = (l, k) => { if (!vars(l).some(isPi))
306
+ return l; const o = {}; for (const x in l)
307
+ o[isPi(x) ? `${x}#${k}` : x] = l[x]; return o; };
308
+ const freshPath = (p, k) => (readsPi(p) ? { ...p, rows: p.rows.map(f => fresh(f, k)), post: Object.fromEntries(Object.entries(p.post).map(([x, f]) => [x, fresh(f, k)])) } : p);
309
+ // A product's value in a run (its factors' raw values multiplied).
310
+ const piValue = (rel, x, at) => {
311
+ const ev = (f) => vars(f).reduce((acc, n) => acc + f[n] * (at[n] ?? 0), f['1'] ?? 0);
312
+ const raw = (n) => { const fs = piParts(n); return fs ? ev(fs[0]) * ev(fs[1]) : at[n] ?? 0; };
313
+ const pair = rel.ints.get(x);
314
+ return pair ? raw(pair[0]) - raw(pair[1]) : raw(x);
315
+ };
316
+ // The bounds the rows put on one integer each.
317
+ function boundsOf(R) {
318
+ const out = new Map();
319
+ for (const f of R) {
320
+ const xs = vars(f);
321
+ if (xs.length !== 1)
322
+ continue;
323
+ const x = xs[0], a = f[x], b = f['1'] ?? 0, e = out.get(x) ?? {};
324
+ if (a > 0)
325
+ e.hi = Math.min(e.hi ?? Infinity, Math.floor(-b / a));
326
+ else
327
+ e.lo = Math.max(e.lo ?? -Infinity, Math.ceil(-b / a));
328
+ out.set(x, e);
329
+ }
330
+ return out;
331
+ }
332
+ // The facts of the products among `names`, given the set's rows R.
333
+ function piFacts(rel, R, names) {
334
+ const pis = [...new Set(names.filter(isPi))];
335
+ if (!pis.length)
336
+ return [];
337
+ const bounds = boundsOf(R), sign = (X) => { const b = bounds.get(X); return b?.lo !== undefined && b.lo >= 0 ? 1 : b?.hi !== undefined && b.hi <= 0 ? -1 : 0; };
338
+ const partOf = new Map();
339
+ for (const [X, [p, n]] of rel.ints) {
340
+ partOf.set(p, [X, 1]);
341
+ partOf.set(n, [X, -1]);
342
+ }
343
+ // a raw factor over the relation's names (a part of an integer's pair ±X, or 0, where the bounds decide its sign), at
344
+ // most one name in it
345
+ const factor = (f) => {
346
+ let o = konst(f['1'] ?? 0);
347
+ for (const r of vars(f)) {
348
+ const q = partOf.get(r);
349
+ if (!q) {
350
+ o = plus(o, { [r]: f[r] });
351
+ continue;
352
+ }
353
+ const s = sign(q[0]);
354
+ if (!s)
355
+ return undefined;
356
+ if (s === q[1])
357
+ o = plus(o, { [q[0]]: f[r] * q[1] });
358
+ }
359
+ return vars(o).length <= 1 ? o : undefined;
360
+ };
361
+ const out = [];
362
+ for (const N of pis) {
363
+ const pair = rel.ints.get(N), terms = pair ? [[pair[0], 1], [pair[1], -1]] : [[N, 1]];
364
+ // N = lin + Σ c·X·Y, by product
365
+ const prods = new Map();
366
+ let lin = {}, ok = true;
367
+ for (const [raw, c0] of terms) {
368
+ const fs = piParts(raw), a = fs && factor(fs[0]), b = fs && factor(fs[1]);
369
+ if (!a || !b) {
370
+ ok = false;
371
+ break;
372
+ }
373
+ const ka = a['1'] ?? 0, kb = b['1'] ?? 0, xa = vars(a)[0], xb = vars(b)[0];
374
+ lin = plus(lin, konst(c0 * ka * kb));
375
+ if (xb)
376
+ lin = plus(lin, { [xb]: c0 * ka * b[xb] });
377
+ if (xa)
378
+ lin = plus(lin, { [xa]: c0 * kb * a[xa] });
379
+ if (xa && xb) {
380
+ const [X, Y] = [xa, xb].sort(), key = `${X}*${Y}`, e = prods.get(key) ?? { X, Y, c: 0 };
381
+ e.c += c0 * a[xa] * b[xb];
382
+ prods.set(key, e);
383
+ }
384
+ }
385
+ const live = [...prods.values()].filter(e => e.c);
386
+ if (!ok || live.length > 1)
387
+ continue;
388
+ if (!live.length) {
389
+ out.push(plus({ [N]: 1 }, lin, -1), plus(lin, { [N]: 1 }, -1));
390
+ continue;
391
+ }
392
+ const { X, Y, c } = live[0];
393
+ if (Math.abs(c) !== 1)
394
+ continue;
395
+ // rows over p = X·Y, then p := c·N
396
+ const rows = [], bx = bounds.get(X) ?? {}, by = bounds.get(Y) ?? {};
397
+ const lower = (u, v) => rows.push({ [X]: v, [Y]: u, 1: -u * v, p: -1 }); // p ≥ v·X + u·Y − u·v: (X − u)(Y − v) ≥ 0
398
+ const upper = (u, v) => rows.push({ [X]: -v, [Y]: -u, 1: u * v, p: 1 }); // p ≤ v·X + u·Y − u·v: (X − u)(v − Y) ≥ 0 read with u a lower, v an upper bound
399
+ if (X === Y) {
400
+ rows.push({ p: -1 });
401
+ for (const b of [bx.lo, bx.hi])
402
+ if (b !== undefined && Number.isFinite(b))
403
+ rows.push({ [X]: 2 * b, 1: -b * b, p: -1 });
404
+ }
405
+ else {
406
+ if (bx.lo !== undefined && by.lo !== undefined)
407
+ lower(bx.lo, by.lo);
408
+ if (bx.hi !== undefined && by.hi !== undefined)
409
+ lower(bx.hi, by.hi);
410
+ if (bx.lo !== undefined && by.hi !== undefined)
411
+ upper(bx.lo, by.hi);
412
+ if (bx.hi !== undefined && by.lo !== undefined)
413
+ rows.push({ [X]: -by.lo, [Y]: -bx.hi, 1: bx.hi * by.lo, p: 1 });
414
+ }
415
+ // (p = c·(N − lin))
416
+ for (const f of rows) {
417
+ const rest = {};
418
+ for (const x in f)
419
+ if (x !== 'p')
420
+ rest[x] = f[x];
421
+ const o = plus(rest, plus({ [N]: 1 }, lin, -1), f.p * c);
422
+ if (!Object.values(o).some(v => !Number.isFinite(v)))
423
+ out.push(o);
424
+ }
425
+ }
426
+ return out;
427
+ }
225
428
  function inputsOf(p, S, P) {
226
429
  const read = [...new Set([...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)])];
227
- return read.filter(x => !S.has(x) && !P.has(x)).sort();
430
+ return read.filter(x => !S.has(x) && !P.has(x) && !isPi(x)).sort();
228
431
  }
229
432
  // The terms a path's rows suggest for u: an equation (rows f and −f, u's coefficient ±1) over known names, else the
230
433
  // bounds a row puts on u (a constant rounded inward, or a term where u's coefficient is ±1).
@@ -291,26 +494,23 @@ function symbolic(p, j, S, P) {
291
494
  }
292
495
  return ins;
293
496
  }
497
+ // A turn of path i from the state sigma (each state name's form), its inputs' forms over the turn's start: its rows (a
498
+ // natural's term a natural), and the state after; with `k`, the turn's products named for the turn k (`freshPath`).
499
+ function turn(rel, natState, i, sigma, ins, k) {
500
+ const p = k === undefined ? rel.paths[i] : freshPath(rel.paths[i], k), insAt = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, sigma)])), sub = { ...sigma, ...insAt };
501
+ return { rs: [...p.rows.map(f => subst(f, sub)), ...natState.map(x => times(sigma[x], -1)), ...Object.keys(insAt).filter(u => !rel.ints.has(u)).map(u => times(insAt[u], -1))],
502
+ post: Object.fromEntries(rel.state.map(x => [x, subst(p.post[x] ?? { [x]: 1 }, sub)])) };
503
+ }
294
504
  // Turns j.. of the cycle composed from a state x (identity at j): the rows over x, and the state after them over x.
295
505
  function compose(rel, steps, natState) {
296
506
  let sigma = Object.fromEntries(rel.state.map(x => [x, { [x]: 1 }]));
297
507
  const rows = [];
298
- for (const s of steps) {
299
- const p = rel.paths[s.path];
300
- const insAt = Object.fromEntries(Object.entries(s.ins).map(([u, t]) => [u, subst(t, sigma)]));
301
- const sub = { ...sigma, ...insAt };
302
- for (const f of p.rows)
303
- rows.push(subst(f, sub));
304
- for (const x of natState)
305
- rows.push(times(sigma[x], -1));
306
- // (a natural input's term is a natural)
307
- for (const u in insAt)
308
- if (!rel.ints.has(u))
309
- rows.push(times(insAt[u], -1));
310
- const next = {};
311
- for (const x of rel.state)
312
- next[x] = subst(p.post[x] ?? { [x]: 1 }, sub);
313
- sigma = next;
508
+ for (const [j, s] of steps.entries()) {
509
+ if (j > 0 && readsPi(rel.paths[s.path]))
510
+ return undefined;
511
+ const t = turn(rel, natState, s.path, sigma, s.ins);
512
+ rows.push(...t.rs);
513
+ sigma = t.post;
314
514
  if (Object.values(sigma).some(big) || rows.some(big))
315
515
  return undefined;
316
516
  }
@@ -324,14 +524,16 @@ function candidate(rel, seq, ins, natState, from, l, late) {
324
524
  if (!whole)
325
525
  return undefined;
326
526
  const G = whole.rows, U = whole.post;
327
- if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || !sat(G))
527
+ if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || G.some(f => vars(f).some(isPi)) || !sat(G))
328
528
  return undefined;
329
- // the differences of each atom of G along U, up to degree 3
529
+ // the differences of each atom of G along U, up to degree 3 (none past a product: it is read at the cycle's start)
330
530
  const opt = [];
331
531
  for (const g of G) {
332
532
  let d = g;
333
533
  for (let k = 1; k <= 3; k++) {
334
534
  const next = plus(subst(d, U), d, -1);
535
+ if (vars(next).some(isPi))
536
+ break;
335
537
  if (isConst(next)) {
336
538
  if ((next['1'] ?? 0) > 0)
337
539
  return undefined;
@@ -343,13 +545,35 @@ function candidate(rel, seq, ins, natState, from, l, late) {
343
545
  d = next;
344
546
  }
345
547
  }
548
+ // A product in U (x := x·y): an atom is kept where R and the product's facts imply it after U; and bounds on each
549
+ // factor, x ≥ c for c up to 32 (x ≤ −c where G puts x below 0), which the product's facts read, are among the atoms
550
+ // Houdini tries (complInterv's x ≥ 4 for y := (x + 1)² > 9), the weakest that does kept.
551
+ const piU = [...new Set(Object.values(U).flatMap(vars).filter(isPi))];
552
+ const keeps = (rs, a) => { const after = subst(a, U); return implied(piU.length ? [...rs, ...piFacts(rel, rs, vars(after))] : rs, after); };
553
+ const pool = [];
554
+ if (piU.length) {
555
+ const partOf = new Map();
556
+ for (const [X, [p, n]] of rel.ints) {
557
+ partOf.set(p, X);
558
+ partOf.set(n, X);
559
+ }
560
+ const xs = [...new Set(piU.flatMap(n => { const pair = rel.ints.get(n); return (pair ? [pair[0], pair[1]] : [n]).flatMap(r => (piParts(r) ?? []).flatMap(vars)); }).map(r => partOf.get(r) ?? r))];
561
+ for (const x of xs) {
562
+ const dir = implied(G, { [x]: -1 }) ? 1 : implied(G, { [x]: 1 }) ? -1 : 1;
563
+ for (const c of [0, 1, 2, 3, 4, 8, 16, 32]) {
564
+ const b = { [x]: -dir, ...konst(c) };
565
+ if (sat([...G, b]))
566
+ pool.push(b);
567
+ }
568
+ }
569
+ }
346
570
  // Houdini: G must be kept by U; a difference not kept is dropped
347
- let R = dedupe([...G, ...opt]);
571
+ let R = dedupe([...G, ...opt, ...pool]);
348
572
  const must = new Set(G.map(canon));
349
573
  for (let round = 0; round < 12; round++) {
350
574
  if (late())
351
575
  return undefined;
352
- const bad = R.filter(a => !implied(R, subst(a, U)));
576
+ const bad = R.filter(a => !keeps(R, a));
353
577
  if (!bad.length)
354
578
  break;
355
579
  if (bad.some(a => must.has(canon(a))))
@@ -357,8 +581,16 @@ function candidate(rel, seq, ins, natState, from, l, late) {
357
581
  const drop = new Set(bad.map(canon));
358
582
  R = R.filter(a => !drop.has(canon(a)));
359
583
  }
360
- if (R.some(a => !implied(R, subst(a, U))) || !sat(R))
584
+ if (R.some(a => !keeps(R, a)) || !sat(R))
361
585
  return undefined;
586
+ // (the factors' bounds the set keeps: each left out, the strongest first, where the rest is kept without it)
587
+ for (const b of [...pool].reverse()) {
588
+ if (late())
589
+ return undefined;
590
+ const key = canon(b), rest = R.filter(a => canon(a) !== key);
591
+ if (rest.length < R.length && !must.has(key) && rest.every(a => keeps(rest, a)))
592
+ R = rest;
593
+ }
362
594
  // R without what the rest of it implies (a smaller goal for the kernel)
363
595
  R = irredundant(R, late);
364
596
  if (late())
@@ -400,10 +632,40 @@ function candidate(rel, seq, ins, natState, from, l, late) {
400
632
  const conj = (xs) => (xs.length === 1 ? xs[0] : { op: 'and', xs });
401
633
  const pcIs = (j) => (rel.loc ? [{ op: '=', a: V(rel.loc), b: K(from(seq[j])) }] : []);
402
634
  const parts = Rs.map((r, j) => conj([...pcIs(j), ...r.map(atom)]));
403
- const set = parts.length === 1 ? parts[0] : { op: 'or', xs: parts };
404
635
  // the witness: each input of the loop per turn
405
- const distinctLocs = new Set(seq.map(from)).size === seq.length;
406
- const conds = parts.map((c, j) => (distinctLocs ? conj(pcIs(j).length ? pcIs(j) : [c]) : c));
636
+ // (a part is told by its location, and where the cycle comes back to a location, by an atom of its rows that each
637
+ // other part there refutes: a short condition, which the body's reads of the witness multiply less; its full rows
638
+ // where no atom tells it apart)
639
+ const tell = (j) => {
640
+ if (!rel.loc)
641
+ return parts[j];
642
+ const others = Rs.flatMap((r, k) => (k !== j && from(seq[k]) === from(seq[j]) ? [r] : []));
643
+ const atoms = [];
644
+ for (const r of others) {
645
+ if (atoms.some(a => !sat([...r, a])))
646
+ continue;
647
+ const a = Rs[j].find(f => !sat([...r, f]));
648
+ if (!a)
649
+ return parts[j];
650
+ atoms.push(a);
651
+ }
652
+ return conj([...pcIs(j), ...atoms.map(atom)]);
653
+ };
654
+ const conds = parts.map((_, j) => tell(j));
655
+ // Where each part is at a location of its own, the set is written by slots: the parts' k-th atoms, one comparison of
656
+ // two if-chains over the locations (the same set). The kernel reads an if only down the branch the case decides, so
657
+ // the set after the turn costs it the next part's atoms, not every part's (TermComp's tqli: its check 10.4 s to 4.5
658
+ // s). Not where parts share a location: their conditions in each chain cost more than they save (s1).
659
+ const slotted = () => {
660
+ const width = Math.max(...Rs.map(r => r.length)), chain = (pick) => conds.reduceRight((acc, c, j) => (isZ(pick(j)) && isZ(acc) ? acc : { op: 'if', c, then: pick(j), else: acc }), K(0));
661
+ const slots = [];
662
+ for (let k = 0; k < width; k++) {
663
+ const ts = Rs.map(r => (r[k] ? term(r[k]) : { p: K(0), n: K(0) }));
664
+ slots.push({ op: '<=', a: chain(j => ts[j].p), b: chain(j => ts[j].n) });
665
+ }
666
+ return { op: 'and', xs: [{ op: 'or', xs: conds }, ...slots] };
667
+ };
668
+ const set = parts.length > 1 && rel.loc && new Set(seq.map(from)).size === seq.length ? slotted() : parts.length === 1 ? parts[0] : { op: 'or', xs: parts };
407
669
  const valueAt = (j, n) => {
408
670
  const p = rel.paths[seq[j]];
409
671
  if (n in p.pins)
@@ -483,26 +745,6 @@ export function* stemsTo(l, targets, io, opts) {
483
745
  pairOf.set(x, [x, 1]);
484
746
  paramInts.push([x, undefined]);
485
747
  }
486
- const linRaw = (e) => {
487
- switch (e.op) {
488
- case 'var': return { [e.name]: 1 };
489
- case 'const': return konst(e.value);
490
- case 'add': {
491
- const a = linRaw(e.a), b = linRaw(e.b);
492
- return a && b && plus(a, b);
493
- }
494
- case 'mul': {
495
- const a = linRaw(e.a);
496
- return a && times(a, e.k);
497
- }
498
- case 'sub':
499
- case 'prod':
500
- case 'min':
501
- case 'max':
502
- case 'if':
503
- case 'get': return undefined;
504
- }
505
- };
506
748
  const toInts = (raw) => {
507
749
  const o = konst(raw['1'] ?? 0), seen = new Map();
508
750
  for (const r of vars(raw)) {
@@ -527,17 +769,17 @@ export function* stemsTo(l, targets, io, opts) {
527
769
  const pair = rel.ints.get(x);
528
770
  if (!pair) {
529
771
  const e = l.state[x];
530
- const r = e && linRaw(e);
772
+ const r = e && linOfE(e);
531
773
  return r && toInts(r);
532
774
  }
533
775
  const ep = l.state[pair[0]], en = l.state[pair[1]];
534
776
  if (!ep || !en)
535
777
  return undefined;
536
778
  if (ep.op === 'sub' && en.op === 'sub' && JSON.stringify(ep.a) === JSON.stringify(en.b) && JSON.stringify(ep.b) === JSON.stringify(en.a)) {
537
- const a = linRaw(ep.a), b = linRaw(ep.b);
779
+ const a = linOfE(ep.a), b = linOfE(ep.b);
538
780
  return a && b && toInts(plus(a, b, -1));
539
781
  }
540
- const a = linRaw(ep), b = linRaw(en);
782
+ const a = linOfE(ep), b = linOfE(en);
541
783
  return a && b && toInts(plus(a, b, -1));
542
784
  };
543
785
  const sigma0 = {};
@@ -676,21 +918,14 @@ export function* stemsTo(l, targets, io, opts) {
676
918
  if (segs.length + (dist.get(loc) ?? Infinity) > maxDepth)
677
919
  return;
678
920
  const step = (i, ins, n) => {
679
- const p = rel.paths[i];
680
- const insAt = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, sigma)]));
681
- const sub = { ...sigma, ...insAt };
682
- const rs = [...p.rows.map(f => subst(f, sub)), ...natState.map(x => times(sigma[x], -1)), ...Object.keys(insAt).filter(u => !rel.ints.has(u)).map(u => times(insAt[u], -1))];
683
- let post;
684
- if (n) {
685
- // the last turn's rows: at sigma + (n − 1)·δ
686
- const last = Object.fromEntries(S.map(x => [x, plus(plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0)), konst(-(n.delta[x] ?? 0)))]));
687
- const insLast = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, last)]));
688
- rs.push(...p.rows.map(f => subst(f, { ...last, ...insLast })), ...natState.map(x => times(last[x], -1)), plus(konst(1), { [n.name]: -1 }));
689
- post = Object.fromEntries(S.map(x => [x, plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0))]));
690
- }
691
- else
692
- post = Object.fromEntries(S.map(x => [x, subst(p.post[x] ?? { [x]: 1 }, sub)]));
693
- return { rs, post };
921
+ const { rs, post } = turn(rel, natState, i, sigma, ins, k);
922
+ if (!n)
923
+ return { rs, post };
924
+ // the last turn's rows: at sigma + (n − 1)·δ
925
+ const p = rel.paths[i], last = Object.fromEntries(S.map(x => [x, plus(plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0)), konst(-(n.delta[x] ?? 0)))]));
926
+ const insLast = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, last)]));
927
+ rs.push(...p.rows.map(f => subst(f, { ...last, ...insLast })), ...natState.map(x => times(last[x], -1)), plus(konst(1), { [n.name]: -1 }));
928
+ return { rs, post: Object.fromEntries(S.map(x => [x, plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0))])) };
694
929
  };
695
930
  // a self-loop accelerated, then each path out
696
931
  if (!lastLoop)