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
@@ -1,26 +1,196 @@
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). An inner loop (a self-loop,
11
+ // or a cycle of two turns, whose turn is a translation with a metering function: `accelerate`) is one more choice at
12
+ // its location, taken to its end at once: its count the metering function's value, linear in the state. Then the
13
+ // cycles the random runs take, between two visits of a location, the commonest first.
14
+ // - 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
15
+ // it (x < i0 gives i0 := x + 1, i0 >= 3 gives 3), else 0; or constants from a model of two rounds of the cycle; or a
16
+ // bound the rest of the cycle puts on it (`lookahead`). The cycle is then one linear loop: its guard G (each turn's
17
+ // rows, read at the state the turns before it leave) and its update U (affine in the state at the cycle's start).
18
+ // - Its n-fold run in closed form (the engine below): an atom g ≤ 0 of G holds after every number n of turns where its
19
+ // value along the run, g(Uⁿx), a polynomial in n for a translation or a triangular update, has its differences at
20
+ // n = 0 all ≤ 0: Δ⁰g = g, Δ^{k+1}g = Δ^k g∘U − Δ^k g, each linear in x (Σ C(n, k)·Δ^k g is g(Uⁿx)). For a geometric
21
+ // update (x := 2x) the differences repeat (Δ²g = Δ¹g) and the same set holds. So the set R is G with each atom's
22
+ // differences up to degree 3, and Houdini drops a difference that isn't kept by U (G's atoms are kept or the cycle is
23
+ // given up): R ∧ ¬a(Ux) refuted for each atom a, by the integer solver (core/solver.ts). A constant difference above 0
24
+ // gives the cycle up at once: g grows past 0.
25
+ // - The set of the loop: per step j of the cycle, at its location, the states from which the rest of the cycle's steps
26
+ // are allowed and end in R (R_j, the weakest precondition: the rest composed; an inner loop's at each of its turns);
27
+ // the witness by location, or by R_j where the cycle passes a location twice, its commonest value with no condition.
28
+ // - Products with a turn's input (x·u, which the relation leaves out): the loop's cases with x fixed (`fixedCases`), the
29
+ // set holding x so.
30
+ // - Stems (`stemsTo`): from the start's location to a part's, a path at a time or a self-loop with a closed form taken
31
+ // many times at once (a translation n times, any other 2 to 16), all linear, then run on the loop itself; `deepen`
32
+ // searches again at twice and four times the depth.
33
+ import { n as K, x as V } from "./machine.js";
1
34
  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];
