gdp-wired 0.26.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.
@@ -7,27 +7,188 @@
7
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
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
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.
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.
12
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
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.
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.
28
33
  import { n as K, x as V } from "./machine.js";
29
34
  import { relationOf } from "./relation.js";
30
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);
44
+ } 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);
176
+ };
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
+ }
31
192
  const isConst = (l) => vars(l).length === 0;
32
193
  // (a row's coefficients divided by their common divisor, its constant rounded up: an integer row as tight as it goes)
33
194
  const tight = (l) => {
@@ -46,126 +207,144 @@ const big = (l) => Object.values(l).some(c => !Number.isSafeInteger(c) || Math.a
46
207
  // rows lin <= 0 satisfiable over the integers (unknown counts as satisfiable: the kernel decides later)
47
208
  const sat = (rows) => solve(rows.map(lin => ({ lin, label: '' })), 3000).kind !== 'refuted';
48
209
  const implied = (rows, a) => solve([...rows, plus(times(a, -1), konst(1))].map(lin => ({ lin, label: '' })), 3000).kind === 'refuted';
49
- // 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.
50
213
  export function* accelerated(l, opts) {
51
- const rel = relOf(l);
52
- if (!rel)
53
- 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) {
54
225
  const { now, until } = opts, maxLen = opts.maxLen ?? 6;
55
- 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;
56
227
  const natState = S.filter(x => !rel.ints.has(x));
57
- const from = (i) => (rel.loc ? rel.from[i] : 0), to = (i) => (rel.loc ? rel.to[i] : 0);
58
228
  // Each path's inputs as terms of the state before it (a few choices each, the first the likeliest).
59
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 = [];
60
232
  // The cycles: closed walks of paths (a location may come twice: two turns at one location, taken in turn), each once
61
233
  // (its least rotation), with at most `maxLen` choices among a location's paths (a chain of locations with one path out,
62
234
  // as a translated program's straight-line code, is free) and at most 64 turns; the shortest first.
63
- let cycles = [];
64
- // (those with an inner loop apart, at most 60, after the rest)
65
- const inners = [];
66
- const byFrom = new Map();
67
- rel.paths.forEach((_, i) => { const f = from(i); byFrom.set(f, [...(byFrom.get(f) ?? []), i]); });
68
- const cap = opts.maxCycles ?? 400;
69
- const least = (seq) => seq.every((_, r) => r === 0 || cmp(seq, [...seq.slice(r), ...seq.slice(0, r)]) < 0);
70
- // (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,
71
- // so a walk that can't come back within the budget is cut)
72
- const costAt = (loc) => ((byFrom.get(loc) ?? []).length > 1 ? 1 : 0);
73
- const back = (start) => {
74
- const d = new Map([[start, 0]]), queue = [start];
75
- while (queue.length) {
76
- const y = queue.shift();
77
- for (let i = 0; i < rel.paths.length; i++) {
78
- if (to(i) !== y)
79
- continue;
80
- const x = from(i), c = d.get(y) + costAt(x);
81
- if (c < (d.get(x) ?? Infinity)) {
82
- d.set(x, c);
83
- if (costAt(x))
84
- queue.push(x);
85
- else
86
- queue.unshift(x);
87
- }
88
- }
89
- }
90
- return d;
91
- };
92
- const backs = new Map();
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;
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]);
106
243
  }
107
- counters.set(j, out);
108
- return out;
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);
112
- const id0 = Object.fromEntries(S.map(x => [x, { [x]: 1 }]));
113
- let nodes = 20_000;
114
- for (let budget = 0; budget <= maxLen && cycles.length < cap && nodes > 0; budget++) {
115
- for (let i = 0; i < rel.paths.length && cycles.length < cap && nodes > 0 && now() < until; i++) {
116
- const s0 = from(i);
117
- if (!backs.has(s0))
118
- backs.set(s0, back(s0));
119
- const d = backs.get(s0);
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) => {
122
- if (--nodes < 0 || cycles.length >= cap || now() > until)
123
- return;
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
- }
130
- if (seq.length >= 64)
131
- return;
132
- const c = cost + costAt(at);
133
- if (c + (d.get(at) ?? Infinity) - costAt(at) > budget || c > budget)
134
- return;
135
- for (const j of byFrom.get(at) ?? []) {
136
- if (j === inner || j < seq[0] || c + (d.get(to(j)) ?? Infinity) > budget)
137
- continue;
138
- const { rs, post } = open(sigma, j, seq.length), all = [...rows, ...rs];
139
- 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)
140
255
  continue;
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];
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
+ }
264
+ }
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);
154
335
  }
