gdp-wired 0.24.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -9
- package/dist/core/accel.d.ts +44 -0
- package/dist/core/accel.js +955 -0
- package/dist/core/bmc.d.ts +8 -0
- package/dist/core/bmc.js +263 -97
- package/dist/core/cycles.d.ts +2 -3
- package/dist/core/cycles.js +409 -174
- package/dist/core/cyclic.d.ts +4 -1
- package/dist/core/cyclic.js +86 -64
- package/dist/core/data.d.ts +9 -1
- package/dist/core/data.js +872 -168
- package/dist/core/discover.js +2 -3
- package/dist/core/dsl.d.ts +3 -2
- package/dist/core/dsl.js +21 -18
- package/dist/core/exists.js +7 -14
- package/dist/core/extract-check.d.ts +3 -2
- package/dist/core/extract-check.js +137 -50
- package/dist/core/extract-print.d.ts +1 -0
- package/dist/core/extract-print.js +26 -3
- package/dist/core/extract-read.d.ts +85 -4
- package/dist/core/extract-read.js +295 -34
- package/dist/core/extract-shapes.d.ts +14 -0
- package/dist/core/extract-shapes.js +608 -78
- package/dist/core/extract-xstate.d.ts +5 -1
- package/dist/core/extract-xstate.js +618 -184
- package/dist/core/extract.js +73 -27
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +364 -40
- package/dist/core/machine.d.ts +6 -0
- package/dist/core/machine.js +35 -3
- package/dist/core/nonterm.d.ts +9 -2
- package/dist/core/nonterm.js +173 -9
- package/dist/core/q.d.ts +1 -0
- package/dist/core/q.js +2 -2
- package/dist/core/relation.d.ts +1 -0
- package/dist/core/relation.js +95 -39
- package/dist/core/solver.d.ts +12 -0
- package/dist/core/solver.js +76 -30
- package/dist/core/transfer.js +23 -14
- package/dist/core/translate.d.ts +1 -1
- package/dist/core/translate.js +22 -49
- package/dist/core/xstate.d.ts +6 -1
- package/dist/core/xstate.js +336 -55
- package/dist/kernel/cdcl.d.ts +5 -0
- package/dist/kernel/cdcl.js +44 -8
- package/dist/kernel/prove.d.ts +6 -1
- package/dist/kernel/prove.js +101 -85
- package/dist/kernel/reader.d.ts +1 -0
- package/dist/kernel/reader.js +4 -3
- package/dist/kernel/simplex.d.ts +1 -1
- package/dist/kernel/simplex.js +13 -1
- package/package.json +3 -2
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
// Accelerated cycles: recurrent sets from a loop's relation, not its runs, and stems into them from runs whose loops are
|
|
2
|
+
// taken n times at once. Untrusted, like core/nonterm.ts, whose search calls this: what is found here is a candidate
|
|
3
|
+
// set, its witness and a stem, and the kernel proves the set closed and the stem into it (kernel.ts's checkRecur,
|
|
4
|
+
// NonTerm.lean's never_ends_of).
|
|
5
|
+
//
|
|
6
|
+
// - Cycles. The relation's paths (core/relation.ts: one turn as linear paths, each from a location to a location) as a
|
|
7
|
+
// graph; its closed walks (a location may come twice: x > 0 and x < 0 taken in turn), each by its least rotation, by
|
|
8
|
+
// how many choices they make among a location's paths (at most `maxLen`; a chain of locations with one path out, as a
|
|
9
|
+
// translated program's straight-line code, costs nothing) and at most 64 turns, a walk cut where its rows (each turn's
|
|
10
|
+
// inputs left open) are refuted; a self-loop also twice over (a period of two: x := −x). Then the cycles the random
|
|
11
|
+
// runs take, between two visits of a location, the commonest first.
|
|
12
|
+
// - A turn's inputs as terms of the state before it: a value a row pins (an equation in it), else a bound a row puts on
|
|
13
|
+
// it (x < i0 gives i0 := x + 1, i0 >= 3 gives 3), else 0; or constants from a model of two rounds of the cycle. The
|
|
14
|
+
// cycle is then one linear loop: its guard G (each turn's rows, read at the state the turns before it leave) and its
|
|
15
|
+
// update U (affine in the state at the cycle's start).
|
|
16
|
+
// - Its n-fold run in closed form: an atom g ≤ 0 of G holds after every number n of turns where its value along the
|
|
17
|
+
// run, g(Uⁿx), a polynomial in n for a translation or a triangular update (the differences core/discover.ts's
|
|
18
|
+
// closedForm fits), has its differences at n = 0 all ≤ 0: Δ⁰g = g, Δ^{k+1}g = Δ^k g∘U − Δ^k g, each linear in x
|
|
19
|
+
// (Σ C(n, k)·Δ^k g is g(Uⁿx)). For a geometric update (x := 2x) the differences repeat (Δ²g = Δ¹g) and the same set
|
|
20
|
+
// holds. So the set R is G with each atom's differences up to degree 3, and Houdini drops a difference that isn't kept
|
|
21
|
+
// by U (G's atoms are kept or the cycle is given up): R ∧ ¬a(Ux) refuted for each atom a, by the integer solver
|
|
22
|
+
// (core/solver.ts). A constant difference above 0 gives the cycle up at once: g grows past 0.
|
|
23
|
+
// - The set of the loop: per turn j of the cycle, at its location, the states from which the rest of the cycle's turns
|
|
24
|
+
// are allowed and end in R (R_j, the weakest precondition: the rest composed); the witness by location, or by R_j
|
|
25
|
+
// where the cycle passes a location twice, its commonest value with no condition.
|
|
26
|
+
// - Stems (`stemsTo`): from the start's location to a part's, a path at a time or a self-loop that is a translation
|
|
27
|
+
// taken n times at once, all linear, then run on the loop itself.
|
|
28
|
+
import { n as K, x as V } from "./machine.js";
|
|
29
|
+
import { relationOf } from "./relation.js";
|
|
30
|
+
import { canon, gcd, konst, linOfE, plus, solve, subst, times, vars } from "./solver.js";
|
|
31
|
+
const isConst = (l) => vars(l).length === 0;
|
|
32
|
+
// (a row's coefficients divided by their common divisor, its constant rounded up: an integer row as tight as it goes)
|
|
33
|
+
const tight = (l) => {
|
|
34
|
+
const g = vars(l).reduce((s, x) => gcd(s, l[x]), 0);
|
|
35
|
+
if (g <= 1)
|
|
36
|
+
return l;
|
|
37
|
+
const o = {};
|
|
38
|
+
for (const x of vars(l))
|
|
39
|
+
o[x] = l[x] / g;
|
|
40
|
+
const c = Math.ceil((l['1'] ?? 0) / g);
|
|
41
|
+
if (c)
|
|
42
|
+
o['1'] = c;
|
|
43
|
+
return o;
|
|
44
|
+
};
|
|
45
|
+
const big = (l) => Object.values(l).some(c => !Number.isSafeInteger(c) || Math.abs(c) > 2 ** 40);
|
|
46
|
+
// rows lin <= 0 satisfiable over the integers (unknown counts as satisfiable: the kernel decides later)
|
|
47
|
+
const sat = (rows) => solve(rows.map(lin => ({ lin, label: '' })), 3000).kind !== 'refuted';
|
|
48
|
+
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).
|
|
50
|
+
export function* accelerated(l, opts) {
|
|
51
|
+
const rel = relOf(l);
|
|
52
|
+
if (!rel)
|
|
53
|
+
return;
|
|
54
|
+
const { now, until } = opts, maxLen = opts.maxLen ?? 6;
|
|
55
|
+
const S = rel.state, P = new Set(rel.params), Sset = new Set(S);
|
|
56
|
+
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
|
+
// Each path's inputs as terms of the state before it (a few choices each, the first the likeliest).
|
|
59
|
+
const choices = rel.paths.map(p => inputChoices(p, Sset, P));
|
|
60
|
+
// The cycles: closed walks of paths (a location may come twice: two turns at one location, taken in turn), each once
|
|
61
|
+
// (its least rotation), with at most `maxLen` choices among a location's paths (a chain of locations with one path out,
|
|
62
|
+
// 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;
|
|
106
|
+
}
|
|
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)))
|
|
140
|
+
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];
|
|
154
|
+
}
|
|
155
|
+
nodes--;
|
|
156
|
+
if (!rws.some(big) && sat(rws))
|
|
157
|
+
walk([...seq, ...Array.from({ length: r }, () => j)], at, c, sg, rws, j);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
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);
|
|
165
|
+
}
|
|
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)];
|
|
169
|
+
// the runs' cycles: between two visits of a location, the paths taken (as their least rotation), by how often; after
|
|
170
|
+
// the enumerated ones of at most 4 turns (at most 20,000 turns read)
|
|
171
|
+
if (opts.runs && opts.io) {
|
|
172
|
+
const count = new Map();
|
|
173
|
+
const byLoc = new Map();
|
|
174
|
+
rel.paths.forEach((_, i) => { byLoc.set(from(i), [...(byLoc.get(from(i)) ?? []), i]); });
|
|
175
|
+
let budget = 20_000;
|
|
176
|
+
for (const r of opts.runs) {
|
|
177
|
+
if (now() > until || budget <= 0)
|
|
178
|
+
break;
|
|
179
|
+
let st = opts.io.start(r.params);
|
|
180
|
+
const seq = [];
|
|
181
|
+
for (const input of r.inputs.slice(0, Math.min(budget, 1000))) {
|
|
182
|
+
budget--;
|
|
183
|
+
const i = pathAt(rel, byLoc.get(rel.loc ? st[rel.loc] ?? 0 : 0) ?? [], st, input);
|
|
184
|
+
if (i === undefined)
|
|
185
|
+
break;
|
|
186
|
+
seq.push(i);
|
|
187
|
+
const nx = opts.io.turn(st, input);
|
|
188
|
+
if (!nx)
|
|
189
|
+
break;
|
|
190
|
+
st = nx;
|
|
191
|
+
}
|
|
192
|
+
const next = new Map();
|
|
193
|
+
for (let k = seq.length - 1; k >= 0; k--) {
|
|
194
|
+
const j = next.get(from(seq[k]));
|
|
195
|
+
next.set(from(seq[k]), k);
|
|
196
|
+
if (j === undefined || j - k > 64)
|
|
197
|
+
continue;
|
|
198
|
+
const c = seq.slice(k, j);
|
|
199
|
+
const r0 = c.map((_, q) => [...c.slice(q), ...c.slice(0, q)]).sort(cmp)[0], key = r0.join(',');
|
|
200
|
+
const e = count.get(key);
|
|
201
|
+
if (e)
|
|
202
|
+
e.n++;
|
|
203
|
+
else
|
|
204
|
+
count.set(key, { seq: r0, n: 1 });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const fromRuns = [...count.values()].sort((a, b) => b.n - a.n || a.seq.length - b.seq.length).slice(0, 60).map(e => e.seq);
|
|
208
|
+
const keys = new Set(fromRuns.map(c => c.join(','))), short = cycles.filter(c => c.length <= 4);
|
|
209
|
+
const shortKeys = new Set(short.map(c => c.join(',')));
|
|
210
|
+
cycles = [...short, ...fromRuns.filter(c => !shortKeys.has(c.join(','))), ...cycles.filter(c => c.length > 4 && !keys.has(c.join(',')))];
|
|
211
|
+
}
|
|
212
|
+
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))])))]))));
|
|
230
|
+
}
|
|
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) };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
// The path a turn takes: its pins (the location, the rule) and its rows hold at the state and the turn's inputs.
|
|
249
|
+
function pathAt(rel, among, st, input) {
|
|
250
|
+
const at = { ...st, ...input };
|
|
251
|
+
const value = (x) => { if (isPi(x))
|
|
252
|
+
return piValue(rel, x, at); const pair = rel.ints.get(x); return pair ? (at[pair[0]] ?? 0) - (at[pair[1]] ?? 0) : (at[x] ?? 0); };
|
|
253
|
+
for (const i of among) {
|
|
254
|
+
const p = rel.paths[i];
|
|
255
|
+
if (Object.entries(p.pins).some(([n, v]) => !n.endsWith('′') && n in at && at[n] !== v))
|
|
256
|
+
continue;
|
|
257
|
+
if (p.rows.every(f => vars(f).reduce((s, x) => s + f[x] * value(x), f['1'] ?? 0) <= 0))
|
|
258
|
+
return i;
|
|
259
|
+
}
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
const rels = new WeakMap();
|
|
263
|
+
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);
|
|
271
|
+
if (r && !r.exact) {
|
|
272
|
+
const known = new Set([...l.params, ...Object.keys(l.state)]);
|
|
273
|
+
const ok = (x) => !isPi(x) || piParts(x)?.every(f => vars(f).every(n => known.has(n))) === true;
|
|
274
|
+
const keep = r.paths.map(p => [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].every(ok));
|
|
275
|
+
r = { ...r, paths: r.paths.filter((_, i) => keep[i]), from: r.from.filter((_, i) => keep[i]), to: r.to.filter((_, i) => keep[i]) };
|
|
276
|
+
}
|
|
277
|
+
const out = r && r.paths.length ? r : undefined;
|
|
278
|
+
rels.set(l, out);
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
// --- products ---------------------------------------------------------------------------------------------------------
|
|
282
|
+
//
|
|
283
|
+
// A product the relation names π(a·b) (core/relation.ts: two of the loop's naturals, each one value or a part of an
|
|
284
|
+
// integer's pair) is, where the set decides the sign of each integer it reads, ±X·Y over the relation's integers, or 0
|
|
285
|
+
// (a pair's other part). Its facts are those of X·Y from the set's bounds on X and Y (McCormick's: (X − l)(Y − m) ≥ 0
|
|
286
|
+
// for lower bounds l, m, and likewise for the upper ones; a square's tangents (X − c)² ≥ 0), linear in the product's
|
|
287
|
+
// name: what a Houdini check of the set needs to keep x := x·y.
|
|
288
|
+
const isPi = (x) => x.startsWith('π(');
|
|
289
|
+
// (the two factors, linear in the loop's names)
|
|
290
|
+
const piParts = (x) => {
|
|
291
|
+
const m = /^π\((.*)·(.*)\)(#\d+)?$/.exec(x);
|
|
292
|
+
if (!m)
|
|
293
|
+
return undefined;
|
|
294
|
+
try {
|
|
295
|
+
return [JSON.parse(m[1]), JSON.parse(m[2])];
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
const piSeen = new WeakMap();
|
|
302
|
+
const readsPi = (p) => { let out = piSeen.get(p); if (out === undefined)
|
|
303
|
+
piSeen.set(p, (out = [...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)].some(isPi))); return out; };
|
|
304
|
+
// (a turn's products named for the turn: values of their own, as the search over several turns reads them)
|
|
305
|
+
const fresh = (l, k) => { if (!vars(l).some(isPi))
|
|
306
|
+
return l; const o = {}; for (const x in l)
|
|
307
|
+
o[isPi(x) ? `${x}#${k}` : x] = l[x]; return o; };
|
|
308
|
+
const freshPath = (p, k) => (readsPi(p) ? { ...p, rows: p.rows.map(f => fresh(f, k)), post: Object.fromEntries(Object.entries(p.post).map(([x, f]) => [x, fresh(f, k)])) } : p);
|
|
309
|
+
// A product's value in a run (its factors' raw values multiplied).
|
|
310
|
+
const piValue = (rel, x, at) => {
|
|
311
|
+
const ev = (f) => vars(f).reduce((acc, n) => acc + f[n] * (at[n] ?? 0), f['1'] ?? 0);
|
|
312
|
+
const raw = (n) => { const fs = piParts(n); return fs ? ev(fs[0]) * ev(fs[1]) : at[n] ?? 0; };
|
|
313
|
+
const pair = rel.ints.get(x);
|
|
314
|
+
return pair ? raw(pair[0]) - raw(pair[1]) : raw(x);
|
|
315
|
+
};
|
|
316
|
+
// The bounds the rows put on one integer each.
|
|
317
|
+
function boundsOf(R) {
|
|
318
|
+
const out = new Map();
|
|
319
|
+
for (const f of R) {
|
|
320
|
+
const xs = vars(f);
|
|
321
|
+
if (xs.length !== 1)
|
|
322
|
+
continue;
|
|
323
|
+
const x = xs[0], a = f[x], b = f['1'] ?? 0, e = out.get(x) ?? {};
|
|
324
|
+
if (a > 0)
|
|
325
|
+
e.hi = Math.min(e.hi ?? Infinity, Math.floor(-b / a));
|
|
326
|
+
else
|
|
327
|
+
e.lo = Math.max(e.lo ?? -Infinity, Math.ceil(-b / a));
|
|
328
|
+
out.set(x, e);
|
|
329
|
+
}
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
332
|
+
// The facts of the products among `names`, given the set's rows R.
|
|
333
|
+
function piFacts(rel, R, names) {
|
|
334
|
+
const pis = [...new Set(names.filter(isPi))];
|
|
335
|
+
if (!pis.length)
|
|
336
|
+
return [];
|
|
337
|
+
const bounds = boundsOf(R), sign = (X) => { const b = bounds.get(X); return b?.lo !== undefined && b.lo >= 0 ? 1 : b?.hi !== undefined && b.hi <= 0 ? -1 : 0; };
|
|
338
|
+
const partOf = new Map();
|
|
339
|
+
for (const [X, [p, n]] of rel.ints) {
|
|
340
|
+
partOf.set(p, [X, 1]);
|
|
341
|
+
partOf.set(n, [X, -1]);
|
|
342
|
+
}
|
|
343
|
+
// a raw factor over the relation's names (a part of an integer's pair ±X, or 0, where the bounds decide its sign), at
|
|
344
|
+
// most one name in it
|
|
345
|
+
const factor = (f) => {
|
|
346
|
+
let o = konst(f['1'] ?? 0);
|
|
347
|
+
for (const r of vars(f)) {
|
|
348
|
+
const q = partOf.get(r);
|
|
349
|
+
if (!q) {
|
|
350
|
+
o = plus(o, { [r]: f[r] });
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const s = sign(q[0]);
|
|
354
|
+
if (!s)
|
|
355
|
+
return undefined;
|
|
356
|
+
if (s === q[1])
|
|
357
|
+
o = plus(o, { [q[0]]: f[r] * q[1] });
|
|
358
|
+
}
|
|
359
|
+
return vars(o).length <= 1 ? o : undefined;
|
|
360
|
+
};
|
|
361
|
+
const out = [];
|
|
362
|
+
for (const N of pis) {
|
|
363
|
+
const pair = rel.ints.get(N), terms = pair ? [[pair[0], 1], [pair[1], -1]] : [[N, 1]];
|
|
364
|
+
// N = lin + Σ c·X·Y, by product
|
|
365
|
+
const prods = new Map();
|
|
366
|
+
let lin = {}, ok = true;
|
|
367
|
+
for (const [raw, c0] of terms) {
|
|
368
|
+
const fs = piParts(raw), a = fs && factor(fs[0]), b = fs && factor(fs[1]);
|
|
369
|
+
if (!a || !b) {
|
|
370
|
+
ok = false;
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
const ka = a['1'] ?? 0, kb = b['1'] ?? 0, xa = vars(a)[0], xb = vars(b)[0];
|
|
374
|
+
lin = plus(lin, konst(c0 * ka * kb));
|
|
375
|
+
if (xb)
|
|
376
|
+
lin = plus(lin, { [xb]: c0 * ka * b[xb] });
|
|
377
|
+
if (xa)
|
|
378
|
+
lin = plus(lin, { [xa]: c0 * kb * a[xa] });
|
|
379
|
+
if (xa && xb) {
|
|
380
|
+
const [X, Y] = [xa, xb].sort(), key = `${X}*${Y}`, e = prods.get(key) ?? { X, Y, c: 0 };
|
|
381
|
+
e.c += c0 * a[xa] * b[xb];
|
|
382
|
+
prods.set(key, e);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const live = [...prods.values()].filter(e => e.c);
|
|
386
|
+
if (!ok || live.length > 1)
|
|
387
|
+
continue;
|
|
388
|
+
if (!live.length) {
|
|
389
|
+
out.push(plus({ [N]: 1 }, lin, -1), plus(lin, { [N]: 1 }, -1));
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
const { X, Y, c } = live[0];
|
|
393
|
+
if (Math.abs(c) !== 1)
|
|
394
|
+
continue;
|
|
395
|
+
// rows over p = X·Y, then p := c·N
|
|
396
|
+
const rows = [], bx = bounds.get(X) ?? {}, by = bounds.get(Y) ?? {};
|
|
397
|
+
const lower = (u, v) => rows.push({ [X]: v, [Y]: u, 1: -u * v, p: -1 }); // p ≥ v·X + u·Y − u·v: (X − u)(Y − v) ≥ 0
|
|
398
|
+
const upper = (u, v) => rows.push({ [X]: -v, [Y]: -u, 1: u * v, p: 1 }); // p ≤ v·X + u·Y − u·v: (X − u)(v − Y) ≥ 0 read with u a lower, v an upper bound
|
|
399
|
+
if (X === Y) {
|
|
400
|
+
rows.push({ p: -1 });
|
|
401
|
+
for (const b of [bx.lo, bx.hi])
|
|
402
|
+
if (b !== undefined && Number.isFinite(b))
|
|
403
|
+
rows.push({ [X]: 2 * b, 1: -b * b, p: -1 });
|
|
404
|
+
}
|
|
405
|
+
else {
|
|
406
|
+
if (bx.lo !== undefined && by.lo !== undefined)
|
|
407
|
+
lower(bx.lo, by.lo);
|
|
408
|
+
if (bx.hi !== undefined && by.hi !== undefined)
|
|
409
|
+
lower(bx.hi, by.hi);
|
|
410
|
+
if (bx.lo !== undefined && by.hi !== undefined)
|
|
411
|
+
upper(bx.lo, by.hi);
|
|
412
|
+
if (bx.hi !== undefined && by.lo !== undefined)
|
|
413
|
+
rows.push({ [X]: -by.lo, [Y]: -bx.hi, 1: bx.hi * by.lo, p: 1 });
|
|
414
|
+
}
|
|
415
|
+
// (p = c·(N − lin))
|
|
416
|
+
for (const f of rows) {
|
|
417
|
+
const rest = {};
|
|
418
|
+
for (const x in f)
|
|
419
|
+
if (x !== 'p')
|
|
420
|
+
rest[x] = f[x];
|
|
421
|
+
const o = plus(rest, plus({ [N]: 1 }, lin, -1), f.p * c);
|
|
422
|
+
if (!Object.values(o).some(v => !Number.isFinite(v)))
|
|
423
|
+
out.push(o);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return out;
|
|
427
|
+
}
|
|
428
|
+
function inputsOf(p, S, P) {
|
|
429
|
+
const read = [...new Set([...p.rows.flatMap(vars), ...Object.values(p.post).flatMap(vars)])];
|
|
430
|
+
return read.filter(x => !S.has(x) && !P.has(x) && !isPi(x)).sort();
|
|
431
|
+
}
|
|
432
|
+
// The terms a path's rows suggest for u: an equation (rows f and −f, u's coefficient ±1) over known names, else the
|
|
433
|
+
// bounds a row puts on u (a constant rounded inward, or a term where u's coefficient is ±1).
|
|
434
|
+
function optionsFor(rows, u, known) {
|
|
435
|
+
const eqs = [], lows = [], highs = [];
|
|
436
|
+
const keys = new Set(rows.map(canon));
|
|
437
|
+
for (const f of rows) {
|
|
438
|
+
const c = f[u];
|
|
439
|
+
if (c === undefined)
|
|
440
|
+
continue;
|
|
441
|
+
const rest = plus(f, { [u]: c }, -1);
|
|
442
|
+
if (!vars(rest).every(known))
|
|
443
|
+
continue;
|
|
444
|
+
if (Math.abs(c) === 1 && keys.has(canon(times(f, -1)))) {
|
|
445
|
+
eqs.push(times(rest, -1 / c));
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (isConst(rest)) {
|
|
449
|
+
const b = -(rest['1'] ?? 0) / c;
|
|
450
|
+
(c < 0 ? lows : highs).push(konst(c < 0 ? Math.ceil(b) : Math.floor(b)));
|
|
451
|
+
}
|
|
452
|
+
else if (Math.abs(c) === 1)
|
|
453
|
+
(c < 0 ? lows : highs).push(times(rest, -1 / c));
|
|
454
|
+
}
|
|
455
|
+
return { eqs, bounds: [...lows, ...highs] };
|
|
456
|
+
}
|
|
457
|
+
const unique = (ls) => [...new Map(ls.map(t => [canon(t), t])).values()];
|
|
458
|
+
// 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
|
|
459
|
+
// satisfiable (each input read with those chosen before it put in).
|
|
460
|
+
function inputChoices(p, S, P) {
|
|
461
|
+
const inputs = inputsOf(p, S, P);
|
|
462
|
+
if (!inputs.length)
|
|
463
|
+
return [{}];
|
|
464
|
+
const known = (x) => S.has(x) || P.has(x);
|
|
465
|
+
const pick = (alt) => {
|
|
466
|
+
const ins = {};
|
|
467
|
+
let rows = p.rows;
|
|
468
|
+
for (const u of inputs) {
|
|
469
|
+
const o = optionsFor(rows, u, known), opts = unique(o.eqs.length ? o.eqs : [...o.bounds, {}]);
|
|
470
|
+
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); });
|
|
471
|
+
const from = ok.length ? ok : opts;
|
|
472
|
+
ins[u] = from[Math.min(alt, from.length - 1)];
|
|
473
|
+
rows = rows.map(f => subst(f, { [u]: ins[u] }));
|
|
474
|
+
}
|
|
475
|
+
return ins;
|
|
476
|
+
};
|
|
477
|
+
const out = new Map();
|
|
478
|
+
for (let a = 0; a < 3; a++) {
|
|
479
|
+
const x = pick(a);
|
|
480
|
+
out.set(JSON.stringify(x), x);
|
|
481
|
+
}
|
|
482
|
+
return [...out.values()];
|
|
483
|
+
}
|
|
484
|
+
// 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
|
|
485
|
+
// u@j.
|
|
486
|
+
function symbolic(p, j, S, P) {
|
|
487
|
+
const ins = {};
|
|
488
|
+
let rows = p.rows;
|
|
489
|
+
const known = (x) => S.has(x) || P.has(x) || x.includes('@');
|
|
490
|
+
for (const u of inputsOf(p, S, P)) {
|
|
491
|
+
const o = optionsFor(rows, u, known);
|
|
492
|
+
ins[u] = o.eqs[0] ?? { [`${u}@${j}`]: 1 };
|
|
493
|
+
rows = rows.map(f => subst(f, { [u]: ins[u] }));
|
|
494
|
+
}
|
|
495
|
+
return ins;
|
|
496
|
+
}
|
|
497
|
+
// A turn of path i from the state sigma (each state name's form), its inputs' forms over the turn's start: its rows (a
|
|
498
|
+
// natural's term a natural), and the state after; with `k`, the turn's products named for the turn k (`freshPath`).
|
|
499
|
+
function turn(rel, natState, i, sigma, ins, k) {
|
|
500
|
+
const p = k === undefined ? rel.paths[i] : freshPath(rel.paths[i], k), insAt = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, sigma)])), sub = { ...sigma, ...insAt };
|
|
501
|
+
return { rs: [...p.rows.map(f => subst(f, sub)), ...natState.map(x => times(sigma[x], -1)), ...Object.keys(insAt).filter(u => !rel.ints.has(u)).map(u => times(insAt[u], -1))],
|
|
502
|
+
post: Object.fromEntries(rel.state.map(x => [x, subst(p.post[x] ?? { [x]: 1 }, sub)])) };
|
|
503
|
+
}
|
|
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.
|
|
505
|
+
function compose(rel, steps, natState) {
|
|
506
|
+
let sigma = Object.fromEntries(rel.state.map(x => [x, { [x]: 1 }]));
|
|
507
|
+
const rows = [];
|
|
508
|
+
for (const [j, s] of steps.entries()) {
|
|
509
|
+
if (j > 0 && readsPi(rel.paths[s.path]))
|
|
510
|
+
return undefined;
|
|
511
|
+
const t = turn(rel, natState, s.path, sigma, s.ins);
|
|
512
|
+
rows.push(...t.rs);
|
|
513
|
+
sigma = t.post;
|
|
514
|
+
if (Object.values(sigma).some(big) || rows.some(big))
|
|
515
|
+
return undefined;
|
|
516
|
+
}
|
|
517
|
+
return { rows: dedupe(rows.map(tight).filter(f => !(isConst(f) && (f['1'] ?? 0) <= 0))), post: sigma };
|
|
518
|
+
}
|
|
519
|
+
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] }));
|
|
523
|
+
const whole = compose(rel, steps, natState);
|
|
524
|
+
if (!whole)
|
|
525
|
+
return undefined;
|
|
526
|
+
const G = whole.rows, U = whole.post;
|
|
527
|
+
if (G.some(f => isConst(f) && (f['1'] ?? 0) > 0) || G.some(f => vars(f).some(isPi)) || !sat(G))
|
|
528
|
+
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)
|
|
530
|
+
const opt = [];
|
|
531
|
+
for (const g of G) {
|
|
532
|
+
let d = g;
|
|
533
|
+
for (let k = 1; k <= 3; k++) {
|
|
534
|
+
const next = plus(subst(d, U), d, -1);
|
|
535
|
+
if (vars(next).some(isPi))
|
|
536
|
+
break;
|
|
537
|
+
if (isConst(next)) {
|
|
538
|
+
if ((next['1'] ?? 0) > 0)
|
|
539
|
+
return undefined;
|
|
540
|
+
break;
|
|
541
|
+
} // (a constant > 0: g grows past 0)
|
|
542
|
+
if (canon(next) === canon(d))
|
|
543
|
+
break;
|
|
544
|
+
opt.push(tight(next));
|
|
545
|
+
d = next;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// A product in U (x := x·y): an atom is kept where R and the product's facts imply it after U; and bounds on each
|
|
549
|
+
// factor, x ≥ c for c up to 32 (x ≤ −c where G puts x below 0), which the product's facts read, are among the atoms
|
|
550
|
+
// Houdini tries (complInterv's x ≥ 4 for y := (x + 1)² > 9), the weakest that does kept.
|
|
551
|
+
const piU = [...new Set(Object.values(U).flatMap(vars).filter(isPi))];
|
|
552
|
+
const keeps = (rs, a) => { const after = subst(a, U); return implied(piU.length ? [...rs, ...piFacts(rel, rs, vars(after))] : rs, after); };
|
|
553
|
+
const pool = [];
|
|
554
|
+
if (piU.length) {
|
|
555
|
+
const partOf = new Map();
|
|
556
|
+
for (const [X, [p, n]] of rel.ints) {
|
|
557
|
+
partOf.set(p, X);
|
|
558
|
+
partOf.set(n, X);
|
|
559
|
+
}
|
|
560
|
+
const xs = [...new Set(piU.flatMap(n => { const pair = rel.ints.get(n); return (pair ? [pair[0], pair[1]] : [n]).flatMap(r => (piParts(r) ?? []).flatMap(vars)); }).map(r => partOf.get(r) ?? r))];
|
|
561
|
+
for (const x of xs) {
|
|
562
|
+
const dir = implied(G, { [x]: -1 }) ? 1 : implied(G, { [x]: 1 }) ? -1 : 1;
|
|
563
|
+
for (const c of [0, 1, 2, 3, 4, 8, 16, 32]) {
|
|
564
|
+
const b = { [x]: -dir, ...konst(c) };
|
|
565
|
+
if (sat([...G, b]))
|
|
566
|
+
pool.push(b);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
// Houdini: G must be kept by U; a difference not kept is dropped
|
|
571
|
+
let R = dedupe([...G, ...opt, ...pool]);
|
|
572
|
+
const must = new Set(G.map(canon));
|
|
573
|
+
for (let round = 0; round < 12; round++) {
|
|
574
|
+
if (late())
|
|
575
|
+
return undefined;
|
|
576
|
+
const bad = R.filter(a => !keeps(R, a));
|
|
577
|
+
if (!bad.length)
|
|
578
|
+
break;
|
|
579
|
+
if (bad.some(a => must.has(canon(a))))
|
|
580
|
+
return undefined;
|
|
581
|
+
const drop = new Set(bad.map(canon));
|
|
582
|
+
R = R.filter(a => !drop.has(canon(a)));
|
|
583
|
+
}
|
|
584
|
+
if (R.some(a => !keeps(R, a)) || !sat(R))
|
|
585
|
+
return undefined;
|
|
586
|
+
// (the factors' bounds the set keeps: each left out, the strongest first, where the rest is kept without it)
|
|
587
|
+
for (const b of [...pool].reverse()) {
|
|
588
|
+
if (late())
|
|
589
|
+
return undefined;
|
|
590
|
+
const key = canon(b), rest = R.filter(a => canon(a) !== key);
|
|
591
|
+
if (rest.length < R.length && !must.has(key) && rest.every(a => keeps(rest, a)))
|
|
592
|
+
R = rest;
|
|
593
|
+
}
|
|
594
|
+
// R without what the rest of it implies (a smaller goal for the kernel)
|
|
595
|
+
R = irredundant(R, late);
|
|
596
|
+
if (late())
|
|
597
|
+
return undefined;
|
|
598
|
+
// per turn j: R_j, the rest of the cycle from turn j allowed and ending in R
|
|
599
|
+
const Rs = steps.map((_, j) => {
|
|
600
|
+
if (j === 0)
|
|
601
|
+
return R;
|
|
602
|
+
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);
|
|
604
|
+
});
|
|
605
|
+
if (late())
|
|
606
|
+
return undefined;
|
|
607
|
+
if (Rs.some(r => !sat(r)))
|
|
608
|
+
return undefined;
|
|
609
|
+
// as the loop's condition and witness
|
|
610
|
+
const intOf = (x) => rel.ints.get(x);
|
|
611
|
+
const term = (f) => {
|
|
612
|
+
let p = K(0), n = K(0);
|
|
613
|
+
const add = (e, k, to) => { const t = k === 1 ? e : { op: 'mul', k, a: e }; if (to === 'p')
|
|
614
|
+
p = isZ(p) ? t : { op: 'add', a: p, b: t };
|
|
615
|
+
else
|
|
616
|
+
n = isZ(n) ? t : { op: 'add', a: n, b: t }; };
|
|
617
|
+
for (const x of vars(f).sort()) {
|
|
618
|
+
const c = f[x], pair = intOf(x);
|
|
619
|
+
if (pair) {
|
|
620
|
+
add(V(pair[0]), Math.abs(c), c > 0 ? 'p' : 'n');
|
|
621
|
+
add(V(pair[1]), Math.abs(c), c > 0 ? 'n' : 'p');
|
|
622
|
+
}
|
|
623
|
+
else
|
|
624
|
+
add(V(x), Math.abs(c), c > 0 ? 'p' : 'n');
|
|
625
|
+
}
|
|
626
|
+
const k = f['1'] ?? 0;
|
|
627
|
+
if (k)
|
|
628
|
+
add(K(Math.abs(k)), 1, k > 0 ? 'p' : 'n');
|
|
629
|
+
return { p, n };
|
|
630
|
+
};
|
|
631
|
+
const atom = (f) => { const t = term(f); return { op: '<=', a: t.p, b: t.n }; };
|
|
632
|
+
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
|
|
636
|
+
// (a part is told by its location, and where the cycle comes back to a location, by an atom of its rows that each
|
|
637
|
+
// other part there refutes: a short condition, which the body's reads of the witness multiply less; its full rows
|
|
638
|
+
// where no atom tells it apart)
|
|
639
|
+
const tell = (j) => {
|
|
640
|
+
if (!rel.loc)
|
|
641
|
+
return parts[j];
|
|
642
|
+
const others = Rs.flatMap((r, k) => (k !== j && from(seq[k]) === from(seq[j]) ? [r] : []));
|
|
643
|
+
const atoms = [];
|
|
644
|
+
for (const r of others) {
|
|
645
|
+
if (atoms.some(a => !sat([...r, a])))
|
|
646
|
+
continue;
|
|
647
|
+
const a = Rs[j].find(f => !sat([...r, f]));
|
|
648
|
+
if (!a)
|
|
649
|
+
return parts[j];
|
|
650
|
+
atoms.push(a);
|
|
651
|
+
}
|
|
652
|
+
return conj([...pcIs(j), ...atoms.map(atom)]);
|
|
653
|
+
};
|
|
654
|
+
const conds = parts.map((_, j) => tell(j));
|
|
655
|
+
// Where each part is at a location of its own, the set is written by slots: the parts' k-th atoms, one comparison of
|
|
656
|
+
// two if-chains over the locations (the same set). The kernel reads an if only down the branch the case decides, so
|
|
657
|
+
// the set after the turn costs it the next part's atoms, not every part's (TermComp's tqli: its check 10.4 s to 4.5
|
|
658
|
+
// s). Not where parts share a location: their conditions in each chain cost more than they save (s1).
|
|
659
|
+
const slotted = () => {
|
|
660
|
+
const width = Math.max(...Rs.map(r => r.length)), chain = (pick) => conds.reduceRight((acc, c, j) => (isZ(pick(j)) && isZ(acc) ? acc : { op: 'if', c, then: pick(j), else: acc }), K(0));
|
|
661
|
+
const slots = [];
|
|
662
|
+
for (let k = 0; k < width; k++) {
|
|
663
|
+
const ts = Rs.map(r => (r[k] ? term(r[k]) : { p: K(0), n: K(0) }));
|
|
664
|
+
slots.push({ op: '<=', a: chain(j => ts[j].p), b: chain(j => ts[j].n) });
|
|
665
|
+
}
|
|
666
|
+
return { op: 'and', xs: [{ op: 'or', xs: conds }, ...slots] };
|
|
667
|
+
};
|
|
668
|
+
const set = parts.length > 1 && rel.loc && new Set(seq.map(from)).size === seq.length ? slotted() : parts.length === 1 ? parts[0] : { op: 'or', xs: parts };
|
|
669
|
+
const valueAt = (j, n) => {
|
|
670
|
+
const p = rel.paths[seq[j]];
|
|
671
|
+
if (n in p.pins)
|
|
672
|
+
return K(p.pins[n]);
|
|
673
|
+
const u = steps[j].ins;
|
|
674
|
+
for (const [x, pair] of rel.ints)
|
|
675
|
+
if (pair[0] === n || pair[1] === n) {
|
|
676
|
+
const t = u[x];
|
|
677
|
+
if (!t)
|
|
678
|
+
return K(0);
|
|
679
|
+
const v = term(t);
|
|
680
|
+
return pair[0] === n ? sub(v.p, v.n) : sub(v.n, v.p);
|
|
681
|
+
}
|
|
682
|
+
const t = u[n];
|
|
683
|
+
if (!t)
|
|
684
|
+
return K(0);
|
|
685
|
+
const v = term(t);
|
|
686
|
+
return sub(v.p, v.n);
|
|
687
|
+
};
|
|
688
|
+
const wit = {};
|
|
689
|
+
for (const n of l.inputs) {
|
|
690
|
+
const vals = seq.map((_, j) => valueAt(j, n)), keys = vals.map(v => JSON.stringify(v));
|
|
691
|
+
if (keys.every(k => k === keys[0])) {
|
|
692
|
+
wit[n] = vals[0];
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
// (the commonest value last, with no condition: a state of any part whose turn takes it matches no other's; a
|
|
696
|
+
// state matched by another part's condition is in that part, whose turn keeps it in the set too)
|
|
697
|
+
const tally = new Map();
|
|
698
|
+
for (const k of keys)
|
|
699
|
+
tally.set(k, (tally.get(k) ?? 0) + 1);
|
|
700
|
+
const common = [...tally].sort((a, b) => b[1] - a[1])[0][0];
|
|
701
|
+
let e = vals[keys.indexOf(common)];
|
|
702
|
+
for (let j = vals.length - 1; j >= 0; j--)
|
|
703
|
+
if (keys[j] !== common)
|
|
704
|
+
e = { op: 'if', c: conds[j], then: vals[j], else: e };
|
|
705
|
+
wit[n] = e;
|
|
706
|
+
}
|
|
707
|
+
return { set, wit, targets: Rs.map((rows, j) => ({ loc: from(seq[j]), rows })) };
|
|
708
|
+
}
|
|
709
|
+
const cmp = (a, b) => { for (let i = 0; i < a.length; i++)
|
|
710
|
+
if (a[i] !== b[i])
|
|
711
|
+
return a[i] - b[i]; return 0; };
|
|
712
|
+
const isZ = (e) => e.op === 'const' && e.value === 0;
|
|
713
|
+
const sub = (a, b) => (isZ(b) ? a : isZ(a) ? K(0) : { op: 'sub', a, b });
|
|
714
|
+
function irredundant(rows, late) {
|
|
715
|
+
let out = rows;
|
|
716
|
+
for (let i = out.length - 1; i >= 0 && !late(); i--) {
|
|
717
|
+
const rest = out.filter((_, j) => j !== i);
|
|
718
|
+
if (rest.length && implied(rest, out[i]))
|
|
719
|
+
out = rest;
|
|
720
|
+
}
|
|
721
|
+
return out;
|
|
722
|
+
}
|
|
723
|
+
// `report.exhausted`: the search ran to its end within its time and calls (no part reached within its depth), as opposed
|
|
724
|
+
// to not applying (a start it doesn't read linearly) or being cut short.
|
|
725
|
+
export function* stemsTo(l, targets, io, opts) {
|
|
726
|
+
const found = relOf(l);
|
|
727
|
+
if (!found)
|
|
728
|
+
return;
|
|
729
|
+
const rel = found;
|
|
730
|
+
const { now, until } = opts, depth = opts.depth ?? 8;
|
|
731
|
+
let calls = opts.calls ?? 400;
|
|
732
|
+
const S = rel.state, P = new Set(rel.params), Sset = new Set(S);
|
|
733
|
+
const natState = S.filter(x => !rel.ints.has(x));
|
|
734
|
+
// the params as integers (a pair x, x$n or x$neg is x − x$n), and the start's state over them
|
|
735
|
+
const pairOf = new Map(), paramInts = [];
|
|
736
|
+
for (const x of l.params)
|
|
737
|
+
for (const sfx of ['$n', '$neg'])
|
|
738
|
+
if (l.params.includes(x + sfx)) {
|
|
739
|
+
pairOf.set(x, [x, 1]);
|
|
740
|
+
pairOf.set(x + sfx, [x, -1]);
|
|
741
|
+
paramInts.push([x, x + sfx]);
|
|
742
|
+
}
|
|
743
|
+
for (const x of l.params)
|
|
744
|
+
if (!pairOf.has(x)) {
|
|
745
|
+
pairOf.set(x, [x, 1]);
|
|
746
|
+
paramInts.push([x, undefined]);
|
|
747
|
+
}
|
|
748
|
+
const toInts = (raw) => {
|
|
749
|
+
const o = konst(raw['1'] ?? 0), seen = new Map();
|
|
750
|
+
for (const r of vars(raw)) {
|
|
751
|
+
const q = pairOf.get(r);
|
|
752
|
+
if (!q)
|
|
753
|
+
return undefined;
|
|
754
|
+
const c = raw[r] * q[1];
|
|
755
|
+
if (seen.has(q[0]) && seen.get(q[0]) !== c)
|
|
756
|
+
return undefined;
|
|
757
|
+
seen.set(q[0], c);
|
|
758
|
+
}
|
|
759
|
+
for (const [x, c] of seen) {
|
|
760
|
+
const pair = paramInts.find(p => p[0] === x);
|
|
761
|
+
// (a pair read whole: both parts, opposite; one part alone is not the integer)
|
|
762
|
+
if (pair[1] && vars(raw).filter(r => pairOf.get(r)?.[0] === x).length !== 2)
|
|
763
|
+
return undefined;
|
|
764
|
+
o[x] = c;
|
|
765
|
+
}
|
|
766
|
+
return o;
|
|
767
|
+
};
|
|
768
|
+
const startOf = (x) => {
|
|
769
|
+
const pair = rel.ints.get(x);
|
|
770
|
+
if (!pair) {
|
|
771
|
+
const e = l.state[x];
|
|
772
|
+
const r = e && linOfE(e);
|
|
773
|
+
return r && toInts(r);
|
|
774
|
+
}
|
|
775
|
+
const ep = l.state[pair[0]], en = l.state[pair[1]];
|
|
776
|
+
if (!ep || !en)
|
|
777
|
+
return undefined;
|
|
778
|
+
if (ep.op === 'sub' && en.op === 'sub' && JSON.stringify(ep.a) === JSON.stringify(en.b) && JSON.stringify(ep.b) === JSON.stringify(en.a)) {
|
|
779
|
+
const a = linOfE(ep.a), b = linOfE(ep.b);
|
|
780
|
+
return a && b && toInts(plus(a, b, -1));
|
|
781
|
+
}
|
|
782
|
+
const a = linOfE(ep), b = linOfE(en);
|
|
783
|
+
return a && b && toInts(plus(a, b, -1));
|
|
784
|
+
};
|
|
785
|
+
const sigma0 = {};
|
|
786
|
+
for (const x of S) {
|
|
787
|
+
const v = startOf(x);
|
|
788
|
+
if (!v)
|
|
789
|
+
return;
|
|
790
|
+
sigma0[x] = v;
|
|
791
|
+
}
|
|
792
|
+
const locE = rel.loc ? l.state[rel.loc] : undefined;
|
|
793
|
+
if (rel.loc && locE?.op !== 'const')
|
|
794
|
+
return;
|
|
795
|
+
const startLoc = locE?.op === 'const' ? locE.value : 0;
|
|
796
|
+
const from = (i) => (rel.loc ? rel.from[i] : 0), to = (i) => (rel.loc ? rel.to[i] : 0);
|
|
797
|
+
const loops = new Map();
|
|
798
|
+
rel.paths.forEach((p, i) => {
|
|
799
|
+
if (from(i) !== to(i))
|
|
800
|
+
return;
|
|
801
|
+
for (const ins of inputChoices(p, Sset, P)) {
|
|
802
|
+
const c = compose(rel, [{ path: i, ins }], natState);
|
|
803
|
+
if (!c)
|
|
804
|
+
continue;
|
|
805
|
+
const delta = {};
|
|
806
|
+
let ok = true;
|
|
807
|
+
for (const x of S) {
|
|
808
|
+
const d = plus(c.post[x], { [x]: 1 }, -1);
|
|
809
|
+
if (!isConst(d)) {
|
|
810
|
+
ok = false;
|
|
811
|
+
break;
|
|
812
|
+
}
|
|
813
|
+
if (d['1'])
|
|
814
|
+
delta[x] = d['1'];
|
|
815
|
+
}
|
|
816
|
+
if (ok && Object.keys(delta).length) {
|
|
817
|
+
loops.set(from(i), [...(loops.get(from(i)) ?? []), { path: i, ins, delta }]);
|
|
818
|
+
break;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
const natParams = paramInts.filter(p => !p[1]).map(p => p[0]);
|
|
823
|
+
const solveRows = (rows) => { calls--; return solve(rows.map(lin => ({ lin, label: '' })), 3000); };
|
|
824
|
+
const evalLin = (f, env, w) => {
|
|
825
|
+
let v = f['1'] ?? 0;
|
|
826
|
+
for (const x of vars(f)) {
|
|
827
|
+
const pair = rel.ints.get(x);
|
|
828
|
+
v += f[x] * (x.includes('@') ? (w[x] ?? 0) : pair ? (env[pair[0]] ?? 0) - (env[pair[1]] ?? 0) : (env[x] ?? 0));
|
|
829
|
+
}
|
|
830
|
+
return v;
|
|
831
|
+
};
|
|
832
|
+
const rawInput = (p, ins, env, w) => {
|
|
833
|
+
const out = {};
|
|
834
|
+
for (const n of l.inputs)
|
|
835
|
+
out[n] = 0;
|
|
836
|
+
for (const [u, t] of Object.entries(ins)) {
|
|
837
|
+
const v = Math.round(evalLin(t, env, w)), pair = rel.ints.get(u);
|
|
838
|
+
if (pair) {
|
|
839
|
+
out[pair[0]] = Math.max(v, 0);
|
|
840
|
+
out[pair[1]] = Math.max(-v, 0);
|
|
841
|
+
}
|
|
842
|
+
else
|
|
843
|
+
out[u] = Math.max(v, 0);
|
|
844
|
+
}
|
|
845
|
+
for (const [n, v] of Object.entries(p.pins))
|
|
846
|
+
if (l.inputs.includes(n))
|
|
847
|
+
out[n] = v;
|
|
848
|
+
return out;
|
|
849
|
+
};
|
|
850
|
+
const concrete = (segs, w) => {
|
|
851
|
+
const params = {};
|
|
852
|
+
for (const [x, neg] of paramInts) {
|
|
853
|
+
const v = Math.round(w[x] ?? 0);
|
|
854
|
+
if (neg) {
|
|
855
|
+
params[x] = Math.max(v, 0);
|
|
856
|
+
params[neg] = Math.max(-v, 0);
|
|
857
|
+
}
|
|
858
|
+
else
|
|
859
|
+
params[x] = Math.max(v, 0);
|
|
860
|
+
}
|
|
861
|
+
let st = io.start(params);
|
|
862
|
+
const stem = [];
|
|
863
|
+
let left = 200_000;
|
|
864
|
+
for (const s of segs) {
|
|
865
|
+
const times = s.n ? Math.round(w[s.n] ?? 1) : 1;
|
|
866
|
+
if (times > 100_000)
|
|
867
|
+
return undefined;
|
|
868
|
+
for (let k = 0; k < times; k++) {
|
|
869
|
+
if (--left < 0)
|
|
870
|
+
return undefined;
|
|
871
|
+
const input = rawInput(rel.paths[s.path], s.ins, st, w), nx = io.turn(st, input);
|
|
872
|
+
if (!nx)
|
|
873
|
+
return undefined;
|
|
874
|
+
stem.push(input);
|
|
875
|
+
st = nx;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return { params, stem };
|
|
879
|
+
};
|
|
880
|
+
const base = natParams.map(x => ({ [x]: -1 }));
|
|
881
|
+
// each location's distance (in turns) to a part of the set: the search goes nearest first, and no further than the
|
|
882
|
+
// depth allows
|
|
883
|
+
const dist = new Map(targets.map(t => [t.loc, 0]));
|
|
884
|
+
for (let changed = true; changed;) {
|
|
885
|
+
changed = false;
|
|
886
|
+
for (let i = 0; i < rel.paths.length; i++) {
|
|
887
|
+
const d = dist.get(to(i));
|
|
888
|
+
if (d !== undefined && (dist.get(from(i)) ?? Infinity) > d + 1) {
|
|
889
|
+
dist.set(from(i), d + 1);
|
|
890
|
+
changed = true;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (!dist.has(startLoc)) {
|
|
895
|
+
if (opts.report)
|
|
896
|
+
opts.report.exhausted = true;
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
const maxDepth = Math.max(depth, dist.get(startLoc) + depth);
|
|
900
|
+
const outs = new Map();
|
|
901
|
+
for (let i = 0; i < rel.paths.length; i++)
|
|
902
|
+
if (dist.has(to(i)))
|
|
903
|
+
outs.set(from(i), [...(outs.get(from(i)) ?? []), i]);
|
|
904
|
+
for (const xs of outs.values())
|
|
905
|
+
xs.sort((a, b) => dist.get(to(a)) - dist.get(to(b)));
|
|
906
|
+
function* dfs(loc, sigma, rows, segs, k, lastLoop) {
|
|
907
|
+
if (calls <= 0 || now() > until)
|
|
908
|
+
return;
|
|
909
|
+
for (const t of targets)
|
|
910
|
+
if (t.loc === loc) {
|
|
911
|
+
const m = solveRows([...rows, ...t.rows.map(f => subst(f, sigma))]);
|
|
912
|
+
if (m.kind === 'sat') {
|
|
913
|
+
const c = concrete(segs, m.witness);
|
|
914
|
+
if (c)
|
|
915
|
+
yield c;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
if (segs.length + (dist.get(loc) ?? Infinity) > maxDepth)
|
|
919
|
+
return;
|
|
920
|
+
const step = (i, ins, n) => {
|
|
921
|
+
const { rs, post } = turn(rel, natState, i, sigma, ins, k);
|
|
922
|
+
if (!n)
|
|
923
|
+
return { rs, post };
|
|
924
|
+
// the last turn's rows: at sigma + (n − 1)·δ
|
|
925
|
+
const p = rel.paths[i], last = Object.fromEntries(S.map(x => [x, plus(plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0)), konst(-(n.delta[x] ?? 0)))]));
|
|
926
|
+
const insLast = Object.fromEntries(Object.entries(ins).map(([u, t]) => [u, subst(t, last)]));
|
|
927
|
+
rs.push(...p.rows.map(f => subst(f, { ...last, ...insLast })), ...natState.map(x => times(last[x], -1)), plus(konst(1), { [n.name]: -1 }));
|
|
928
|
+
return { rs, post: Object.fromEntries(S.map(x => [x, plus(sigma[x], times({ [n.name]: 1 }, n.delta[x] ?? 0))])) };
|
|
929
|
+
};
|
|
930
|
+
// a self-loop accelerated, then each path out
|
|
931
|
+
if (!lastLoop)
|
|
932
|
+
for (const lp of loops.get(loc) ?? []) {
|
|
933
|
+
const name = `n@${k}`, { rs, post } = step(lp.path, lp.ins, { name, delta: lp.delta });
|
|
934
|
+
const all = [...rows, ...rs];
|
|
935
|
+
if (solveRows(all).kind === 'refuted')
|
|
936
|
+
continue;
|
|
937
|
+
yield* dfs(loc, post, all, [...segs, { path: lp.path, ins: lp.ins, n: name }], k + 1, true);
|
|
938
|
+
}
|
|
939
|
+
for (const i of outs.get(loc) ?? []) {
|
|
940
|
+
if (segs.length + 1 + dist.get(to(i)) > maxDepth)
|
|
941
|
+
continue;
|
|
942
|
+
const p = rel.paths[i], ins = {};
|
|
943
|
+
for (const [u, t] of Object.entries(symbolic(p, k, Sset, P)))
|
|
944
|
+
ins[u] = Object.fromEntries(Object.entries(t).map(([x, c]) => [x.includes('@') ? x.replace(/@\d+$/, `@${k}`) : x, c]));
|
|
945
|
+
const { rs, post } = step(i, ins);
|
|
946
|
+
const all = [...rows, ...rs];
|
|
947
|
+
if (all.some(big) || solveRows(all).kind === 'refuted')
|
|
948
|
+
continue;
|
|
949
|
+
yield* dfs(to(i), post, all, [...segs, { path: i, ins }], k + 1, false);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
yield* dfs(startLoc, sigma0, [...base], [], 0, false);
|
|
953
|
+
if (opts.report && calls > 0 && now() <= until)
|
|
954
|
+
opts.report.exhausted = true;
|
|
955
|
+
}
|