35
+ import { canon, gcd, konst, linOfE, plus, solve, subst, times, vars } from "./solver.js";
36
+ import { Q0, Q1, bgcd, q, qadd, qdiv, qmul, qsub } from "./q.js";
37
+ const qv = (l) => new Map(Object.entries(l).filter(([, c]) => c).map(([x, c]) => [x, q(c)]));
38
+ const qvAdd = (a, b, f) => { const o = new Map(a); for (const [x, c] of b) {
39
+ const s = qadd(o.get(x) ?? Q0, qmul(c, f));
40
+ if (s.num)
41
+ o.set(x, s);
42
+ else
43
+ o.delete(x);
9
44
  } 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;
45
+ // The unknowns of A·u = B (each right-hand side a form), by elimination over the rationals; undefined where they aren't
46
+ // one solution.
47
+ function solveQ(A, B, m) {
48
+ const rows = A.map((r, i) => ({ a: [...r], b: B[i] })), piv = [];
49
+ let at = 0;
50
+ for (let j = 0; j < m; j++) {
51
+ const p = rows.findIndex((r, i) => i >= at && r.a[j].num !== 0n);
52
+ if (p < 0)
53
+ return undefined;
54
+ const r = rows[p];
55
+ rows[p] = rows[at];
56
+ rows[at] = r;
57
+ const inv = qdiv(Q1, r.a[j]);
58
+ r.a = r.a.map(x => qmul(x, inv));
59
+ r.b = qvAdd(new Map(), r.b, inv);
60
+ for (const [i, o] of rows.entries())
61
+ if (i !== at && o.a[j].num !== 0n) {
62
+ const f = o.a[j];
63
+ o.a = o.a.map((x, c) => qsub(x, qmul(f, r.a[c])));
64
+ o.b = qvAdd(o.b, r.b, qsub(Q0, f));
65
+ }
66
+ piv.push(at++);
67
+ }
68
+ return rows.slice(at).every(r => r.b.size === 0) ? piv.map(i => rows[i].b) : undefined;
69
+ }
70
+ const choose = (n, k) => { let c = 1n; for (let i = 0; i < k; i++)
71
+ c = c * BigInt(n - i) / BigInt(i + 1); return c; };
72
+ const basis = (r, k, n) => (r === 0 ? (n === k ? Q1 : Q0) : q(choose(n, k) * BigInt(r) ** BigInt(n)));
73
+ // The integer roots of Σ P[i]·tⁱ to their multiplicities, all of them, or undefined.
74
+ function intRoots(P) {
75
+ let p = [...P];
76
+ const out = [];
77
+ const take = (r) => {
78
+ const n = p.length - 1, b = new Array(n);
79
+ let acc = 0n;
80
+ for (let i = n; i >= 1; i--) {
81
+ acc = acc * r + p[i];
82
+ b[i - 1] = acc;
83
+ }
84
+ if (acc * r + p[0] !== 0n)
85
+ return false;
86
+ p = b;
87
+ const e = out.find(x => x.r === Number(r));
88
+ if (e)
89
+ e.mult++;
90
+ else
91
+ out.push({ r: Number(r), mult: 1 });
92
+ return true;
93
+ };
94
+ while (p.length > 1 && p[0] === 0n)
95
+ take(0n);
96
+ const c = p[0] < 0n ? -p[0] : p[0];
97
+ if (p.length > 1 && c > 10n ** 12n)
98
+ return undefined;
99
+ for (let d = 1n; p.length > 1 && d * d <= c; d++) {
100
+ if (c % d)
101
+ continue;
102
+ for (const r of [d, -d, c / d, -c / d])
103
+ while (p.length > 1 && take(r))
104
+ ;
105
+ }
106
+ return p.length === 1 && out.every(x => Math.abs(x.r) <= 2 ** 20) ? out : undefined;
107
+ }
108
+ export function closedForm(terms, exact, order = 6) {
109
+ const vs = terms.map(qv);
110
+ if (vs.every(v => v.size === 0))
111
+ return { terms: [], den: 1 };
112
+ for (let m = 1; m <= order; m++) {
113
+ const windows = exact ? 1 : vs.length - 2 * m;
114
+ if (vs.length < m + 1 || windows < 1)
115
+ return undefined;
116
+ // v[n + m] = Σ a_i·v[n + i], each coordinate of each window an equation
117
+ const A = [], B = [];
118
+ for (let n = 0; n < (exact ? 1 : vs.length - m); n++)
119
+ for (const x of new Set(vs.slice(n, n + m + 1).flatMap(v => [...v.keys()]))) {
120
+ A.push(vs.slice(n, n + m).map(v => v.get(x) ?? Q0));
121
+ B.push(new Map([['1', vs[n + m].get(x) ?? Q0]]));
122
+ }
123
+ const a = solveQ(A, B.map(b => new Map([...b].filter(([, c]) => c.num))), m);
124
+ if (!a)
125
+ continue;
126
+ // tᵐ − Σ a_i·tⁱ over the integers
127
+ const as = a.map(f => f.get('1') ?? Q0), L = as.reduce((l, x) => l / bgcd(l, x.den) * x.den, 1n);
128
+ const roots = intRoots([...as.map(x => -x.num * (L / x.den)), L]);
129
+ if (!roots)
130
+ return undefined;
131
+ const bs = roots.flatMap(({ r, mult }) => Array.from({ length: mult }, (_, k) => ({ r, k })));
132
+ const c = solveQ(Array.from({ length: m }, (_, n) => bs.map(b => basis(b.r, b.k, n))), vs.slice(0, m), m);
133
+ if (!c)
134
+ return undefined;
135
+ let den = 1n;
136
+ for (const f of c)
137
+ for (const x of f.values())
138
+ den = den / bgcd(den, x.den) * x.den;
139
+ const out = [];
140
+ for (const [j, f] of c.entries()) {
141
+ const l = {};
142
+ for (const [x, y] of f) {
143
+ const v = Number(y.num * (den / y.den));
144
+ if (!Number.isSafeInteger(v))
145
+ return undefined;
146
+ l[x] = v;
147
+ }
148
+ if (Object.keys(l).length)
149
+ out.push({ ...bs[j], c: l });
150
+ }
151
+ return Number.isSafeInteger(Number(den)) ? { terms: out, den: Number(den) } : undefined;
152
+ }
153
+ return undefined;
154
+ }
155
+ // g, g∘U, g∘U², … (count of them)
156
+ export const iterates = (g, U, count) => { const out = [g]; while (out.length < count)
157
+ out.push(subst(out.at(-1), U)); return out; };
158
+ // g(Uⁿx) in closed form
159
+ export const nfold = (g, U, order = 6) => closedForm(iterates(g, U, order + 1), true, order);
160
+ // A closed form that is a polynomial in n: its coefficients by k in the binomial basis C(n, k) (over den), or undefined.
161
+ export const polyOf = (f) => {
162
+ if (f.terms.some(t => t.r !== 1))
163
+ return undefined;
164
+ const out = [];
165
+ for (const t of f.terms)
166
+ out[t.k] = t.c;
167
+ return Array.from({ length: out.length }, (_, k) => out[k] ?? {});
168
+ };
169
+ // A closed form at a count n: a linear form (over the rationals where den doesn't divide it; a form of integer iterates
170
+ // is integral).
171
+ export const closedAt = (f, n) => {
172
+ let o = {};
173
+ for (const t of f.terms)
174
+ o = plus(o, times(t.c, Number(basis(t.r, t.k, n).num)));
175
+ return times(o, 1 / f.den);
19
176
  };
20
- const canon = (l) => JSON.stringify(Object.keys(l).sort().map(x => [x, l[x]]));
177
+ export function accelerate(G, U, S) {
178
+ const delta = {};
179
+ for (const x of S) {
180
+ const f = nfold({ [x]: 1 }, U, 2), p = f && polyOf(f);
181
+ if (!p || p.length > 2 || f.den !== 1 || vars(p[1] ?? {}).length)
182
+ return undefined;
183
+ if (p[1]?.['1'])
184
+ delta[x] = p[1]['1'];
185
+ }
186
+ if (!Object.keys(delta).length)
187
+ return undefined;
188
+ const rise = (a) => vars(a).reduce((s, x) => s + a[x] * (delta[x] ?? 0), 0);
189
+ const m = G.find(a => rise(a) === 1);
190
+ return { delta, ...(m ? { meter: plus(konst(1), m, -1) } : {}) };
191
+ }
21
192
  const isConst = (l) => vars(l).length === 0;
22
193
  // (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
194
  const tight = (l) => {
25
195
  const g = vars(l).reduce((s, x) => gcd(s, l[x]), 0);
26
196
  if (g <= 1)
@@ -37,88 +207,144 @@ const big = (l) => Object.values(l).some(c => !Number.isSafeInteger(c) || Math.a
37
207
  // rows lin <= 0 satisfiable over the integers (unknown counts as satisfiable: the kernel decides later)
38
208
  const sat = (rows) => solve(rows.map(lin => ({ lin, label: '' })), 3000).kind !== 'refuted';
39
209
  const implied = (rows, a) => solve([...rows, plus(times(a, -1), konst(1))].map(lin => ({ lin, label: '' })), 3000).kind === 'refuted';
40
- // The candidates, one at a time (a generator: the caller tries each against the kernel and stops when one is proven).
210
+ // The candidates, one at a time (a generator: the caller tries each against the kernel and stops when one is proven):
211
+ // the relation's cycles, then those of its cases where a state value that a product reads with a turn's input is fixed
212
+ // (`fixedCases`), which have 30% of the time where there are any.
41
213
  export function* accelerated(l, opts) {
42
- const rel = relOf(l);
43
- if (!rel)
44
- return;
214
+ const rel = relOf(l), fixed = fixedCases(l), { now } = opts;
215
+ if (rel)
216
+ yield* cyclesOf(l, rel, fixed.length ? { ...opts, until: now() + (opts.until - now()) * 0.7 } : opts, []);
217
+ for (const f of fixed) {
218
+ if (now() > opts.until)
219
+ return;
220
+ yield* cyclesOf(l, f.rel, { now, until: opts.until, ...(opts.maxLen ? { maxLen: opts.maxLen } : {}) }, f.pins);
221
+ }
222
+ }
223
+ // (`pins`: rows every part of the set keeps, the fixed values of a case)
224
+ function* cyclesOf(l, rel, opts, pins) {
45
225
  const { now, until } = opts, maxLen = opts.maxLen ?? 6;
46
- const S = rel.state, P = new Set(rel.params), Sset = new Set(S);
226
+ const S = rel.state, P = new Set(rel.params), Sset = new Set(S), NP = rel.paths.length;
47
227
  const natState = S.filter(x => !rel.ints.has(x));
48
- const from = (i) => (rel.loc ? rel.from[i] : 0), to = (i) => (rel.loc ? rel.to[i] : 0);
49
228
  // Each path's inputs as terms of the state before it (a few choices each, the first the likeliest).
50
229
  const choices = rel.paths.map(p => inputChoices(p, Sset, P));
230
+ const from = (i) => (i >= NP ? loops[i - NP].loc : rel.loc ? rel.from[i] : 0), to = (i) => (i >= NP ? loops[i - NP].loc : rel.loc ? rel.to[i] : 0);
231
+ const loops = [];
51
232
  // The cycles: closed walks of paths (a location may come twice: two turns at one location, taken in turn), each once
52
233
  // (its least rotation), with at most `maxLen` choices among a location's paths (a chain of locations with one path out,
53
234
  // as a translated program's straight-line code, is free) and at most 64 turns; the shortest first.
54
- let cycles = [];
55
- const byFrom = new Map();
56
- rel.paths.forEach((_, i) => { const f = from(i); byFrom.set(f, [...(byFrom.get(f) ?? []), i]); });
57
- const cap = opts.maxCycles ?? 400;
58
- const least = (seq) => seq.every((_, r) => r === 0 || cmp(seq, [...seq.slice(r), ...seq.slice(0, r)]) < 0);
59
- // (a turn costs 1 at a location of more than one path, 0 else; each location's least cost back to the cycle's start,
60
- // so a walk that can't come back within the budget is cut)
61
- const costAt = (loc) => ((byFrom.get(loc) ?? []).length > 1 ? 1 : 0);
62
- const back = (start) => {
63
- const d = new Map([[start, 0]]), queue = [start];
64
- while (queue.length) {
65
- const y = queue.shift();
66
- for (let i = 0; i < rel.paths.length; i++) {
67
- if (to(i) !== y)
68
- continue;
69
- const x = from(i), c = d.get(y) + costAt(x);
70
- if (c < (d.get(x) ?? Infinity)) {
71
- d.set(x, c);
72
- if (costAt(x))
73
- queue.push(x);
74
- else
75
- queue.unshift(x);
76
- }
77
- }
235
+ const enumerate = (ids) => {
236
+ let cycles = [];
237
+ // (those with an inner loop counted out apart, at most 60, after the rest)
238
+ const counted = [];
239
+ const byFrom = new Map();
240
+ for (let i = 0; i < ids; i++) {
241
+ const f = from(i);
242
+ byFrom.set(f, [...(byFrom.get(f) ?? []), i]);
78
243
  }
79
- return d;
80
- };
81
- 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)])) };
88
- };
89
- const id0 = Object.fromEntries(S.map(x => [x, { [x]: 1 }]));
90
- let nodes = 20_000;
91
- for (let budget = 0; budget <= maxLen && cycles.length < cap && nodes > 0; budget++) {
92
- for (let i = 0; i < rel.paths.length && cycles.length < cap && nodes > 0 && now() < until; i++) {
93
- const s0 = from(i);
94
- if (!backs.has(s0))
95
- backs.set(s0, back(s0));
96
- const d = backs.get(s0);
97
- const walk = (seq, at, cost, sigma, rows) => {
98
- if (--nodes < 0 || cycles.length >= cap || now() > until)
99
- return;
100
- if (at === s0 && cost === budget && least(seq) && sat(rows))
101
- cycles.push(seq);
102
- if (seq.length >= 64)
103
- return;
104
- const c = cost + costAt(at);
105
- if (c + (d.get(at) ?? Infinity) - costAt(at) > budget || c > budget)
106
- return;
107
- for (const j of byFrom.get(at) ?? []) {
108
- if (j < seq[0] || c + (d.get(to(j)) ?? Infinity) > budget)
109
- continue;
110
- const { rs, post } = open(sigma, j, seq.length), all = [...rows, ...rs];
111
- if (all.some(big) || (costAt(at) && !sat(all)))
244
+ const cap = opts.maxCycles ?? 400;
245
+ const least = (seq) => seq.every((_, r) => r === 0 || cmp(seq, [...seq.slice(r), ...seq.slice(0, r)]) < 0);
246
+ // (a turn costs 1 at a location of more than one path, 0 else; each location's least cost back to the cycle's start,
247
+ // so a walk that can't come back within the budget is cut)
248
+ const costAt = (loc) => ((byFrom.get(loc) ?? []).length > 1 ? 1 : 0);
249
+ const back = (start) => {
250
+ const d = new Map([[start, 0]]), queue = [start];
251
+ while (queue.length) {
252
+ const y = queue.shift();
253
+ for (let i = 0; i < NP; i++) {
254
+ if (to(i) !== y)
112
255
  continue;
113
- walk([...seq, j], to(j), c, post, all);
256
+ const x = from(i), c = d.get(y) + costAt(x);
257
+ if (c < (d.get(x) ?? Infinity)) {
258
+ d.set(x, c);
259
+ if (costAt(x))
260
+ queue.push(x);
261
+ else
262
+ queue.unshift(x);
263
+ }
114
264
  }
115
- };
116
- const c0 = costAt(s0), first = open(id0, i, 0);
117
- if (c0 + (d.get(to(i)) ?? Infinity) <= budget && sat(first.rs))
118
- walk([i], to(i), c0, first.post, first.rs);
265
+ }
266
+ return d;
267
+ };
268
+ const backs = new Map();
269
+ // (a self-loop that counts a value by ±1 towards a bound its rows put on it)
270
+ const counters = new Map();
271
+ const counter = (j) => {
272
+ if (counters.has(j))
273
+ return counters.get(j);
274
+ const p = rel.paths[j], bounds = boundsOf(p.rows);
275
+ let out;
276
+ for (const x of S) {
277
+ const e = p.post[x], delta = e?.['1'] ?? 0, b = bounds.get(x);
278
+ if (!e || vars(e).length !== 1 || e[x] !== 1 || Math.abs(delta) !== 1 || (delta > 0 ? b?.hi : b?.lo) === undefined)
279
+ continue;
280
+ out = { x, delta, ...(b.lo !== undefined ? { lo: b.lo } : {}), ...(b.hi !== undefined ? { hi: b.hi } : {}) };
281
+ break;
282
+ }
283
+ counters.set(j, out);
284
+ return out;
285
+ };
286
+ // (each walk's turns composed with their inputs left open, u@k: a walk whose rows are refuted is cut where it chose; an
287
+ // inner loop with its own inputs)
288
+ const open = (sigma, i, k) => (i >= NP ? stepTurn(rel, natState, { inner: loops[i - NP] }, sigma) : turn(rel, natState, i, sigma, symbolic(rel.paths[i], k, Sset, P), k));
289
+ const id0 = Object.fromEntries(S.map(x => [x, { [x]: 1 }]));
290
+ let nodes = 20_000;
291
+ for (let budget = 0; budget <= maxLen && cycles.length < cap && nodes > 0; budget++) {
292
+ for (let i = 0; i < NP && cycles.length < cap && nodes > 0 && now() < until; i++) {
293
+ const s0 = from(i);
294
+ if (!backs.has(s0))
295
+ backs.set(s0, back(s0));
296
+ const d = backs.get(s0);
297
+ // (`inner`: the self-loop just taken as many times as its rows allow, not taken again at once)
298
+ const walk = (seq, at, cost, sigma, rows, inner) => {
299
+ if (--nodes < 0 || cycles.length >= cap || now() > until)
300
+ return;
301
+ if (at === s0 && cost === budget && least(seq) && sat(rows)) {
302
+ if (!seq.some((x, q) => q > 0 && x === seq[q - 1] && to(x) === from(x) && x < NP))
303
+ cycles.push(seq);
304
+ else if (counted.length < 60)
305
+ counted.push(seq);
306
+ }
307
+ if (seq.length >= 64)
308
+ return;
309
+ const c = cost + costAt(at);
310
+ if (c + (d.get(at) ?? Infinity) - costAt(at) > budget || c > budget)
311
+ return;
312
+ for (const j of byFrom.get(at) ?? []) {
313
+ if (j === inner || j < seq[0] || (j >= NP && j === seq.at(-1)) || c + (d.get(to(j)) ?? Infinity) > budget)
314
+ continue;
315
+ const { rs, post } = open(sigma, j, seq.length), all = [...rows, ...rs];
316
+ if (all.some(big) || (costAt(at) && !sat(all)))
317
+ continue;
318
+ walk([...seq, j], to(j), c, post, all);
319
+ // 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
320
+ // set (x := 0, then x := x + 1 while x < 12: KnapsackDP's), taken as many times as that, as one choice, where
321
+ // that is 2 to 24 times; the walk goes on from there.
322
+ const cl = j < NP && to(j) === at && j !== seq.at(-1) && counted.length < 60 ? counter(j) : undefined, k0 = cl && sigma[cl.x];
323
+ if (cl && k0 && isConst(k0)) {
324
+ const k = k0['1'] ?? 0, r = cl.delta > 0 ? (cl.hi ?? -Infinity) - k + 1 : k - (cl.lo ?? Infinity) + 1;
325
+ if (r >= 2 && r <= 24 && seq.length + r < 64) {
326
+ let sg = sigma, rws = rows;
327
+ for (let q = 0; q < r; q++) {
328
+ const more = open(sg, j, seq.length + q);
329
+ sg = more.post;
330
+ rws = [...rws, ...more.rs];
331
+ }
332
+ nodes--;
333
+ if (!rws.some(big) && sat(rws))
334
+ walk([...seq, ...Array.from({ length: r }, () => j)], at, c, sg, rws, j);
335
+ }
336
+ }
337
+ }
338
+ };
339
+ const c0 = costAt(s0), first = open(id0, i, 0);
340
+ if (c0 + (d.get(to(i)) ?? Infinity) <= budget && sat(first.rs))
341
+ walk([i], to(i), c0, first.post, first.rs);
342
+ }
119
343
  }
120
- }
121
- cycles = cycles.sort((x, y) => x.length - y.length).slice(0, cap);
344
+ cycles = cycles.sort((x, y) => x.length - y.length).slice(0, cap);
345
+ return [...cycles.filter(c => c.length <= 6), ...counted.sort((x, y) => x.length - y.length), ...cycles.filter(c => c.length > 6)];
346
+ };
347
+ let cycles = enumerate(NP);
122
348
  // the runs' cycles: between two visits of a location, the paths taken (as their least rotation), by how often; after
123
349
  // the enumerated ones of at most 4 turns (at most 20,000 turns read)
124
350
  if (opts.runs && opts.io) {
@@ -163,40 +389,114 @@ export function* accelerated(l, opts) {
163
389
  cycles = [...short, ...fromRuns.filter(c => !shortKeys.has(c.join(','))), ...cycles.filter(c => c.length > 4 && !keys.has(c.join(',')))];
164
390
  }
165
391
  const tried = new Set();
166
- for (const cyc of cycles) {
167
- for (const reps of cyc.length === 1 ? [1, 2] : [1]) {
168
- const seq = Array.from({ length: reps }, () => cyc).flat();
169
- // the choices of inputs: constants from a model of two rounds of the cycle (the constants the same in each), then
170
- // each path's first choice of terms, then one path at a time its others
171
- const sets = [];
172
- const sym = seq.map((pi, j) => symbolic(rel.paths[pi], j, Sset, P));
173
- if (sym.some(x => Object.values(x).some(t => vars(t).some(v => v.includes('@'))))) {
174
- const two = compose(rel, [...seq, ...seq].map((path, j) => ({ path, ins: sym[j % seq.length] })), natState);
175
- const m = two && solve(two.rows.map(lin => ({ lin, label: '' })), 3000);
176
- if (m && m.kind === 'sat')
177
- sets.push(sym.map(x => Object.fromEntries(Object.entries(x).map(([u, t]) => [u, subst(t, Object.fromEntries(vars(t).filter(v => v.includes('@')).map(v => [v, konst(Math.round(m.witness[v] ?? 0))])))]))));
392
+ const stepOf = (pi, ins) => (pi >= NP ? { inner: loops[pi - NP] } : { path: pi, ins });
393
+ // (`look`: the lookahead's choices too, or only them)
394
+ const tryAll = function* (cycs, look) {
395
+ for (const cyc0 of cycs) {
396
+ // (a cycle with a product: its turn first, where its product is read at the cycle's start; one such turn at most)
397
+ const prodAt = cyc0.flatMap((pi, j) => (pi < NP && readsPi(rel.paths[pi]) ? [j] : []));
398
+ if (prodAt.length > 1)
399
+ continue;
400
+ const cyc = prodAt.length ? [...cyc0.slice(prodAt[0]), ...cyc0.slice(0, prodAt[0])] : cyc0;
401
+ for (const reps of cyc.length === 1 && !prodAt.length ? [1, 2] : [1]) {
402
+ const seq = Array.from({ length: reps }, () => cyc).flat();
403
+ const firsts = seq.map(pi => (pi >= NP ? {} : choices[pi][0]));
404
+ // the choices of inputs: constants from a model of two rounds of the cycle (the constants the same in each), then
405
+ // each path's first choice of terms, then one path at a time its others, then one input at a time a bound the rest
406
+ // of the cycle puts on it (`lookahead`)
407
+ const sets = [];
408
+ if (look === 'only')
409
+ sets.push(...lookahead(rel, seq.map((pi, j) => stepOf(pi, firsts[j])), natState, Sset, P));
410
+ else {
411
+ const sym = seq.map((pi, j) => (pi >= NP ? {} : symbolic(rel.paths[pi], j, Sset, P)));
412
+ if (sym.some(x => Object.values(x).some(t => vars(t).some(v => v.includes('@'))))) {
413
+ const two = compose(rel, [...seq, ...seq].map((pi, j) => stepOf(pi, sym[j % seq.length])), natState);
414
+ const m = two && solve(two.rows.map(lin => ({ lin, label: '' })), 3000);
415
+ if (m && m.kind === 'sat')
416
+ sets.push(sym.map(x => Object.fromEntries(Object.entries(x).map(([u, t]) => [u, subst(t, Object.fromEntries(vars(t).filter(v => v.includes('@')).map(v => [v, konst(Math.round(m.witness[v] ?? 0))])))]))));
417
+ }
418
+ sets.push(firsts);
419
+ seq.forEach((pi, j) => { if (pi < NP)
420
+ for (let c = 1; c < choices[pi].length; c++)
421
+ sets.push(seq.map((qi, k) => (k === j ? choices[pi][c] : firsts[k]))); });
422
+ if (look === 'yes')
423
+ sets.push(...lookahead(rel, seq.map((pi, j) => stepOf(pi, firsts[j])), natState, Sset, P));
424
+ }
425
+ for (const ins of sets) {
426
+ if (now() > until)
427
+ return;
428
+ const key = `${seq.join(',')}|${JSON.stringify(ins)}`;
429
+ if (tried.has(key))
430
+ continue;
431
+ tried.add(key);
432
+ const out = candidate(rel, seq.map((pi, j) => stepOf(pi, ins[j])), natState, l, () => now() > until, pins);
433
+ if (out)
434
+ yield { ...out, cycle: seq, locs: seq.map(from) };
435
+ }
178
436
  }
179
- sets.push(seq.map(pi => choices[pi][0]));
180
- seq.forEach((pi, j) => { for (let c = 1; c < choices[pi].length; c++)
181
- sets.push(seq.map((qi, k) => choices[qi][k === j ? c : 0])); });
182
- for (const ins of sets) {
183
- if (now() > until)
184
- return;
185
- const key = `${seq.join(',')}|${JSON.stringify(ins)}`;
186
- if (tried.has(key))
187
- continue;
188
- tried.add(key);
189
- const out = candidate(rel, seq, ins, natState, from, l, () => now() > until);
190
- if (out)
191
- yield { ...out, cycle: seq, locs: seq.map(from) };
437
+ }
438
+ };
439
+ // The relation's cycles, then the cycles with an inner loop taken to its end, then the lookahead's choices on the first
440
+ yield* tryAll(cycles, 'no');
441
+ if (now() > until)
442
+ return;
443
+ // The inner loops: a self-loop or a cycle of two turns at a location whose turn, with its inputs' choices, is a
444
+ // translation with a metering function (core/accel.ts's `accelerate`), taken to its end as one step of a walk; each
445
+ // named NP + k among the paths.
446
+ let tries = 2000;
447
+ for (let i = 0; i < NP && loops.length < 40 && tries > 0 && now() < until; i++) {
448
+ const at = rel.loc ? rel.from[i] : 0;
449
+ if (readsPi(rel.paths[i]))
450
+ continue;
451
+ const tails = rel.loc && rel.to[i] !== at ? rel.paths.flatMap((_, j) => (rel.from[j] === rel.to[i] && rel.to[j] === at && j !== i ? [j] : [])) : [];
452
+ for (const ps of [...(!rel.loc || rel.to[i] === at ? [[i]] : []), ...tails.map(j => [i, j])]) {
453
+ if (ps.some(j => readsPi(rel.paths[j])))
454
+ continue;
455
+ const combos = ps.length === 1 ? choices[i].map(c => [c]) : choices[i].flatMap(a => choices[ps[1]].map(b => [a, b]));
456
+ for (const ins of combos.slice(0, 9)) {
457
+ if (--tries < 0)
458
+ break;
459
+ const c = compose(rel, ps.map((path, j) => ({ path, ins: ins[j] })), natState), a = c && accelerate(c.rows, c.post, S);
460
+ if (c && a?.meter && sat(c.rows)) {
461
+ loops.push({ loc: at, paths: ps, ins, rows: c.rows, acc: { delta: a.delta, meter: a.meter } });
462
+ break;
463
+ }
192
464
  }
193
465
  }
194
466
  }
467
+ if (loops.length)
468
+ yield* tryAll(enumerate(NP + loops.length).filter(c => c.some(i => i >= NP)), 'yes');
469
+ if (now() < until)
470
+ yield* tryAll(cycles, 'only');
471
+ }
472
+ // The choices one input at a time of a turn's that the rest of the cycle bounds: the cycle from that turn on (its other
473
+ // inputs as chosen), the bounds its rows put on the input, as terms of the state at that turn (x ≤ u gives x), the
474
+ // first three that leave the rows satisfiable; at most 12.
475
+ function lookahead(rel, steps, natState, S, P) {
476
+ const out = [];
477
+ for (const [j, s] of steps.entries()) {
478
+ if (!('path' in s))
479
+ continue;
480
+ for (const u of inputsOf(rel.paths[s.path], S, P)) {
481
+ if (out.length >= 12)
482
+ return out;
483
+ const name = `${u}@look`, rot = [{ path: s.path, ins: { ...s.ins, [u]: { [name]: 1 } } }, ...steps.slice(j + 1), ...steps.slice(0, j)];
484
+ const c = compose(rel, rot, natState);
485
+ if (!c)
486
+ continue;
487
+ const { bounds } = optionsFor(c.rows, name, x => S.has(x) || P.has(x));
488
+ const ok = unique(bounds).filter(t => sat(c.rows.map(f => subst(f, { [name]: t }))));
489
+ for (const t of ok.slice(0, 3))
490
+ out.push(steps.map((x, k) => (k === j ? { ...s.ins, [u]: t } : 'path' in x ? x.ins : {})));
491
+ }
492
+ }
493
+ return out;
195
494
  }
196
495
  // The path a turn takes: its pins (the location, the rule) and its rows hold at the state and the turn's inputs.
197
496
  function pathAt(rel, among, st, input) {
198
497
  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); };
498
+ const value = (x) => { if (isPi(x))
499
+ 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
500
  for (const i of among) {
201
501
  const p = rel.paths[i];
202
502
  if (Object.entries(p.pins).some(([n, v]) => !n.endsWith('′') && n in at && at[n] !== v))
@@ -206,25 +506,212 @@ function pathAt(rel, among, st, input) {
206
506
  }
207
507
  return undefined;
208
508
  }
209
- const rels = new WeakMap();
509
+ // (the relation as built, products and all, and as kept: each built once a loop)
510
+ const raws = new WeakMap(), rels = new WeakMap();
511
+ const rawOf = (l) => { if (!raws.has(l))
512
+ raws.set(l, relationOf(l)); return raws.get(l); };
210
513
  function relOf(l) {
211
- if (rels.has(l))
212
- 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)
215
- let r = relationOf(l);
514
+ if (!rels.has(l))
515
+ rels.set(l, kept(l, rawOf(l)));
516
+ return rels.get(l);
517
+ }
518
+ // (a path that reads a product, which the relation stands for by a natural of its own, is kept where each product is
519
+ // 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
520
+ // cycle's start (`piFacts`); a product of a turn's input is left out. The kernel checks what is found against the loop
521
+ // itself.)
522
+ function kept(l, r) {
216
523
  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 };
524
+ const known = new Set([...l.params, ...Object.keys(l.state)]);
525
+ const ok = (x) => !isPi(x) || piParts(x)?.every(f => vars(f).every(n => known.has(n))) === true;
526
+ const keep = r.paths.map(p => [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].every(ok));
527
+ r = { ...r, paths: r.paths.filter((_, i) => keep[i]), from: r.from.filter((_, i) => keep[i]), to: r.to.filter((_, i) => keep[i]) };
528
+ }
529
+ return r && r.paths.length ? r : undefined;
530
+ }
531
+ // A product of a state value (or a param) and a turn's input (RandomHard's arg2 = arg3·x) is linear where the value is fixed:
532
+ // the loop's cases at x = 1, 0, −1 and 2 (an integer x, x$n or x$neg; a natural at 1, 0 and 2), each the relation of the
533
+ // loop whose condition fixes x first (its products then a constant times the input), the set holding x fixed (`pins`).
534
+ // At most two such values.
535
+ const fixes = new WeakMap();
536
+ function fixedCases(l) {
537
+ const hit = fixes.get(l);
538
+ if (hit)
539
+ return hit;
540
+ const out = [], raw = rawOf(l), S = new Set([...Object.keys(l.state), ...l.params]), I = new Set(l.inputs), xs = new Set();
541
+ for (const p of raw && !raw.exact ? raw.paths : [])
542
+ for (const n of [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)]) {
543
+ const fs = isPi(n) ? piParts(n) : undefined;
544
+ if (!fs)
545
+ continue;
546
+ const [a, b] = fs.map(vars);
547
+ for (const [f, g] of [[a, b], [b, a]])
548
+ if (f.length === 1 && S.has(f[0]) && g.some(x => I.has(x)))
549
+ xs.add(f[0].replace(/\$(n|neg)$/, ''));
550
+ }
551
+ for (const x of [...xs].filter(x => S.has(x)).slice(0, 2)) {
552
+ const twin = [`${x}$n`, `${x}$neg`].find(t => S.has(t));
553
+ for (const c of twin ? [1, 0, -1, 2] : [1, 0, 2]) {
554
+ const vals = twin ? [[x, Math.max(c, 0)], [twin, Math.max(-c, 0)]] : [[x, c]];
555
+ const r = kept(l, relationOf({ ...l, while: { op: 'and', xs: [...vals.map(([n, v]) => ({ op: '=', a: V(n), b: K(v) })), l.while] } }));
556
+ if (!r)
557
+ continue;
558
+ const pins = r.ints.has(x) ? [{ [x]: 1, 1: -c }, { [x]: -1, 1: c }] : vals.flatMap(([n, v]) => [{ [n]: 1, ...konst(-v) }, { [n]: -1, ...konst(v) }]);
559
+ out.push({ rel: r, pins });
560
+ }
561
+ }
562
+ fixes.set(l, out);
563
+ return out;
564
+ }
565
+ // --- products ---------------------------------------------------------------------------------------------------------
566
+ //
567
+ // A product the relation names π(a·b) (core/relation.ts: two of the loop's naturals, each one value or a part of an
568
+ // integer's pair) is, where the set decides the sign of each integer it reads, ±X·Y over the relation's integers, or 0
569
+ // (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
570
+ // for lower bounds l, m, and likewise for the upper ones; a square's tangents (X − c)² ≥ 0), linear in the product's
571
+ // name: what a Houdini check of the set needs to keep x := x·y.
572
+ const isPi = (x) => x.startsWith('π(');
573
+ // (the two factors, linear in the loop's names)
574
+ const piParts = (x) => {
575
+ const m = /^π\((.*)·(.*)\)(#\d+)?$/.exec(x);
576
+ if (!m)
577
+ return undefined;
578
+ try {
579
+ return [JSON.parse(m[1]), JSON.parse(m[2])];
580
+ }
581
+ catch {
582
+ return undefined;
583
+ }
584
+ };
585
+ const piSeen = new WeakMap();
586
+ const readsPi = (p) => { let out = piSeen.get(p); if (out === undefined)
587
+ piSeen.set(p, (out = [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].some(isPi))); return out; };
588
+ // (a turn's products named for the turn: values of their own, as the search over several turns reads them)
589
+ const fresh = (l, k) => { if (!vars(l).some(isPi))
590
+ return l; const o = {}; for (const x in l)
591
+ o[isPi(x) ? `${x}#${k}` : x] = l[x]; return o; };
592
+ 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);
593
+ // A product's value in a run (its factors' raw values multiplied).
594
+ const piValue = (rel, x, at) => {
595
+ const ev = (f) => vars(f).reduce((acc, n) => acc + f[n] * (at[n] ?? 0), f['1'] ?? 0);
596
+ const raw = (n) => { const fs = piParts(n); return fs ? ev(fs[0]) * ev(fs[1]) : at[n] ?? 0; };
597
+ const pair = rel.ints.get(x);
598
+ return pair ? raw(pair[0]) - raw(pair[1]) : raw(x);
599
+ };
600
+ // The bounds the rows put on one integer each.
601
+ function boundsOf(R) {
602
+ const out = new Map();
603
+ for (const f of R) {
604
+ const xs = vars(f);
605
+ if (xs.length !== 1)
606
+ continue;
607
+ const x = xs[0], a = f[x], b = f['1'] ?? 0, e = out.get(x) ?? {};
608
+ if (a > 0)
609
+ e.hi = Math.min(e.hi ?? Infinity, Math.floor(-b / a));
610
+ else
611
+ e.lo = Math.max(e.lo ?? -Infinity, Math.ceil(-b / a));
612
+ out.set(x, e);
613
+ }
614
+ return out;
615
+ }
616
+ // The facts of the products among `names`, given the set's rows R.
617
+ function piFacts(rel, R, names) {
618
+ const pis = [...new Set(names.filter(isPi))];
619
+ if (!pis.length)
620
+ return [];
621
+ 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; };
622
+ const partOf = new Map();
623
+ for (const [X, [p, n]] of rel.ints) {
624
+ partOf.set(p, [X, 1]);
625
+ partOf.set(n, [X, -1]);
626
+ }
627
+ // 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
628
+ // most one name in it
629
+ const factor = (f) => {
630
+ let o = konst(f['1'] ?? 0);
631
+ for (const r of vars(f)) {
632
+ const q = partOf.get(r);
633
+ if (!q) {
634
+ o = plus(o, { [r]: f[r] });
635
+ continue;
636
+ }
637
+ const s = sign(q[0]);
638
+ if (!s)
639
+ return undefined;
640
+ if (s === q[1])
641
+ o = plus(o, { [q[0]]: f[r] * q[1] });
642
+ }
643
+ return vars(o).length <= 1 ? o : undefined;
644
+ };
645
+ const out = [];
646
+ for (const N of pis) {
647
+ const pair = rel.ints.get(N), terms = pair ? [[pair[0], 1], [pair[1], -1]] : [[N, 1]];
648
+ // N = lin + Σ c·X·Y, by product
649
+ const prods = new Map();
650
+ let lin = {}, ok = true;
651
+ for (const [raw, c0] of terms) {
652
+ const fs = piParts(raw), a = fs && factor(fs[0]), b = fs && factor(fs[1]);
653
+ if (!a || !b) {
654
+ ok = false;
655
+ break;
656
+ }
657
+ const ka = a['1'] ?? 0, kb = b['1'] ?? 0, xa = vars(a)[0], xb = vars(b)[0];
658
+ lin = plus(lin, konst(c0 * ka * kb));
659
+ if (xb)
660
+ lin = plus(lin, { [xb]: c0 * ka * b[xb] });
661
+ if (xa)
662
+ lin = plus(lin, { [xa]: c0 * kb * a[xa] });
663
+ if (xa && xb) {
664
+ const [X, Y] = [xa, xb].sort(), key = `${X}*${Y}`, e = prods.get(key) ?? { X, Y, c: 0 };
665
+ e.c += c0 * a[xa] * b[xb];
666
+ prods.set(key, e);
667
+ }
668
+ }
669
+ const live = [...prods.values()].filter(e => e.c);
670
+ if (!ok || live.length > 1)
671
+ continue;
672
+ if (!live.length) {
673
+ out.push(plus({ [N]: 1 }, lin, -1), plus(lin, { [N]: 1 }, -1));
674
+ continue;
675
+ }
676
+ const { X, Y, c } = live[0];
677
+ if (Math.abs(c) !== 1)
678
+ continue;
679
+ // rows over p = X·Y, then p := c·N
680
+ const rows = [], bx = bounds.get(X) ?? {}, by = bounds.get(Y) ?? {};
681
+ 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
682
+ 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
683
+ if (X === Y) {
684
+ rows.push({ p: -1 });
685
+ for (const b of [bx.lo, bx.hi])
686
+ if (b !== undefined && Number.isFinite(b))
687
+ rows.push({ [X]: 2 * b, 1: -b * b, p: -1 });
688
+ }
689
+ else {
690
+ if (bx.lo !== undefined && by.lo !== undefined)
691
+ lower(bx.lo, by.lo);
692
+ if (bx.hi !== undefined && by.hi !== undefined)
693
+ lower(bx.hi, by.hi);
694
+ if (bx.lo !== undefined && by.hi !== undefined)
695
+ upper(bx.lo, by.hi);
696
+ if (bx.hi !== undefined && by.lo !== undefined)
697
+ rows.push({ [X]: -by.lo, [Y]: -bx.hi, 1: bx.hi * by.lo, p: 1 });
698
+ }
699
+ // (p = c·(N − lin))
700
+ for (const f of rows) {
701
+ const rest = {};
702
+ for (const x in f)
703
+ if (x !== 'p')
704
+ rest[x] = f[x];
705
+ const o = plus(rest, plus({ [N]: 1 }, lin, -1), f.p * c);
706
+ if (!Object.values(o).some(v => !Number.isFinite(v)))
707
+ out.push(o);
708
+ }
220
709
  }
221
- const out = r && r.paths.length ? r : undefined;
222
- rels.set(l, out);
223
710
  return out;
224
711
  }