155
- nodes--;
156
- if (!rws.some(big) && sat(rws))
157
- walk([...seq, ...Array.from({ length: r }, () => j)], at, c, sg, rws, j);
158
336
  }
159
337
  }
160
- }
161
- };
162
- const c0 = costAt(s0), first = open(id0, i, 0);
163
- if (c0 + (d.get(to(i)) ?? Infinity) <= budget && sat(first.rs))
164
- walk([i], to(i), c0, first.post, first.rs);
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
+ }
165
343
  }
166
- }
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)];
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);
169
348
  // the runs' cycles: between two visits of a location, the paths taken (as their least rotation), by how often; after
170
349
  // the enumerated ones of at most 4 turns (at most 20,000 turns read)
171
350
  if (opts.runs && opts.io) {
@@ -210,40 +389,108 @@ export function* accelerated(l, opts) {
210
389
  cycles = [...short, ...fromRuns.filter(c => !shortKeys.has(c.join(','))), ...cycles.filter(c => c.length > 4 && !keys.has(c.join(',')))];
211
390
  }
212
391
  const tried = new Set();
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]) {
220
- const seq = Array.from({ length: reps }, () => cyc).flat();
221
- // the choices of inputs: constants from a model of two rounds of the cycle (the constants the same in each), then
222
- // each path's first choice of terms, then one path at a time its others
223
- const sets = [];
224
- const sym = seq.map((pi, j) => symbolic(rel.paths[pi], j, Sset, P));
225
- if (sym.some(x => Object.values(x).some(t => vars(t).some(v => v.includes('@'))))) {
226
- const two = compose(rel, [...seq, ...seq].map((path, j) => ({ path, ins: sym[j % seq.length] })), natState);
227
- const m = two && solve(two.rows.map(lin => ({ lin, label: '' })), 3000);
228
- if (m && m.kind === 'sat')
229
- 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
+ }
230
436
  }
231
- sets.push(seq.map(pi => choices[pi][0]));
232
- seq.forEach((pi, j) => { for (let c = 1; c < choices[pi].length; c++)
233
- sets.push(seq.map((qi, k) => choices[qi][k === j ? c : 0])); });
234
- for (const ins of sets) {
235
- if (now() > until)
236
- return;
237
- const key = `${seq.join(',')}|${JSON.stringify(ins)}`;
238
- if (tried.has(key))
239
- continue;
240
- tried.add(key);
241
- const out = candidate(rel, seq, ins, natState, from, l, () => now() > until);
242
- if (out)
243
- 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
+ }
244
464
  }
245
465
  }
246
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;
247
494
  }
248
495
  // The path a turn takes: its pins (the location, the rule) and its rows hold at the state and the turn's inputs.
249
496
  function pathAt(rel, among, st, input) {
@@ -259,23 +506,60 @@ function pathAt(rel, among, st, input) {
259
506
  }
260
507
  return undefined;
261
508
  }
262
- 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); };
263
513
  function relOf(l) {
264
- if (rels.has(l))
265
- return rels.get(l);
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.)
270
- 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) {
271
523
  if (r && !r.exact) {
272
524
  const known = new Set([...l.params, ...Object.keys(l.state)]);
273
525
  const ok = (x) => !isPi(x) || piParts(x)?.every(f => vars(f).every(n => known.has(n))) === true;
274
526
  const keep = r.paths.map(p => [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].every(ok));
275
527
  r = { ...r, paths: r.paths.filter((_, i) => keep[i]), from: r.from.filter((_, i) => keep[i]), to: r.to.filter((_, i) => keep[i]) };
276
528
  }
277
- const out = r && r.paths.length ? r : undefined;
278
- rels.set(l, out);
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);
279
563
  return out;
280
564
  }
281
565
  // --- products ---------------------------------------------------------------------------------------------------------
@@ -501,14 +785,25 @@ function turn(rel, natState, i, sigma, ins, k) {
501
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))],
502
786
  post: Object.fromEntries(rel.state.map(x => [x, subst(p.post[x] ?? { [x]: 1 }, sub)])) };
