gdp-wired 0.23.0 → 0.25.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 (47) hide show
  1. package/README.md +12 -2
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +720 -0
  4. package/dist/core/bmc.d.ts +13 -2
  5. package/dist/core/bmc.js +390 -18
  6. package/dist/core/cycles.d.ts +23 -0
  7. package/dist/core/cycles.js +527 -146
  8. package/dist/core/data.d.ts +17 -0
  9. package/dist/core/data.js +1177 -213
  10. package/dist/core/discover.js +8 -3
  11. package/dist/core/dsl.d.ts +7 -2
  12. package/dist/core/dsl.js +47 -9
  13. package/dist/core/extract-check.d.ts +77 -0
  14. package/dist/core/extract-check.js +785 -0
  15. package/dist/core/extract-ir.d.ts +139 -0
  16. package/dist/core/extract-ir.js +198 -0
  17. package/dist/core/extract-print.d.ts +30 -0
  18. package/dist/core/extract-print.js +426 -0
  19. package/dist/core/extract-read.d.ts +298 -0
  20. package/dist/core/extract-read.js +1298 -0
  21. package/dist/core/extract-shapes.d.ts +13 -0
  22. package/dist/core/extract-shapes.js +993 -0
  23. package/dist/core/extract-xstate.d.ts +34 -0
  24. package/dist/core/extract-xstate.js +320 -0
  25. package/dist/core/extract.d.ts +31 -0
  26. package/dist/core/extract.js +249 -0
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +298 -28
  29. package/dist/core/kind.d.ts +30 -0
  30. package/dist/core/kind.js +81 -0
  31. package/dist/core/nonterm.d.ts +4 -1
  32. package/dist/core/nonterm.js +98 -2
  33. package/dist/core/relation.js +82 -7
  34. package/dist/core/transfer.js +1 -1
  35. package/dist/core/xstate.d.ts +6 -0
  36. package/dist/core/xstate.js +70 -12
  37. package/dist/kernel/cdcl.d.ts +15 -0
  38. package/dist/kernel/cdcl.js +331 -244
  39. package/dist/kernel/kernel.d.ts +15 -0
  40. package/dist/kernel/kernel.js +32 -0
  41. package/dist/kernel/prove.js +20 -7
  42. package/dist/kernel/reader.d.ts +14 -0
  43. package/dist/kernel/reader.js +102 -14
  44. package/dist/lean-kernel/emit.d.ts +28 -1
  45. package/dist/lean-kernel/emit.js +56 -15
  46. package/dist/lean-kernel/library.js +2 -1
  47. package/package.json +12 -3