225
712
  function inputsOf(p, S, P) {
226
713
  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();
714
+ return read.filter(x => !S.has(x) && !P.has(x) && !isPi(x)).sort();
228
715
  }
229
716
  // 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
717
  // bounds a row puts on u (a constant rounded inward, or a term where u's coefficient is ±1).
@@ -291,65 +778,98 @@ function symbolic(p, j, S, P) {
291
778
  }
292
779
  return ins;
293
780
  }
294
- // Turns j.. of the cycle composed from a state x (identity at j): the rows over x, and the state after them over x.
781
+ // 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
782
+ // natural's term a natural), and the state after; with `k`, the turn's products named for the turn k (`freshPath`).
783
+ function turn(rel, natState, i, sigma, ins, k) {
784
+ 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 };
785
+ 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))],
786
+ post: Object.fromEntries(rel.state.map(x => [x, subst(p.post[x] ?? { [x]: 1 }, sub)])) };
787
+ }
788
+ // A step from sigma. An inner loop's: its count m = meter(sigma) at least 1, its turn's rows at the first and the last
789
+ // of its turns (sigma + (m − 1)·δ: each row is linear in the turn's number, so it holds between), the state after
790
+ // sigma + m·δ, all linear in sigma.
791
+ function stepTurn(rel, natState, s, sigma) {
792
+ if ('path' in s)
793
+ return turn(rel, natState, s.path, sigma, s.ins);
794
+ const { rows, acc } = s.inner, m = subst(acc.meter, sigma);
795
+ const shift = (t) => Object.fromEntries(rel.state.map(x => [x, plus(sigma[x], times(t, acc.delta[x] ?? 0))]));
796
+ const last = shift(plus(m, konst(-1)));
797
+ return { rs: [plus(konst(1), m, -1), ...rows.map(f => subst(f, sigma)), ...rows.map(f => subst(f, last))], post: shift(m) };
798
+ }
799
+ // Steps j.. of the cycle composed from a state x (identity at j): the rows over x, and the state after them over x.
295
800
  function compose(rel, steps, natState) {
296
801
  let sigma = Object.fromEntries(rel.state.map(x => [x, { [x]: 1 }]));
297
802
  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;
803
+ for (const [j, s] of steps.entries()) {
804
+ if (j > 0 && 'path' in s && readsPi(rel.paths[s.path]))
805
+ return undefined;
806
+ const t = stepTurn(rel, natState, s, sigma);
807
+ rows.push(...t.rs);
808
+ sigma = t.post;
314
809
  if (Object.values(sigma).some(big) || rows.some(big))
315
810
  return undefined;
316
811
  }
317
812
  return { rows: dedupe(rows.map(tight).filter(f => !(isConst(f) && (f['1'] ?? 0) <= 0))), post: sigma };
318
813
  }