503
787
  }
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.
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.
505
800
  function compose(rel, steps, natState) {
506
801
  let sigma = Object.fromEntries(rel.state.map(x => [x, { [x]: 1 }]));
507
802
  const rows = [];
508
803
  for (const [j, s] of steps.entries()) {
509
- if (j > 0 && readsPi(rel.paths[s.path]))
804
+ if (j > 0 && 'path' in s && readsPi(rel.paths[s.path]))
510
805
  return undefined;
511
- const t = turn(rel, natState, s.path, sigma, s.ins);
806
+ const t = stepTurn(rel, natState, s, sigma);
512
807
  rows.push(...t.rs);
513
808
  sigma = t.post;
514
809
  if (Object.values(sigma).some(big) || rows.some(big))
@@ -517,16 +812,17 @@ function compose(rel, steps, natState) {
517
812
  return { rows: dedupe(rows.map(tight).filter(f => !(isConst(f) && (f['1'] ?? 0) <= 0))), post: sigma };
518
813
  }
519
814
  const dedupe = (rows) => [...new Map(rows.map(f => [canon(f), f])).values()];
520
- // (`late`: the time is up; a candidate half made is given up)
521
- function candidate(rel, seq, ins, natState, from, l, late) {
522
- 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) {
523
817
  const whole = compose(rel, steps, natState);
524
818
  if (!whole)
525
819
  return undefined;
526
- const G = whole.rows, U = whole.post;
820
+ const G = dedupe([...whole.rows, ...pins]), U = whole.post;
527
821
  if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || G.some(f => vars(f).some(isPi)) || !sat(G))
528
822
  return undefined;
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)
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)
530
826
  const opt = [];
531
827
  for (const g of G) {
532
828
  let d = g;
@@ -538,7 +834,7 @@ function candidate(rel, seq, ins, natState, from, l, late) {
538
834
  if ((next['1'] ?? 0) > 0)
539
835
  return undefined;
540
836
  break;
541
- } // (a constant > 0: g grows past 0)
837
+ }
542
838
  if (canon(next) === canon(d))
543
839
  break;
544
840
  opt.push(tight(next));
@@ -595,16 +891,37 @@ function candidate(rel, seq, ins, natState, from, l, late) {
595
891
  R = irredundant(R, late);
596
892
  if (late())
597
893
  return undefined;
598
- // 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);
599
897
  const Rs = steps.map((_, j) => {
600
898
  if (j === 0)
601
899
  return R;
602
900
  const rest = compose(rel, steps.slice(j), natState);
603
- 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);
604
902
  });
605
903
  if (late())
606
904
  return undefined;
607
- 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)))
608
925
  return undefined;
609
926
  // as the loop's condition and witness
610
927
  const intOf = (x) => rel.ints.get(x);
@@ -630,23 +947,23 @@ function candidate(rel, seq, ins, natState, from, l, late) {
630
947
  };
631
948
  const atom = (f) => { const t = term(f); return { op: '<=', a: t.p, b: t.n }; };
632
949
  const conj = (xs) => (xs.length === 1 ? xs[0] : { op: 'and', xs });
633
- const pcIs = (j) => (rel.loc ? [{ op: '=', a: V(rel.loc), b: K(from(seq[j])) }] : []);
634
- const parts = Rs.map((r, j) => conj([...pcIs(j), ...r.map(atom)]));
635
- // the witness: each input of the loop per turn
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
636
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
637
954
  // other part there refutes: a short condition, which the body's reads of the witness multiply less; its full rows
638
955
  // where no atom tells it apart)
639
956
  const tell = (j) => {
640
957
  if (!rel.loc)
641
- return parts[j];
642
- const others = Rs.flatMap((r, k) => (k !== j && from(seq[k]) === from(seq[j]) ? [r] : []));
958
+ return full[j];
959
+ const others = parts.flatMap((r, k) => (k !== j && r.loc === parts[j].loc ? [r.rows] : []));
643
960
  const atoms = [];
644
961
  for (const r of others) {
645
962
  if (atoms.some(a => !sat([...r, a])))
646
963
  continue;
647
- const a = Rs[j].find(f => !sat([...r, f]));
964
+ const a = parts[j].rows.find(f => !sat([...r, f]));
648
965
  if (!a)
649
- return parts[j];
966
+ return full[j];
650
967
  atoms.push(a);
651
968
  }
652
969
  return conj([...pcIs(j), ...atoms.map(atom)]);
@@ -657,20 +974,20 @@ function candidate(rel, seq, ins, natState, from, l, late) {
657
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
658
975
  // s). Not where parts share a location: their conditions in each chain cost more than they save (s1).
659
976
  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));
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));
661
978
  const slots = [];
662
979
  for (let k = 0; k < width; k++) {
663
- const ts = Rs.map(r => (r[k] ? term(r[k]) : { p: K(0), n: K(0) }));
980
+ const ts = parts.map(r => (r.rows[k] ? term(r.rows[k]) : { p: K(0), n: K(0) }));
664
981
  slots.push({ op: '<=', a: chain(j => ts[j].p), b: chain(j => ts[j].n) });
665
982
  }
666
983
  return { op: 'and', xs: [{ op: 'or', xs: conds }, ...slots] };