@@ -0,0 +1,720 @@
1
+ import { relationOf } from "./relation.js";
2
+ import { solve } from "./solver.js";
3
+ const K = (value) => ({ op: 'const', value }), V = (name) => ({ op: 'var', name });
4
+ const vars = (l) => Object.keys(l).filter(x => x !== '1');
5
+ const plus = (a, b, f = 1) => { const o = { ...a }; for (const x in b) {
6
+ o[x] = (o[x] ?? 0) + f * b[x];
7
+ if (!o[x])
8
+ delete o[x];
9
+ } return o; };
10
+ const times = (a, f) => { const o = {}; if (f)
11
+ for (const x in a)
12
+ o[x] = a[x] * f; return o; };
13
+ const konst = (c) => (c ? { 1: c } : {});
14
+ const subst = (l, m) => {
15
+ let o = konst(l['1'] ?? 0);
16
+ for (const x of vars(l))
17
+ o = plus(o, m[x] ?? { [x]: 1 }, l[x]);
18
+ return o;
19
+ };
20
+ const canon = (l) => JSON.stringify(Object.keys(l).sort().map(x => [x, l[x]]));
21
+ const isConst = (l) => vars(l).length === 0;
22
+ // (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
+ const tight = (l) => {
25
+ const g = vars(l).reduce((s, x) => gcd(s, l[x]), 0);
26
+ if (g <= 1)
27
+ return l;
28
+ const o = {};
29
+ for (const x of vars(l))
30
+ o[x] = l[x] / g;
31
+ const c = Math.ceil((l['1'] ?? 0) / g);
32
+ if (c)
33
+ o['1'] = c;
34
+ return o;
35
+ };
36
+ const big = (l) => Object.values(l).some(c => !Number.isSafeInteger(c) || Math.abs(c) > 2 ** 40);
37
+ // rows lin <= 0 satisfiable over the integers (unknown counts as satisfiable: the kernel decides later)
38
+ const sat = (rows) => solve(rows.map(lin => ({ lin, label: '' })), 3000).kind !== 'refuted';
39
+ 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).
41
+ export function* accelerated(l, opts) {
42
+ const rel = relOf(l);
43
+ if (!rel)
44
+ return;
45
+ const { now, until } = opts, maxLen = opts.maxLen ?? 6;
46
+ const S = rel.state, P = new Set(rel.params), Sset = new Set(S);
47
+ 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
+ // Each path's inputs as terms of the state before it (a few choices each, the first the likeliest).
50
+ const choices = rel.paths.map(p => inputChoices(p, Sset, P));
51
+ // The cycles: closed walks of paths (a location may come twice: two turns at one location, taken in turn), each once
52
+ // (its least rotation), with at most `maxLen` choices among a location's paths (a chain of locations with one path out,
53
+ // 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
+ }
78
+ }
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)))
112
+ continue;
113
+ walk([...seq, j], to(j), c, post, all);
114
+ }
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);
119
+ }
120
+ }
121
+ cycles = cycles.sort((x, y) => x.length - y.length).slice(0, cap);
122
+ // the runs' cycles: between two visits of a location, the paths taken (as their least rotation), by how often; after
123
+ // the enumerated ones of at most 4 turns (at most 20,000 turns read)
124
+ if (opts.runs && opts.io) {
125
+ const count = new Map();
126
+ const byLoc = new Map();
127
+ rel.paths.forEach((_, i) => { byLoc.set(from(i), [...(byLoc.get(from(i)) ?? []), i]); });
128
+ let budget = 20_000;
129
+ for (const r of opts.runs) {
130
+ if (now() > until || budget <= 0)
131
+ break;
132
+ let st = opts.io.start(r.params);
133
+ const seq = [];
134
+ for (const input of r.inputs.slice(0, Math.min(budget, 1000))) {
135
+ budget--;
136
+ const i = pathAt(rel, byLoc.get(rel.loc ? st[rel.loc] ?? 0 : 0) ?? [], st, input);
137
+ if (i === undefined)
138
+ break;
139
+ seq.push(i);
140
+ const nx = opts.io.turn(st, input);
141
+ if (!nx)
142
+ break;
143
+ st = nx;
144
+ }
145
+ const next = new Map();
146
+ for (let k = seq.length - 1; k >= 0; k--) {
147
+ const j = next.get(from(seq[k]));
148
+ next.set(from(seq[k]), k);
149
+ if (j === undefined || j - k > 64)
150
+ continue;
151
+ const c = seq.slice(k, j);
152
+ const r0 = c.map((_, q) => [...c.slice(q), ...c.slice(0, q)]).sort(cmp)[0], key = r0.join(',');
153
+ const e = count.get(key);
154
+ if (e)
155
+ e.n++;
156
+ else
157
+ count.set(key, { seq: r0, n: 1 });
158
+ }
159
+ }
160
+ const fromRuns = [...count.values()].sort((a, b) => b.n - a.n || a.seq.length - b.seq.length).slice(0, 60).map(e => e.seq);
161
+ const keys = new Set(fromRuns.map(c => c.join(','))), short = cycles.filter(c => c.length <= 4);
162
+ const shortKeys = new Set(short.map(c => c.join(',')));
163
+ cycles = [...short, ...fromRuns.filter(c => !shortKeys.has(c.join(','))), ...cycles.filter(c => c.length > 4 && !keys.has(c.join(',')))];
164
+ }
165
+ 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))])))]))));
178
+ }
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) };
192
+ }
193
+ }
194
+ }
195
+ }
196
+ // The path a turn takes: its pins (the location, the rule) and its rows hold at the state and the turn's inputs.
197
+ function pathAt(rel, among, st, input) {
198
+ 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); };
200
+ for (const i of among) {
201
+ const p = rel.paths[i];
202
+ if (Object.entries(p.pins).some(([n, v]) => !n.endsWith('′') && n in at && at[n] !== v))
203
+ continue;
204
+ if (p.rows.every(f => vars(f).reduce((s, x) => s + f[x] * value(x), f['1'] ?? 0) <= 0))
205
+ return i;
206
+ }
207
+ return undefined;
208
+ }
209
+ const rels = new WeakMap();
210
+ 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);
216
+ 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 };
220
+ }
221
+ const out = r && r.paths.length ? r : undefined;
222
+ rels.set(l, out);
223
+ return out;
224
+ }
225
+ function inputsOf(p, S, P) {
226
+ 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();
228
+ }
229
+ // 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
+ // bounds a row puts on u (a constant rounded inward, or a term where u's coefficient is ±1).
231
+ function optionsFor(rows, u, known) {
232
+ const eqs = [], lows = [], highs = [];
233
+ const keys = new Set(rows.map(canon));
234
+ for (const f of rows) {
235
+ const c = f[u];
236
+ if (c === undefined)
237
+ continue;
238
+ const rest = plus(f, { [u]: c }, -1);
239
+ if (!vars(rest).every(known))
240
+ continue;
241
+ if (Math.abs(c) === 1 && keys.has(canon(times(f, -1)))) {
242
+ eqs.push(times(rest, -1 / c));
243
+ continue;
244
+ }
245
+ if (isConst(rest)) {
246
+ const b = -(rest['1'] ?? 0) / c;
247
+ (c < 0 ? lows : highs).push(konst(c < 0 ? Math.ceil(b) : Math.floor(b)));
248
+ }
249
+ else if (Math.abs(c) === 1)
250
+ (c < 0 ? lows : highs).push(times(rest, -1 / c));
251
+ }
252
+ return { eqs, bounds: [...lows, ...highs] };
253
+ }
254
+ const unique = (ls) => [...new Map(ls.map(t => [canon(t), t])).values()];
255
+ // Up to three choices of a path's inputs as terms: per input, the alt-th of its options that leaves the path's rows
256
+ // satisfiable (each input read with those chosen before it put in).
257
+ function inputChoices(p, S, P) {
258
+ const inputs = inputsOf(p, S, P);
259
+ if (!inputs.length)
260
+ return [{}];
261
+ const known = (x) => S.has(x) || P.has(x);
262
+ const pick = (alt) => {
263
+ const ins = {};
264
+ let rows = p.rows;
265
+ for (const u of inputs) {
266
+ const o = optionsFor(rows, u, known), opts = unique(o.eqs.length ? o.eqs : [...o.bounds, {}]);
267
+ const ok = opts.filter(t => { const rs = rows.map(f => subst(f, { [u]: t })); return !rs.some(f => isConst(f) && (f['1'] ?? 0) > 0) && sat(rs); });
268
+ const from = ok.length ? ok : opts;
269
+ ins[u] = from[Math.min(alt, from.length - 1)];
270
+ rows = rows.map(f => subst(f, { [u]: ins[u] }));
271
+ }
272
+ return ins;
273
+ };
274
+ const out = new Map();
275
+ for (let a = 0; a < 3; a++) {
276
+ const x = pick(a);
277
+ out.set(JSON.stringify(x), x);
278
+ }
279
+ return [...out.values()];
280
+ }
281
+ // A path's inputs at the cycle's turn j with the constants left open: an equation's term where its rows give one, else
282
+ // u@j.
283
+ function symbolic(p, j, S, P) {
284
+ const ins = {};
285
+ let rows = p.rows;
286
+ const known = (x) => S.has(x) || P.has(x) || x.includes('@');
287
+ for (const u of inputsOf(p, S, P)) {
288
+ const o = optionsFor(rows, u, known);
289
+ ins[u] = o.eqs[0] ?? { [`${u}@${j}`]: 1 };
290
+ rows = rows.map(f => subst(f, { [u]: ins[u] }));
291
+ }
292
+ return ins;
293
+ }
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.
295
+ function compose(rel, steps, natState) {
296
+ let sigma = Object.fromEntries(rel.state.map(x => [x, { [x]: 1 }]));
297
+ 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;
314
+ if (Object.values(sigma).some(big) || rows.some(big))
315
+ return undefined;
316
+ }
317
+ return { rows: dedupe(rows.map(tight).filter(f => !(isConst(f) && (f['1'] ?? 0) <= 0))), post: sigma };
318
+ }
319
+ 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] }));
323
+ const whole = compose(rel, steps, natState);
324
+ if (!whole)
325
+ return undefined;
326
+ const G = whole.rows, U = whole.post;
327
+ if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || !sat(G))
328
+ return undefined;
329
+ // the differences of each atom of G along U, up to degree 3
330
+ const opt = [];
331
+ for (const g of G) {
332
+ let d = g;
333
+ for (let k = 1; k <= 3; k++) {
334
+ const next = plus(subst(d, U), d, -1);
335
+ if (isConst(next)) {
336
+ if ((next['1'] ?? 0) > 0)
337
+ return undefined;
338
+ break;
339
+ } // (a constant > 0: g grows past 0)
340
+ if (canon(next) === canon(d))
341
+ break;
342
+ opt.push(tight(next));
343
+ d = next;
344
+ }
345
+ }
346
+ // Houdini: G must be kept by U; a difference not kept is dropped
347
+ let R = dedupe([...G, ...opt]);
348
+ const must = new Set(G.map(canon));
349
+ for (let round = 0; round < 12; round++) {
350
+ if (late())
351
+ return undefined;
352
+ const bad = R.filter(a => !implied(R, subst(a, U)));
353
+ if (!bad.length)
354
+ break;
355
+ if (bad.some(a => must.has(canon(a))))
356
+ return undefined;
357
+ const drop = new Set(bad.map(canon));
358
+ R = R.filter(a => !drop.has(canon(a)));
359
+ }
360
+ if (R.some(a => !implied(R, subst(a, U))) || !sat(R))
361
+ return undefined;
362
+ // R without what the rest of it implies (a smaller goal for the kernel)
363
+ R = irredundant(R, late);
364
+ if (late())
365
+ return undefined;
366
+ // per turn j: R_j, the rest of the cycle from turn j allowed and ending in R
367
+ const Rs = steps.map((_, j) => {
368
+ if (j === 0)
369
+ return R;
370
+ 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);
372
+ });
373
+ if (late())
374
+ return undefined;
375
+ if (Rs.some(r => !sat(r)))
376
+ return undefined;
377
+ // as the loop's condition and witness
378
+ const intOf = (x) => rel.ints.get(x);
379
+ const term = (f) => {
380
+ let p = K(0), n = K(0);
381
+ const add = (e, k, to) => { const t = k === 1 ? e : { op: 'mul', k, a: e }; if (to === 'p')
382
+ p = isZ(p) ? t : { op: 'add', a: p, b: t };
383
+ else
384
+ n = isZ(n) ? t : { op: 'add', a: n, b: t }; };
385
+ for (const x of vars(f).sort()) {
386
+ const c = f[x], pair = intOf(x);
387
+ if (pair) {
388
+ add(V(pair[0]), Math.abs(c), c > 0 ? 'p' : 'n');
389
+ add(V(pair[1]), Math.abs(c), c > 0 ? 'n' : 'p');
390
+ }
391
+ else
392
+ add(V(x), Math.abs(c), c > 0 ? 'p' : 'n');
393
+ }
394
+ const k = f['1'] ?? 0;
395
+ if (k)
396
+ add(K(Math.abs(k)), 1, k > 0 ? 'p' : 'n');
397
+ return { p, n };
398
+ };
399
+ const atom = (f) => { const t = term(f); return { op: '<=', a: t.p, b: t.n }; };
400
+ 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));
407
+ const valueAt = (j, n) => {
408
+ const p = rel.paths[seq[j]];
409
+ if (n in p.pins)
410
+ return K(p.pins[n]);
411
+ const u = steps[j].ins;
412
+ for (const [x, pair] of rel.ints)
413
+ if (pair[0] === n || pair[1] === n) {
414
+ const t = u[x];
415
+ if (!t)
416
+ return K(0);
417
+ const v = term(t);
418
+ return pair[0] === n ? sub(v.p, v.n) : sub(v.n, v.p);
419
+ }
420
+ const t = u[n];
421
+ if (!t)
422
+ return K(0);
423
+ const v = term(t);
424
+ return sub(v.p, v.n);
425
+ };
426
+ const wit = {};
427
+ for (const n of l.inputs) {
428
+ const vals = seq.map((_, j) => valueAt(j, n)), keys = vals.map(v => JSON.stringify(v));
429
+ if (keys.every(k => k === keys[0])) {
430
+ wit[n] = vals[0];
431
+ continue;
432
+ }
433
+ // (the commonest value last, with no condition: a state of any part whose turn takes it matches no other's; a
434
+ // state matched by another part's condition is in that part, whose turn keeps it in the set too)
435
+ const tally = new Map();
436
+ for (const k of keys)
437
+ tally.set(k, (tally.get(k) ?? 0) + 1);
438
+ const common = [...tally].sort((a, b) => b[1] - a[1])[0][0];
439
+ let e = vals[keys.indexOf(common)];
440
+ for (let j = vals.length - 1; j >= 0; j--)
441
+ if (keys[j] !== common)
442
+ e = { op: 'if', c: conds[j], then: vals[j], else: e };
443
+ wit[n] = e;
444
+ }
445
+ return { set, wit, targets: Rs.map((rows, j) => ({ loc: from(seq[j]), rows })) };
446
+ }
447
+ const cmp = (a, b) => { for (let i = 0; i < a.length; i++)
448
+ if (a[i] !== b[i])
449
+ return a[i] - b[i]; return 0; };
450
+ const isZ = (e) => e.op === 'const' && e.value === 0;
451
+ const sub = (a, b) => (isZ(b) ? a : isZ(a) ? K(0) : { op: 'sub', a, b });
452
+ function irredundant(rows, late) {
453
+ let out = rows;
454
+ for (let i = out.length - 1; i >= 0 && !late(); i--) {
455
+ const rest = out.filter((_, j) => j !== i);
456
+ if (rest.length && implied(rest, out[i]))
457
+ out = rest;
458
+ }
459
+ return out;
460
+ }
461
+ // `report.exhausted`: the search ran to its end within its time and calls (no part reached within its depth), as opposed
462
+ // to not applying (a start it doesn't read linearly) or being cut short.
463
+ export function* stemsTo(l, targets, io, opts) {
464
+ const found = relOf(l);
465
+ if (!found)
466
+ return;
467
+ const rel = found;
468
+ const { now, until } = opts, depth = opts.depth ?? 8;
469
+ let calls = opts.calls ?? 400;
470
+ const S = rel.state, P = new Set(rel.params), Sset = new Set(S);
471
+ const natState = S.filter(x => !rel.ints.has(x));
472
+ // the params as integers (a pair x, x$n or x$neg is x − x$n), and the start's state over them
473
+ const pairOf = new Map(), paramInts = [];
474
+ for (const x of l.params)
475
+ for (const sfx of ['$n', '$neg'])
476
+ if (l.params.includes(x + sfx)) {
477
+ pairOf.set(x, [x, 1]);
478
+ pairOf.set(x + sfx, [x, -1]);
479
+ paramInts.push([x, x + sfx]);
480
+ }
481
+ for (const x of l.params)
482
+ if (!pairOf.has(x)) {
483
+ pairOf.set(x, [x, 1]);
484
+ paramInts.push([x, undefined]);
485
+ }
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
+ const toInts = (raw) => {
507
+ const o = konst(raw['1'] ?? 0), seen = new Map();
508
+ for (const r of vars(raw)) {
509
+ const q = pairOf.get(r);
510
+ if (!q)
511
+ return undefined;
512
+ const c = raw[r] * q[1];
513
+ if (seen.has(q[0]) && seen.get(q[0]) !== c)
514
+ return undefined;
515
+ seen.set(q[0], c);
516
+ }
517
+ for (const [x, c] of seen) {
518
+ const pair = paramInts.find(p => p[0] === x);
519
+ // (a pair read whole: both parts, opposite; one part alone is not the integer)
520
+ if (pair[1] && vars(raw).filter(r => pairOf.get(r)?.[0] === x).length !== 2)
521
+ return undefined;
522
+ o[x] = c;
523
+ }
524
+ return o;
525
+ };
526
+ const startOf = (x) => {
527
+ const pair = rel.ints.get(x);
528
+ if (!pair) {
529
+ const e = l.state[x];
530
+ const r = e && linRaw(e);
531
+ return r && toInts(r);
532
+ }
533
+ const ep = l.state[pair[0]], en = l.state[pair[1]];
534
+ if (!ep || !en)
535
+ return undefined;
536
+ 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);
538
+ return a && b && toInts(plus(a, b, -1));
539
+ }
540
+ const a = linRaw(ep), b = linRaw(en);
541
+ return a && b && toInts(plus(a, b, -1));
542
+ };
543
+ const sigma0 = {};
544
+ for (const x of S) {
545
+ const v = startOf(x);
546
+ if (!v)
547
+ return;
548
+ sigma0[x] = v;
549
+ }
550
+ const locE = rel.loc ? l.state[rel.loc] : undefined;
551
+ if (rel.loc && locE?.op !== 'const')
552
+ return;
553
+ const startLoc = locE?.op === 'const' ? locE.value : 0;
554
+ const from = (i) => (rel.loc ? rel.from[i] : 0), to = (i) => (rel.loc ? rel.to[i] : 0);
555
+ const loops = new Map();
556
+ rel.paths.forEach((p, i) => {
557
+ if (from(i) !== to(i))
558
+ return;
559
+ for (const ins of inputChoices(p, Sset, P)) {
560
+ const c = compose(rel, [{ path: i, ins }], natState);
561
+ if (!c)
562
+ continue;
563
+ const delta = {};
564
+ let ok = true;
565
+ for (const x of S) {
566
+ const d = plus(c.post[x], { [x]: 1 }, -1);
567
+ if (!isConst(d)) {
568
+ ok = false;
569
+ break;
570
+ }
571
+ if (d['1'])
572
+ delta[x] = d['1'];
573
+ }
574
+ if (ok && Object.keys(delta).length) {
575
+ loops.set(from(i), [...(loops.get(from(i)) ?? []), { path: i, ins, delta }]);
576
+ break;
577
+ }
578
+ }
579
+ });
580
+ const natParams = paramInts.filter(p => !p[1]).map(p => p[0]);
581
+ const solveRows = (rows) => { calls--; return solve(rows.map(lin => ({ lin, label: '' })), 3000); };
582
+ const evalLin = (f, env, w) => {
583
+ let v = f['1'] ?? 0;
584
+ for (const x of vars(f)) {
585
+ const pair = rel.ints.get(x);
586
+ v += f[x] * (x.includes('@') ? (w[x] ?? 0) : pair ? (env[pair[0]] ?? 0) - (env[pair[1]] ?? 0) : (env[x] ?? 0));
587
+ }
588
+ return v;
589
+ };
590
+ const rawInput = (p, ins, env, w) => {
591
+ const out = {};
592
+ for (const n of l.inputs)
593
+ out[n] = 0;
594
+ for (const [u, t] of Object.entries(ins)) {
595
+ const v = Math.round(evalLin(t, env, w)), pair = rel.ints.get(u);
596
+ if (pair) {
597
+ out[pair[0]] = Math.max(v, 0);
598
+ out[pair[1]] = Math.max(-v, 0);
599
+ }
600
+ else
601
+ out[u] = Math.max(v, 0);
602
+ }
603
+ for (const [n, v] of Object.entries(p.pins))
604
+ if (l.inputs.includes(n))
605
+ out[n] = v;
606
+ return out;
607
+ };
608
+ const concrete = (segs, w) => {
609
+ const params = {};
610
+ for (const [x, neg] of paramInts) {
611
+ const v = Math.round(w[x] ?? 0);
612
+ if (neg) {
613
+ params[x] = Math.max(v, 0);
614
+ params[neg] = Math.max(-v, 0);
615
+ }
616
+ else
617
+ params[x] = Math.max(v, 0);
618
+ }
619
+ let st = io.start(params);
620
+ const stem = [];
621
+ let left = 200_000;
622
+ for (const s of segs) {
623
+ const times = s.n ? Math.round(w[s.n] ?? 1) : 1;
624
+ if (times > 100_000)
625
+ return undefined;
626
+ for (let k = 0; k < times; k++) {
627
+ if (--left < 0)
628
+ return undefined;
629
+ const input = rawInput(rel.paths[s.path], s.ins, st, w), nx = io.turn(st, input);
630
+ if (!nx)
631
+ return undefined;
632
+ stem.push(input);
633
+ st = nx;
634
+ }
635
+ }
636
+ return { params, stem };
637
+ };
638
+ const base = natParams.map(x => ({ [x]: -1 }));
639
+ // each location's distance (in turns) to a part of the set: the search goes nearest first, and no further than the
640
+ // depth allows
641
+ const dist = new Map(targets.map(t => [t.loc, 0]));
642
+ for (let changed = true; changed;) {
643
+ changed = false;
644
+ for (let i = 0; i < rel.paths.length; i++) {
645
+ const d = dist.get(to(i));
646
+ if (d !== undefined && (dist.get(from(i)) ?? Infinity) > d + 1) {
647
+ dist.set(from(i), d + 1);
648
+ changed = true;
649
+ }
650
+ }
651
+ }
652
+ if (!dist.has(startLoc)) {
653
+ if (opts.report)
654
+ opts.report.exhausted = true;
655
+ return;
656
+ }
657
+ const maxDepth = Math.max(depth, dist.get(startLoc) + depth);
658
+ const outs = new Map();
659
+ for (let i = 0; i < rel.paths.length; i++)
660
+ if (dist.has(to(i)))
661
+ outs.set(from(i), [...(outs.get(from(i)) ?? []), i]);
662
+ for (const xs of outs.values())
663
+ xs.sort((a, b) => dist.get(to(a)) - dist.get(to(b)));
664
+ function* dfs(loc, sigma, rows, segs, k, lastLoop) {
665
+ if (calls <= 0 || now() > until)
666
+ return;
667
+ for (const t of targets)
668
+ if (t.loc === loc) {
669
+ const m = solveRows([...rows, ...t.rows.map(f => subst(f, sigma))]);
670
+ if (m.kind === 'sat') {
671
+ const c = concrete(segs, m.witness);
672
+ if (c)
673
+ yield c;
674
+ }
675
+ }
676
+ if (segs.length + (dist.get(loc) ?? Infinity) > maxDepth)
677
+ return;
678
+ 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 };
694
+ };
695
+ // a self-loop accelerated, then each path out
696
+ if (!lastLoop)
697
+ for (const lp of loops.get(loc) ?? []) {
698
+ const name = `n@${k}`, { rs, post } = step(lp.path, lp.ins, { name, delta: lp.delta });
699
+ const all = [...rows, ...rs];
700
+ if (solveRows(all).kind === 'refuted')
701
+ continue;
702
+ yield* dfs(loc, post, all, [...segs, { path: lp.path, ins: lp.ins, n: name }], k + 1, true);
703
+ }
704
+ for (const i of outs.get(loc) ?? []) {
705
+ if (segs.length + 1 + dist.get(to(i)) > maxDepth)
706
+ continue;
707
+ const p = rel.paths[i], ins = {};
708
+ for (const [u, t] of Object.entries(symbolic(p, k, Sset, P)))
709
+ ins[u] = Object.fromEntries(Object.entries(t).map(([x, c]) => [x.includes('@') ? x.replace(/@\d+$/, `@${k}`) : x, c]));
710
+ const { rs, post } = step(i, ins);
711
+ const all = [...rows, ...rs];
712
+ if (all.some(big) || solveRows(all).kind === 'refuted')
713
+ continue;
714
+ yield* dfs(to(i), post, all, [...segs, { path: i, ins }], k + 1, false);
715
+ }
716
+ }
717
+ yield* dfs(startLoc, sigma0, [...base], [], 0, false);
718
+ if (opts.report && calls > 0 && now() <= until)
719
+ opts.report.exhausted = true;
720
+ }