319
814
  const dedupe = (rows) => [...new Map(rows.map(f => [canon(f), f])).values()];
320
- // (`late`: the time is up; a candidate half made is given up)
321
- function candidate(rel, seq, ins, natState, from, l, late) {
322
- const steps = seq.map((path, j) => ({ path, ins: ins[j] }));
815
+ // (`late`: the time is up; a candidate half made is given up; `pins`: rows each part keeps, a case's fixed values)
816
+ function candidate(rel, steps, natState, l, late, pins) {
323
817
  const whole = compose(rel, steps, natState);
324
818
  if (!whole)
325
819
  return undefined;
326
- const G = whole.rows, U = whole.post;
327
- if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || !sat(G))
820
+ const G = dedupe([...whole.rows, ...pins]), U = whole.post;
821
+ if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || G.some(f => vars(f).some(isPi)) || !sat(G))
328
822
  return undefined;
329
- // the differences of each atom of G along U, up to degree 3
823
+ // 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): the
824
+ // iterates g, g∘U, … of the closed forms' engine, differenced; a constant last difference above 0 gives the cycle up (g
825
+ // grows past 0)
330
826
  const opt = [];
331
827
  for (const g of G) {
332
828
  let d = g;
333
829
  for (let k = 1; k <= 3; k++) {
334
830
  const next = plus(subst(d, U), d, -1);
831
+ if (vars(next).some(isPi))
832
+ break;
335
833
  if (isConst(next)) {
336
834
  if ((next['1'] ?? 0) > 0)
337
835
  return undefined;
338
836
  break;
339
- } // (a constant > 0: g grows past 0)
837
+ }
340
838
  if (canon(next) === canon(d))
341
839
  break;
342
840
  opt.push(tight(next));
343
841
  d = next;
344
842
  }