667
984
  };
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 };
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 };
669
986
  const valueAt = (j, n) => {
670
- const p = rel.paths[seq[j]];
987
+ const p = rel.paths[parts[j].path];
671
988
  if (n in p.pins)
672
989
  return K(p.pins[n]);
673
- const u = steps[j].ins;
990
+ const u = parts[j].ins;
674
991
  for (const [x, pair] of rel.ints)
675
992
  if (pair[0] === n || pair[1] === n) {
676
993
  const t = u[x];
@@ -687,7 +1004,7 @@ function candidate(rel, seq, ins, natState, from, l, late) {
687
1004
  };
688
1005
  const wit = {};
689
1006
  for (const n of l.inputs) {
690
- 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));
691
1008
  if (keys.every(k => k === keys[0])) {
692
1009
  wit[n] = vals[0];
693
1010
  continue;
@@ -704,7 +1021,7 @@ function candidate(rel, seq, ins, natState, from, l, late) {
704
1021
  e = { op: 'if', c: conds[j], then: vals[j], else: e };
705
1022
  wit[n] = e;
706
1023
  }
707
- 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 })) };
708
1025
  }
709
1026
  const cmp = (a, b) => { for (let i = 0; i < a.length; i++)
710
1027
  if (a[i] !== b[i])
@@ -796,25 +1113,26 @@ export function* stemsTo(l, targets, io, opts) {
796
1113
  const from = (i) => (rel.loc ? rel.from[i] : 0), to = (i) => (rel.loc ? rel.to[i] : 0);
797
1114
  const loops = new Map();
798
1115
  rel.paths.forEach((p, i) => {
799
- if (from(i) !== to(i))
1116
+ if (from(i) !== to(i) || readsPi(p))
800
1117
  return;
801
1118
  for (const ins of inputChoices(p, Sset, P)) {
802
1119
  const c = compose(rel, [{ path: i, ins }], natState);
803
1120
  if (!c)
804
1121
  continue;
805
- const delta = {};
806
- 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 = {};
807
1128
  for (const x of S) {
808
- const d = plus(c.post[x], { [x]: 1 }, -1);
809
- if (!isConst(d)) {
810
- ok = false;
1129
+ const f = nfold({ [x]: 1 }, c.post, 4);
1130
+ if (!f)
811
1131
  break;
812
- }
813
- if (d['1'])
814
- delta[x] = d['1'];
1132
+ closed[x] = f;
815
1133
  }
816
- if (ok && Object.keys(delta).length) {
817
- 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 }]);
818
1136
  break;
819
1137
  }
820
1138
  }
@@ -862,7 +1180,7 @@ export function* stemsTo(l, targets, io, opts) {
862
1180
  const stem = [];
863
1181
  let left = 200_000;
864
1182
  for (const s of segs) {
865
- 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;
866
1184
  if (times > 100_000)
867
1185
  return undefined;
868
1186
  for (let k = 0; k < times; k++) {
@@ -896,7 +1214,8 @@ export function* stemsTo(l, targets, io, opts) {
896
1214
  opts.report.exhausted = true;
897
1215
  return;
898
1216
  }
899
- 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;
900
1219
  const outs = new Map();
901
1220
  for (let i = 0; i < rel.paths.length; i++)
902
1221
  if (dist.has(to(i)))
@@ -909,7 +1228,7 @@ export function* stemsTo(l, targets, io, opts) {
909
1228
  for (const t of targets)
910
1229
  if (t.loc === loc) {
911
1230
  const m = solveRows([...rows, ...t.rows.map(f => subst(f, sigma))]);
912
- if (m.kind === 'sat') {
1231
+ if (m.kind === 'sat' && segs.length > shallow) {
913
1232
  const c = concrete(segs, m.witness);
914
1233
  if (c)
915
1234
  yield c;
@@ -930,6 +1249,21 @@ export function* stemsTo(l, targets, io, opts) {
930
1249
  // a self-loop accelerated, then each path out
931
1250
  if (!lastLoop)
932
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
+ }
933
1267
  const name = `n@${k}`, { rs, post } = step(lp.path, lp.ins, { name, delta: lp.delta });
934
1268
  const all = [...rows, ...rs];
935
1269
  if (solveRows(all).kind === 'refuted')
@@ -949,7 +1283,15 @@ export function* stemsTo(l, targets, io, opts) {
949
1283
  yield* dfs(to(i), post, all, [...segs, { path: i, ins }], k + 1, false);
950
1284
  }
951
1285
  }
952
- yield* dfs(startLoc, sigma0, [...base], [], 0, false);
953
- 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)
954
1296
  opts.report.exhausted = true;
955
1297
  }