345
843
  }
844
+ // 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
845
+ // 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
846
+ // Houdini tries (complInterv's x ≥ 4 for y := (x + 1)² > 9), the weakest that does kept.
847
+ const piU = [...new Set(Object.values(U).flatMap(vars).filter(isPi))];
848
+ const keeps = (rs, a) => { const after = subst(a, U); return implied(piU.length ? [...rs, ...piFacts(rel, rs, vars(after))] : rs, after); };
849
+ const pool = [];
850
+ if (piU.length) {
851
+ const partOf = new Map();
852
+ for (const [X, [p, n]] of rel.ints) {
853
+ partOf.set(p, X);
854
+ partOf.set(n, X);
855
+ }
856
+ 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))];
857
+ for (const x of xs) {
858
+ const dir = implied(G, { [x]: -1 }) ? 1 : implied(G, { [x]: 1 }) ? -1 : 1;
859
+ for (const c of [0, 1, 2, 3, 4, 8, 16, 32]) {
860
+ const b = { [x]: -dir, ...konst(c) };
861
+ if (sat([...G, b]))
862
+ pool.push(b);
863
+ }
864
+ }
865
+ }
346
866
  // Houdini: G must be kept by U; a difference not kept is dropped
347
- let R = dedupe([...G, ...opt]);
867
+ let R = dedupe([...G, ...opt, ...pool]);
348
868
  const must = new Set(G.map(canon));
349
869
  for (let round = 0; round < 12; round++) {
350
870
  if (late())
351
871
  return undefined;
352
- const bad = R.filter(a => !implied(R, subst(a, U)));
872
+ const bad = R.filter(a => !keeps(R, a));
353
873
  if (!bad.length)
354
874
  break;
355
875
  if (bad.some(a => must.has(canon(a))))
@@ -357,22 +877,51 @@ function candidate(rel, seq, ins, natState, from, l, late) {
357
877
  const drop = new Set(bad.map(canon));
358
878
  R = R.filter(a => !drop.has(canon(a)));
359
879
  }
360
- if (R.some(a => !implied(R, subst(a, U))) || !sat(R))
880
+ if (R.some(a => !keeps(R, a)) || !sat(R))
361
881
  return undefined;
882
+ // (the factors' bounds the set keeps: each left out, the strongest first, where the rest is kept without it)
883
+ for (const b of [...pool].reverse()) {
884
+ if (late())
885
+ return undefined;
886
+ const key = canon(b), rest = R.filter(a => canon(a) !== key);
887
+ if (rest.length < R.length && !must.has(key) && rest.every(a => keeps(rest, a)))
888
+ R = rest;
889
+ }
362
890
  // R without what the rest of it implies (a smaller goal for the kernel)
363
891
  R = irredundant(R, late);
364
892
  if (late())
365
893
  return undefined;
366
- // per turn j: R_j, the rest of the cycle from turn j allowed and ending in R
894
+ // per step j: R_j, the rest of the cycle from step j allowed and ending in R (an inner loop's, at each of its turns'
895
+ // starts with a turn of it left: the same state after it)
896
+ const restOf = (rows, post, to) => irredundant(dedupe([...rows, ...pins, ...to.map(a => tight(subst(a, post)))].filter(f => !(isConst(f) && (f['1'] ?? 0) <= 0))), late);
367
897
  const Rs = steps.map((_, j) => {
368
898
  if (j === 0)
369
899
  return R;
370
900
  const rest = compose(rel, steps.slice(j), natState);
371
- return irredundant(dedupe([...rest.rows, ...R.map(a => tight(subst(a, rest.post)))].filter(f => !(isConst(f) && (f['1'] ?? 0) <= 0))), late);
901
+ return restOf(rest.rows, rest.post, R);
372
902
  });
373
903
  if (late())
374
904
  return undefined;
375
- if (Rs.some(r => !sat(r)))
905
+ const locOf = (i) => (rel.loc ? rel.from[i] : 0);
906
+ const parts = [];
907
+ for (const [j, s] of steps.entries()) {
908
+ if ('path' in s) {
909
+ parts.push({ loc: locOf(s.path), rows: Rs[j], path: s.path, ins: s.ins });
910
+ continue;
911
+ }
912
+ const { paths, ins } = s.inner;
913
+ parts.push({ loc: s.inner.loc, rows: Rs[j], path: paths[0], ins: ins[0] });
914
+ for (let t = 1; t < paths.length; t++) {
915
+ const rest = compose(rel, paths.slice(t).map((path, k) => ({ path, ins: ins[t + k] })), natState);
916
+ if (!rest)
917
+ return undefined;
918
+ for (const to of [Rs[j], Rs[(j + 1) % steps.length]])
919
+ parts.push({ loc: locOf(paths[t]), rows: restOf(rest.rows, rest.post, to), path: paths[t], ins: ins[t] });
920
+ }
921
+ }
922
+ if (late())
923
+ return undefined;
924
+ if (parts.some(p => !sat(p.rows)))
376
925
  return undefined;
377
926
  // as the loop's condition and witness
378
927
  const intOf = (x) => rel.ints.get(x);
@@ -398,17 +947,47 @@ function candidate(rel, seq, ins, natState, from, l, late) {
398
947
  };
399
948
  const atom = (f) => { const t = term(f); return { op: '<=', a: t.p, b: t.n }; };
400
949
  const conj = (xs) => (xs.length === 1 ? xs[0] : { op: 'and', xs });
401
- const pcIs = (j) => (rel.loc ? [{ op: '=', a: V(rel.loc), b: K(from(seq[j])) }] : []);
402
- 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
- // 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));
950
+ const pcIs = (j) => (rel.loc ? [{ op: '=', a: V(rel.loc), b: K(parts[j].loc) }] : []);
951
+ const full = parts.map((r, j) => conj([...pcIs(j), ...r.rows.map(atom)]));
952
+ // the witness: each input of the loop per part
953
+ // (a part is told by its location, and where the cycle comes back to a location, by an atom of its rows that each
954
+ // other part there refutes: a short condition, which the body's reads of the witness multiply less; its full rows
955
+ // where no atom tells it apart)
956
+ const tell = (j) => {
957
+ if (!rel.loc)
958
+ return full[j];
959
+ const others = parts.flatMap((r, k) => (k !== j && r.loc === parts[j].loc ? [r.rows] : []));
960
+ const atoms = [];
961
+ for (const r of others) {
962
+ if (atoms.some(a => !sat([...r, a])))
963
+ continue;
964
+ const a = parts[j].rows.find(f => !sat([...r, f]));
965
+ if (!a)
966
+ return full[j];
967
+ atoms.push(a);
968
+ }
969
+ return conj([...pcIs(j), ...atoms.map(atom)]);
970
+ };
971
+ const conds = parts.map((_, j) => tell(j));
972
+ // Where each part is at a location of its own, the set is written by slots: the parts' k-th atoms, one comparison of
973
+ // two if-chains over the locations (the same set). The kernel reads an if only down the branch the case decides, so
974
+ // 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
975
+ // s). Not where parts share a location: their conditions in each chain cost more than they save (s1).
976
+ const slotted = () => {
977
+ const width = Math.max(...parts.map(r => r.rows.length)), chain = (pick) => conds.reduceRight((acc, c, j) => (isZ(pick(j)) && isZ(acc) ? acc : { op: 'if', c, then: pick(j), else: acc }), K(0));
978
+ const slots = [];
979
+ for (let k = 0; k < width; k++) {
980
+ const ts = parts.map(r => (r.rows[k] ? term(r.rows[k]) : { p: K(0), n: K(0) }));
981
+ slots.push({ op: '<=', a: chain(j => ts[j].p), b: chain(j => ts[j].n) });
982
+ }
983
+ return { op: 'and', xs: [{ op: 'or', xs: conds }, ...slots] };
984
+ };
985
+ const set = parts.length > 1 && rel.loc && new Set(parts.map(p => p.loc)).size === parts.length ? slotted() : parts.length === 1 ? full[0] : { op: 'or', xs: full };
407
986
  const valueAt = (j, n) => {
408
- const p = rel.paths[seq[j]];
987
+ const p = rel.paths[parts[j].path];
409
988
  if (n in p.pins)
410
989
  return K(p.pins[n]);
411
- const u = steps[j].ins;
990
+ const u = parts[j].ins;
412
991
  for (const [x, pair] of rel.ints)
413
992
  if (pair[0] === n || pair[1] === n) {
414
993
  const t = u[x];
@@ -425,7 +1004,7 @@ function candidate(rel, seq, ins, natState, from, l, late) {
425
1004
  };
426
1005
  const wit = {};
427
1006
  for (const n of l.inputs) {
428
- const vals = seq.map((_, j) => valueAt(j, n)), keys = vals.map(v => JSON.stringify(v));
1007
+ const vals = parts.map((_, j) => valueAt(j, n)), keys = vals.map(v => JSON.stringify(v));
429
1008
  if (keys.every(k => k === keys[0])) {
430
1009
  wit[n] = vals[0];
431
1010
  continue;
@@ -442,7 +1021,7 @@ function candidate(rel, seq, ins, natState, from, l, late) {
442
1021
  e = { op: 'if', c: conds[j], then: vals[j], else: e };
443
1022
  wit[n] = e;
444
1023
  }
445
- return { set, wit, targets: Rs.map((rows, j) => ({ loc: from(seq[j]), rows })) };
1024
+ return { set, wit, targets: parts.map(p => ({ loc: p.loc, rows: p.rows })) };
446
1025
  }
447
1026
  const cmp = (a, b) => { for (let i = 0; i < a.length; i++)
448
1027
  if (a[i] !== b[i])
@@ -483,26 +1062,6 @@ export function* stemsTo(l, targets, io, opts) {
483
1062
  pairOf.set(x, [x, 1]);
484
1063
  paramInts.push([x, undefined]);
485
1064
  }
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
1065
  const toInts = (raw) => {
507
1066
  const o = konst(raw['1'] ?? 0), seen = new Map();
508
1067
  for (const r of vars(raw)) {
@@ -527,17 +1086,17 @@ export function* stemsTo(l, targets, io, opts) {
527
1086
  const pair = rel.ints.get(x);
528
1087
  if (!pair) {
529
1088
  const e = l.state[x];
530
- const r = e && linRaw(e);
1089
+ const r = e && linOfE(e);
531
1090
  return r && toInts(r);
532
1091
  }
533
1092
  const ep = l.state[pair[0]], en = l.state[pair[1]];
534
1093
  if (!ep || !en)
535
1094
  return undefined;
536
1095
  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);
1096
+ const a = linOfE(ep.a), b = linOfE(ep.b);
538
1097
  return a && b && toInts(plus(a, b, -1));
539
1098
  }
540
- const a = linRaw(ep), b = linRaw(en);
1099
+ const a = linOfE(ep), b = linOfE(en);
541
1100
  return a && b && toInts(plus(a, b, -1));
542
1101
  };
543
1102
  const sigma0 = {};
@@ -554,25 +1113,26 @@ export function* stemsTo(l, targets, io, opts) {
554
1113
  const from = (i) => (rel.loc ? rel.from[i] : 0), to = (i) => (rel.loc ? rel.to[i] : 0);
555
1114
  const loops = new Map();
556
1115
  rel.paths.forEach((p, i) => {
557
- if (from(i) !== to(i))
1116
+ if (from(i) !== to(i) || readsPi(p))
558
1117
  return;
559
1118
  for (const ins of inputChoices(p, Sset, P)) {
560
1119
  const c = compose(rel, [{ path: i, ins }], natState);
561
1120
  if (!c)
562
1121
  continue;
563
- const delta = {};
564
- let ok = true;
1122
+ const a = accelerate(c.rows, c.post, S);
1123
+ if (a) {
1124
+ loops.set(from(i), [...(loops.get(from(i)) ?? []), { path: i, ins, delta: a.delta }]);
1125
+ break;
1126
+ }
1127
+ const closed = {};
565
1128
  for (const x of S) {
566
- const d = plus(c.post[x], { [x]: 1 }, -1);
567
- if (!isConst(d)) {
568
- ok = false;
1129
+ const f = nfold({ [x]: 1 }, c.post, 4);
1130
+ if (!f)
569
1131
  break;
570
- }
571
- if (d['1'])
572
- delta[x] = d['1'];
1132
+ closed[x] = f;
573
1133
  }
574
- if (ok && Object.keys(delta).length) {
575
- loops.set(from(i), [...(loops.get(from(i)) ?? []), { path: i, ins, delta }]);
1134
+ if (Object.keys(closed).length === S.length && S.some(x => canon(c.post[x]) !== canon({ [x]: 1 }))) {
1135
+ loops.set(from(i), [...(loops.get(from(i)) ?? []), { path: i, ins, closed }]);
576
1136
  break;
577
1137
  }
578
1138
  }
@@ -620,7 +1180,7 @@ export function* stemsTo(l, targets, io, opts) {
620
1180
  const stem = [];
621
1181
  let left = 200_000;
622
1182
  for (const s of segs) {
623
- const times = s.n ? Math.round(w[s.n] ?? 1) : 1;
1183
+ const times = s.n ? Math.round(w[s.n] ?? 1) : s.times ?? 1;
624
1184
  if (times > 100_000)
625
1185
  return undefined;
626
1186
  for (let k = 0; k < times; k++) {
@@ -654,7 +1214,8 @@ export function* stemsTo(l, targets, io, opts) {
654
1214
  opts.report.exhausted = true;
655
1215
  return;
656
1216
  }
657
- const maxDepth = Math.max(depth, dist.get(startLoc) + depth);
1217
+ // (`deepen`: the depth, then twice and four times it, with the calls given, 4 and 16 times them, a stem yielded once)
1218
+ let maxDepth = 0, shallow = -1;
658
1219
  const outs = new Map();
659
1220
  for (let i = 0; i < rel.paths.length; i++)
660
1221
  if (dist.has(to(i)))
@@ -667,7 +1228,7 @@ export function* stemsTo(l, targets, io, opts) {
667
1228
  for (const t of targets)
668
1229
  if (t.loc === loc) {
669
1230
  const m = solveRows([...rows, ...t.rows.map(f => subst(f, sigma))]);
670
- if (m.kind === 'sat') {
1231
+ if (m.kind === 'sat' && segs.length > shallow) {
671
1232
  const c = concrete(segs, m.witness);
672
1233
  if (c)
673
1234
  yield c;
@@ -676,25 +1237,33 @@ export function* stemsTo(l, targets, io, opts) {
676
1237
  if (segs.length + (dist.get(loc) ?? Infinity) > maxDepth)
677
1238
  return;
678
1239
  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 };
1240
+ const { rs, post } = turn(rel, natState, i, sigma, ins, k);
1241
+ if (!n)
1242
+ return { rs, post };
1243
+ // the last turn's rows: at sigma + (n − 1)·δ
1244
+ 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)))]));
1245
+ const insLast = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, last)]));
1246
+ rs.push(...p.rows.map(f => subst(f, { ...last, ...insLast })), ...natState.map(x => times(last[x], -1)), plus(konst(1), { [n.name]: -1 }));
1247
+ return { rs, post: Object.fromEntries(S.map(x => [x, plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0))])) };
694
1248
  };
695
1249
  // a self-loop accelerated, then each path out
696
1250
  if (!lastLoop)
697
1251
  for (const lp of loops.get(loc) ?? []) {
1252
+ if (lp.closed) {
1253
+ // each count: its turns' rows (each turn's state the closed form at its number), the state after at the count
1254
+ let rs = [];
1255
+ for (let c = 1, at = sigma; c <= 16; c++) {
1256
+ rs = [...rs, ...turn(rel, natState, lp.path, at, lp.ins).rs];
1257
+ at = Object.fromEntries(S.map(x => [x, subst(closedAt(lp.closed[x], c), sigma)]));
1258
+ if (![2, 4, 8, 16].includes(c))
1259
+ continue;
1260
+ const all = [...rows, ...rs];
1261
+ if (all.some(big) || Object.values(at).some(big) || solveRows(all).kind === 'refuted')
1262
+ break;
1263
+ yield* dfs(loc, at, all, [...segs, { path: lp.path, ins: lp.ins, times: c }], k + 1, true);
1264
+ }
1265
+ continue;
1266
+ }
698
1267
  const name = `n@${k}`, { rs, post } = step(lp.path, lp.ins, { name, delta: lp.delta });
699
1268
  const all = [...rows, ...rs];
700
1269
  if (solveRows(all).kind === 'refuted')
@@ -714,7 +1283,15 @@ export function* stemsTo(l, targets, io, opts) {
714
1283
  yield* dfs(to(i), post, all, [...segs, { path: i, ins }], k + 1, false);
715
1284
  }
716
1285
  }
717
- yield* dfs(startLoc, sigma0, [...base], [], 0, false);
718
- if (opts.report && calls > 0 && now() <= until)
1286
+ for (const r of opts.deepen ? [1, 2, 4] : [1]) {
1287
+ const d = r * depth;
1288
+ calls = (opts.calls ?? 400) * r * r;
1289
+ maxDepth = Math.max(d, dist.get(startLoc) + d);
1290
+ yield* dfs(startLoc, sigma0, [...base], [], 0, false);
1291
+ if (calls <= 0 || now() > until)
1292
+ return;
1293
+ shallow = maxDepth;
1294
+ }
1295
+ if (opts.report)
719
1296
  opts.report.exhausted = true;
720
1297
  }