gdp-wired 0.32.0 → 0.33.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,7 +7,7 @@
7
7
  // a model read back as the kernel's witness and judged on every hypothesis, or nothing.
8
8
  import { evalC } from "../core/machine.js";
9
9
  import { canon, linear } from "./kernel.js";
10
- import { konst, plus, solve, times, v as tv } from "../core/solver.js";
10
+ import { env, konst, plus, solve, times, v as tv } from "../core/solver.js";
11
11
  import { Simplex } from "./simplex.js";
12
12
  // (a term's text, once per object: the decision asks it of the same terms many times)
13
13
  const textsOf = new WeakMap();
@@ -51,7 +51,10 @@ const partName = (e) => e.op === 'var' ? e.name
51
51
  // A key Σ c·x + d as its terms; undefined where it reads anything but parts under constant factors.
52
52
  const linTerms = (e, k, out, d) => e.op === 'var' || e.op === 'get' ? (n => n !== undefined && (out.push([n, k]), true))(partName(e)) : e.op === 'const' ? ((d.c += k * e.value), true)
53
53
  : e.op === 'mul' ? linTerms(e.a, k * e.k, out, d) : e.op === 'add' ? linTerms(e.a, k, out, d) && linTerms(e.b, k, out, d) : false;
54
- function tupleOf(e) {
54
+ const tupleMemo = new WeakMap();
55
+ function tupleOf(e) { let t = tupleMemo.get(e); if (t === undefined)
56
+ tupleMemo.set(e, (t = tupleOf0(e) ?? null)); return t ?? undefined; }
57
+ function tupleOf0(e) {
55
58
  const ts = [], d = { c: 0 };
56
59
  if (!linTerms(e, 1, ts, d) || d.c !== 0 || !ts.length)
57
60
  return undefined;
@@ -75,7 +78,7 @@ export function decide(goal, patterns, opts = {}) {
75
78
  }
76
79
  function decide1(goal0, patterns, opts = {}) {
77
80
  fnMaps = new Set(Object.entries(patterns).filter(([, c]) => c.length === 1 && c[0] === 0).map(([f]) => f));
78
- const goal = { name: goal0.name, hyps: goal0.hyps.map(liftedKeys) };
81
+ const goal = goal0;
79
82
  // (a model whose order leaves no room between two near constants: again with the constants between them, below)
80
83
  // (a model the read-back breaks: once more without the other goals' theory lemmas, whose history chose that model)
81
84
  try {
@@ -160,57 +163,35 @@ const liftedKeys = (c) => { let x = liftMemo.get(c); if (!x)
160
163
  liftMemo.set(c, (x = liftC(c))); return x; };
161
164
  // (thrown by `late` checked every 4,096 clauses and hypotheses read: a goal's clauses are quadratic in its terms)
162
165
  const pastEnd = new Error('past the deadline');
166
+ // The work the EPR path does, counted (each clause and hypothesis read, each literal the CDCL search propagates), and a
167
+ // cap on it a caller sets (core/infer.ts's engine, per goal): past the cap the decision is unknown, at the same place on
168
+ // any machine, where a wall-clock end stops it wherever the machine has got to. Untrusted: it only stops a search.
169
+ export const eprMeter = { n: 0 };
170
+ let eprCap = Infinity;
171
+ export const pastEprCap = () => eprMeter.n > eprCap;
172
+ export function withEprCap(units, f) {
173
+ const outer = eprCap;
174
+ eprCap = Math.min(outer, eprMeter.n + units);
175
+ try {
176
+ return f();
177
+ }
178
+ finally {
179
+ eprCap = outer;
180
+ }
181
+ }
163
182
  // The theory's lemmas, by their atoms' names: each is arithmetic over the terms those names read (a part's value, a cell's
164
183
  // at its key), so it holds in every goal that has those atoms, a round's other goals over the same set above all; each
165
184
  // goal starts with those it has. At most 20,000, then begun again.
166
185
  const lemmaCache = new Map();
167
186
  const noRoom = 'no values for the model\'s order', breaks = 'the abstraction\'s model breaks';
168
- function decide0(goal, patterns, opts) {
169
- // --- which hypotheses are EPR-shaped: every map read at a key of its map's pattern
170
- const shaped = goal.hyps.map(h => {
171
- let ok = true;
172
- const walk = (o) => {
173
- if (!ok || !o || typeof o !== 'object')
174
- return;
175
- const x = o;
176
- if (x.op === 'get' && fnMaps.has(x.map)) {
177
- if (partName(x) === undefined) {
178
- ok = false;
179
- return;
180
- }
181
- }
182
- else if (x.op === 'get') {
183
- const t = x.args ? undefined : tupleOf(x.key), p = patterns[x.map];
184
- if (!t || !p || !sameCoefs(t.coefs, p)) {
185
- ok = false;
186
- return;
187
- }
188
- }
189
- for (const v of Object.values(o))
190
- walk(v);
191
- };
192
- walk(h);
193
- return ok;
194
- });
195
- if (decideHook.on)
196
- lastShaped = shaped;
197
- // (the conclusion's reads at keys of any radix shape: one of the wrong sort, Leader[k] <= Msg[k] with Msg a relation of
198
- // pairs, is a cell of its own, as in a hypothesis)
199
- const tupled = (o) => { if (!o || typeof o !== 'object')
200
- return true; const x = o; if (x.op === 'get' && !fnMaps.has(x.map) && (x.args || !tupleOf(x.key)))
201
- return false; return Object.values(o).every(tupled); };
202
- if (!shaped.at(-1) && !tupled(goal.hyps.at(-1)))
203
- return { unknown: 'the conclusion is not EPR-shaped' };
204
- const hyps = goal.hyps;
205
- let ticks = 0;
206
- const tick = () => { if ((++ticks & 4095) === 0 && opts.late?.())
207
- throw pastEnd; };
208
- const fits = (map, key) => { const t = tupleOf(key), p = patterns[map]; return t && p && sameCoefs(t.coefs, p) ? t : undefined; };
209
- // --- names: a part is a name some read's key or a key equality reads; the rest are scalars
210
- // (each function part once: its reads are many, its congruence pairs of parts)
211
- const parts = new Set(), fnParts = [], fnSeen = new Set();
212
- // (the goal's reads and comparisons, gathered in one walk, each shared node once: the walks below read these lists)
213
- const reads = [], comps = [], seen = new WeakSet();
187
+ const factsMemo = new Map();
188
+ function factsOf(h0, tick) {
189
+ tick();
190
+ const text = h0 ? JSON.stringify(h0) : '';
191
+ let f = factsMemo.get(text);
192
+ if (f)
193
+ return f;
194
+ const h = h0 && liftedKeys(h0), reads = [], comps = [], bounds = [], seen = new WeakSet();
214
195
  const gather = (o) => {
215
196
  if (!o || typeof o !== 'object' || seen.has(o))
216
197
  return;
@@ -224,23 +205,83 @@ function decide0(goal, patterns, opts) {
224
205
  for (const v of Object.values(o))
225
206
  gather(v);
226
207
  };
227
- hyps.forEach(gather);
228
- for (const x of reads) {
229
- if (fnMaps.has(x.map)) {
230
- const n = partName(x), a = partName(x.key);
231
- if (n && a) {
232
- if (!fnSeen.has(n))
233
- (fnSeen.add(n), fnParts.push({ f: x.map, n, a }));
234
- parts.add(n);
235
- parts.add(a);
236
- }
208
+ gather(h);
209
+ // exact: a scalar or a cell a hypothesis bounds by a constant (M[t] <= 1, a kind's instance)
210
+ const unitWalk = (c) => {
211
+ if (!c)
212
+ return;
213
+ if (c.op === 'and') {
214
+ c.xs.forEach(unitWalk);
215
+ return;
237
216
  }
238
- else
239
- fits(x.map, x.key)?.parts.forEach(p => parts.add(p));
217
+ if ((c.op === '<=' || c.op === '<') && c.b.op === 'const' && (c.a.op === 'get' || c.a.op === 'var')) {
218
+ const b = c.b.value - (c.op === '<' ? 1 : 0);
219
+ if (b >= 0)
220
+ bounds.push([textOfE(c.a), b]);
221
+ }
222
+ };
223
+ unitWalk(h);
224
+ if (factsMemo.size > 50_000)
225
+ factsMemo.clear();
226
+ factsMemo.set(text, (f = { h, text, reads, comps, bounds }));
227
+ return f;
228
+ }
229
+ const leavesOf = (e, k, out) => {
230
+ if (e.op === 'add') {
231
+ leavesOf(e.a, k, out);
232
+ leavesOf(e.b, k, out);
233
+ }
234
+ else if (e.op === 'mul')
235
+ leavesOf(e.a, k * e.k, out);
236
+ else if (e.op === 'if') {
237
+ leavesOf(e.then, k, out);
238
+ leavesOf(e.else, k, out);
239
+ }
240
+ else if (e.op !== 'const')
241
+ out.push([e, k]);
242
+ };
243
+ const compMemo = new WeakMap();
244
+ const compInfo = (c) => {
245
+ let x = compMemo.get(c);
246
+ if (!x) {
247
+ const ts = [], consts = [];
248
+ leavesOf(c.a, 1, ts);
249
+ leavesOf(c.b, -1, ts);
250
+ const k = (e) => { if (e.op === 'const')
251
+ consts.push(Math.abs(e.value));
252
+ else if (e.op === 'add')
253
+ (k(e.a), k(e.b));
254
+ else if (e.op === 'mul')
255
+ k(e.a);
256
+ else if (e.op === 'if')
257
+ (k(e.then), k(e.else)); };
258
+ k(c.a);
259
+ k(c.b);
260
+ compMemo.set(c, (x = { ts, top: Math.max(1, ...consts), ta: tupleOf(c.a), tb: tupleOf(c.b) }));
240
261
  }
262
+ return x;
263
+ };
264
+ function stateOf(fs, patterns, tick) {
265
+ const fits = (map, key) => { const t = tupleOf(key), p = patterns[map]; return t && p && sameCoefs(t.coefs, p) ? t : undefined; };
266
+ const parts = new Set(), fnParts = [], fnSeen = new Set(), reads = [];
267
+ for (const f of fs)
268
+ for (const x of f.reads) {
269
+ reads.push(x);
270
+ if (fnMaps.has(x.map)) {
271
+ const n = partName(x), a = partName(x.key);
272
+ if (n && a) {
273
+ if (!fnSeen.has(n))
274
+ (fnSeen.add(n), fnParts.push({ f: x.map, n, a }));
275
+ parts.add(n);
276
+ parts.add(a);
277
+ }
278
+ }
279
+ else
280
+ fits(x.map, x.key)?.parts.forEach(p => parts.add(p));
281
+ }
241
282
  // (and the names of a key equality between tuples of one shape: of several parts, or of one where the other side is a part)
242
- const eqs = comps.flatMap(c => { if (c.op !== '=')
243
- return []; const ta = tupleOf(c.a), tb = tupleOf(c.b); return ta && tb && sameCoefs(ta.coefs, tb.coefs) ? [{ ta, tb }] : []; });
283
+ const eqs = fs.flatMap(f => f.comps.flatMap(c => { if (c.op !== '=')
284
+ return []; const { ta, tb } = compInfo(c); return ta && tb && sameCoefs(ta.coefs, tb.coefs) ? [{ ta, tb }] : []; }));
244
285
  for (let grew = true; grew;) {
245
286
  grew = false;
246
287
  for (const { ta, tb } of eqs)
@@ -251,104 +292,115 @@ function decide0(goal, patterns, opts) {
251
292
  grew = true;
252
293
  }
253
294
  }
254
- // exact: a scalar or a cell a hypothesis bounds by a constant (M[t] <= 1, a kind's instance): its values are
255
- // 0 .. that bound exactly, no "cap or more", so it is compared with any finite term by cases, not ordered (a yes/no
256
- // that implies another, Leader[x] <= Voted[x]); the hypothesis is the origin of the clause that it takes one of them
257
- const ordMaps = new Set(), ordScalars = new Set();
258
295
  const bounded = new Map();
259
- const unitWalk = (c, h) => {
260
- if (!c)
261
- return;
262
- if (c.op === 'and') {
263
- c.xs.forEach(x => unitWalk(x, h));
264
- return;
296
+ for (const f of fs)
297
+ for (const [id, b] of f.bounds) {
298
+ const had = bounded.get(id);
299
+ if (had === undefined || b < had)
300
+ bounded.set(id, b);
265
301
  }
266
- if ((c.op === '<=' || c.op === '<') && c.b.op === 'const' && (c.a.op === 'get' || c.a.op === 'var')) {
267
- const id = textOfE(c.a), b = c.b.value - (c.op === '<' ? 1 : 0), had = bounded.get(id);
268
- if (b >= 0 && (!had || b < had.b))
269
- bounded.set(id, { b, h });
270
- }
271
- };
272
- hyps.forEach((c, h) => unitWalk(c, h));
273
- // (one compared with a key part, or beside an ordered term, is of that sort: ordered, below, and not exact)
302
+ const ordMaps = new Set(), ordScalars = new Set();
274
303
  const exactOf = (e) => (e.op === 'get' ? (!ordMaps.has(e.map) ? bounded.get(textOfE(e)) : undefined) : e.op === 'var' && !parts.has(e.name) && !ordScalars.has(e.name) ? bounded.get(textOfE(e)) : undefined);
275
304
  // --- caps: a finite term's values are 0 .. cap, cap above every constant a comparison it is in has (so a larger value
276
305
  // decides every comparison the cap does: the terms are naturals with coefficients of one sign)
277
306
  const caps = new Map();
278
307
  const termKey = (e) => (e.op === 'var' && !parts.has(e.name) ? `s:${e.name}` : e.op === 'get' ? `c:${e.map}` : undefined);
279
- for (const c of comps) {
280
- {
281
- const consts = [], keys = [];
308
+ const ofParts = (t) => t?.parts.every(x => parts.has(x));
309
+ const ordComps = [];
310
+ for (const f of fs)
311
+ for (const c of f.comps) {
312
+ const ci = compInfo(c);
282
313
  let ex = 0;
283
- const w = (e, k) => { if (e.op === 'const')
284
- consts.push(Math.abs(e.value));
285
- else if (e.op === 'add')
286
- (w(e.a, k), w(e.b, k));
287
- else if (e.op === 'mul')
288
- w(e.a, k * e.k);
289
- else if (e.op === 'if')
290
- (w(e.then, k), w(e.else, k));
291
- else {
314
+ for (const [e, k] of ci.ts) {
292
315
  const x = exactOf(e);
293
- if (x)
294
- ex += Math.abs(k) * x.b;
316
+ if (x !== undefined)
317
+ ex += Math.abs(k) * x;
318
+ }
319
+ // (and past what the exact terms beside can add: x <= Voted[k] with x at its cap is false at every larger x)
320
+ const top = ci.top + ex + 1;
321
+ for (const [e] of ci.ts) {
295
322
  const t = termKey(e);
296
323
  if (t)
297
- keys.push(t);
298
- } };
299
- w(c.a, 1);
300
- w(c.b, 1);
301
- // (and past what the exact terms beside can add: x <= Voted[k] with x at its cap is false at every larger x)
302
- const top = Math.max(1, ...consts) + ex + 1;
303
- for (const k of keys)
304
- caps.set(k, Math.max(caps.get(k) ?? 1, top));
324
+ caps.set(t, Math.max(caps.get(t) ?? 1, top));
325
+ }
326
+ if (!(ofParts(ci.ta) && ofParts(ci.tb)))
327
+ ordComps.push(ci.ts);
305
328
  }
306
- }
307
329
  // ordered: a map's cells, or a scalar, compared with another non-constant term (an epoch with a node's epoch: Ivy's
308
330
  // total order, `le`), not only with constants (a yes/no, a choice, which stay finite)
309
- const leaves = (e, k, out) => {
310
- if (e.op === 'add') {
311
- leaves(e.a, k, out);
312
- leaves(e.b, k, out);
313
- }
314
- else if (e.op === 'mul')
315
- leaves(e.a, k * e.k, out);
316
- else if (e.op === 'if') {
317
- leaves(e.then, k, out);
318
- leaves(e.else, k, out);
319
- }
320
- else if (e.op !== 'const')
321
- out.push([e, k]);
322
- };
323
- const ofParts = (e) => tupleOf(e)?.parts.every(x => parts.has(x));
324
- const ordComps = comps.filter(c => !(ofParts(c.a) && ofParts(c.b))).map(c => { const ts = []; leaves(c.a, 1, ts); leaves(c.b, -1, ts); return ts; });
331
+ let grew = true;
325
332
  const ordWalk = (ts) => {
326
- {
327
- const hasPart = ts.some(([e]) => (n => n !== undefined && parts.has(n))(partName(e)));
328
- const nonPart = ts.filter(([e]) => (hasPart || !exactOf(e)) && ((e.op === 'get' && !fnMaps.has(e.map)) || (e.op === 'var' && !parts.has(e.name))));
329
- // (and every term beside an ordered one in a comparison: one value of the sort, an if-then-else's branches)
330
- const tn = ts.filter(([e]) => hasPart || !exactOf(e)), mixed = nonPart.length && tn.length > 1 && tn.some(t => t[1] > 0) && tn.some(t => t[1] < 0);
331
- const beside = nonPart.some(([e]) => (e.op === 'get' && ordMaps.has(e.map)) || (e.op === 'var' && ordScalars.has(e.name)));
332
- if (mixed || beside)
333
- for (const [e] of nonPart) {
334
- if (e.op === 'get' && !ordMaps.has(e.map)) {
335
- ordMaps.add(e.map);
336
- grew = true;
337
- }
338
- else if (e.op === 'var' && !ordScalars.has(e.name)) {
339
- ordScalars.add(e.name);
340
- grew = true;
341
- }
333
+ const hasPart = ts.some(([e]) => (n => n !== undefined && parts.has(n))(partName(e)));
334
+ const nonPart = ts.filter(([e]) => (hasPart || exactOf(e) === undefined) && ((e.op === 'get' && !fnMaps.has(e.map)) || (e.op === 'var' && !parts.has(e.name))));
335
+ // (and every term beside an ordered one in a comparison: one value of the sort, an if-then-else's branches)
336
+ const tn = ts.filter(([e]) => hasPart || exactOf(e) === undefined), mixed = nonPart.length && tn.length > 1 && tn.some(t => t[1] > 0) && tn.some(t => t[1] < 0);
337
+ const beside = nonPart.some(([e]) => (e.op === 'get' && ordMaps.has(e.map)) || (e.op === 'var' && ordScalars.has(e.name)));
338
+ if (mixed || beside)
339
+ for (const [e] of nonPart) {
340
+ if (e.op === 'get' && !ordMaps.has(e.map)) {
341
+ ordMaps.add(e.map);
342
+ grew = true;
342
343
  }
343
- }
344
+ else if (e.op === 'var' && !ordScalars.has(e.name)) {
345
+ ordScalars.add(e.name);
346
+ grew = true;
347
+ }
348
+ }
344
349
  };
345
- let grew = true;
346
350
  while (grew) {
347
351
  grew = false;
348
352
  ordComps.forEach(ts => (tick(), ordWalk(ts)));
349
353
  }
354
+ const sorted = (xs) => [...xs].map(x => String(x)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
355
+ // (the bounded terms not in it: each finite variable a goal reads is checked against them in its encoder)
356
+ return { parts, fnParts, bounded, caps, ordMaps, ordScalars, reads, sig: JSON.stringify([JSON.stringify(patterns), sorted(parts), sorted(caps), sorted(ordMaps), sorted(ordScalars)]) };
357
+ }
358
+ // One encoder per sort of goal (`State.sig`): every hypothesis it was asked is encoded once, its clauses guarded by an
359
+ // activation literal (¬a ∨ clause), its atoms, cells and ordered terms kept, the axioms over them all (each holds in every
360
+ // model of any goal), and one CDCL search (`cdclSolver`) whose learned clauses and theory lemmas stay. A goal is its
361
+ // hypotheses' literals assumed: a refutation's origins are hypotheses of the goal (a clause of a hypothesis not assumed is
362
+ // satisfied by its guard, so never a reason), a model is read back over the goal's own terms. Unsat here is unsat there,
363
+ // as for one goal alone; a model is judged on every hypothesis. GDP_EPR_INC=0: an encoder per goal, as before.
364
+ const incOn = env.GDP_EPR_INC !== '0';
365
+ const pool = new Map(), other = 'another encoder\'s goal';
366
+ function decide0(goal, patterns, opts) {
367
+ let ticks = 0;
368
+ const tick = () => { eprMeter.n++; if ((++ticks & 4095) === 0 && opts.late?.())
369
+ throw pastEnd; };
370
+ const fs = goal.hyps.map(h => factsOf(h, tick));
371
+ // --- which hypotheses are EPR-shaped: every map read at a key of its map's pattern
372
+ const shapedOf = (f) => f.reads.every(x => (fnMaps.has(x.map) ? partName(x) !== undefined : (t => !!t && !!patterns[x.map] && sameCoefs(t.coefs, patterns[x.map]))(x.args ? undefined : tupleOf(x.key))));
373
+ if (decideHook.on)
374
+ lastShaped = fs.map(shapedOf);
375
+ // (the conclusion's reads at keys of any radix shape: one of the wrong sort, Leader[k] <= Msg[k] with Msg a relation of
376
+ // pairs, is a cell of its own, as in a hypothesis)
377
+ const last = fs.at(-1);
378
+ if (last && !shapedOf(last) && last.reads.some(x => !fnMaps.has(x.map) && (x.args || !tupleOf(x.key))))
379
+ return { unknown: 'the conclusion is not EPR-shaped' };
380
+ const st = stateOf(fs, patterns, tick);
381
+ if (!incOn || opts.fill || opts.fresh)
382
+ return encoder(st, patterns).decide(goal, fs, st, opts);
383
+ let enc = pool.get(st.sig);
384
+ if (enc)
385
+ pool.delete(st.sig);
386
+ else if (pool.size >= 4)
387
+ pool.delete(pool.keys().next().value);
388
+ let d = enc?.decide(goal, fs, st, opts);
389
+ if (!d || ('unknown' in d && d.unknown === other))
390
+ d = (enc = encoder(st, patterns)).decide(goal, fs, st, opts);
391
+ if (enc.size() < 20_000)
392
+ pool.set(st.sig, enc);
393
+ return d;
394
+ }
395
+ function encoder(st, patterns) {
396
+ const { parts, bounded, caps, ordMaps, ordScalars } = st;
397
+ const fits = (map, key) => { const t = tupleOf(key), p = patterns[map]; return t && p && sameCoefs(t.coefs, p) ? t : undefined; };
398
+ const exactOf = (e) => (e.op === 'get' ? (!ordMaps.has(e.map) ? bounded.get(textOfE(e)) : undefined) : e.op === 'var' && !parts.has(e.name) && !ordScalars.has(e.name) ? bounded.get(textOfE(e)) : undefined);
399
+ let tick = () => { eprMeter.n++; };
400
+ // (what the hypothesis being encoded reads: its ordered terms, finite terms, opaque atoms and successors)
401
+ let use = { ords: [], fins: [], opq: [], succ: [] };
350
402
  // --- atoms
351
- const ids = new Map(), names = [''];
403
+ const ids = new Map(), names = [''], kept = new Set(), first = new Set();
352
404
  const atom = (key) => { let v = ids.get(key); if (v === undefined) {
353
405
  v = names.length;
354
406
  ids.set(key, v);
@@ -357,70 +409,86 @@ function decide0(goal, patterns, opts) {
357
409
  // (the order's and equality's atoms by their two terms, without building their text again: the axioms ask them
358
410
  // quadratically and the transitivity cubically)
359
411
  const pairAtoms = (tag) => { const byA = new Map(); return (a, b) => { let in2 = byA.get(a); if (!in2)
360
- byA.set(a, (in2 = new Map())); let f = in2.get(b); if (!f)
361
- in2.set(b, (f = atom(`${tag} ${a} ${b}`))); return f; }; };
412
+ byA.set(a, (in2 = new Map())); let f = in2.get(b); if (!f) {
413
+ in2.set(b, (f = atom(`${tag} ${a} ${b}`)));
414
+ if (tag === 'le')
415
+ kept.add(f.v);
416
+ } return f; }; };
362
417
  const eqAt = pairAtoms('eq'), leAt = pairAtoms('le');
363
418
  const eq = (x, y) => (x === y ? T : x < y ? eqAt(x, y) : eqAt(y, x));
364
419
  // the ordered terms (every part among them), `le a b` a ≤ b
365
420
  const ords = new Set(['k:0', ...[...parts].map(x => `p:${x}`)]);
421
+ const touch = (id) => { ords.add(id); use.ords.push(id); };
366
422
  const le = (a, b) => (a === b ? T : leAt(a, b));
367
423
  // a part under a bound, x < c: ¬(c ≤ x) in the order (below), the constant one of its terms
368
424
  const ltAt = (x, c) => { if (c <= 0)
369
- return Fa; ords.add(`k:${c}`); return not(le(`k:${c}`, `p:${x}`)); };
370
- const fins = new Map(), cellsOf = new Map(), odd = [];
425
+ return Fa; touch(`k:${c}`); return not(le(`k:${c}`, `p:${x}`)); };
426
+ // a finite variable at a value: a scalar s:x, or a cell c:M(parts) of map M
427
+ const fins = new Map(), finsList = [];
371
428
  const finAt = (f, v) => atom(`val ${f.id} ${v}`);
429
+ const newFin = (id, cap, ex, more, bkey) => {
430
+ const f = { id, cap: ex ?? cap, bkey, ...(ex !== undefined ? { exact: true } : {}), ...more };
431
+ fins.set(id, f);
432
+ finsList.push(f);
433
+ const ls = Array.from({ length: f.cap + 1 }, (_, val) => v(finAt(f, val)));
434
+ first.add(ls[0]);
435
+ // one value per finite variable: of an exact one, under each hypothesis that bounds it
436
+ if (!f.exact)
437
+ add(ls, -1);
438
+ else {
439
+ exactFins.set(bkey, f);
440
+ for (const b of boundBy.get(bkey) ?? [])
441
+ if (b.b === f.cap)
442
+ add([-b.a, ...ls], b.gid);
443
+ }
444
+ for (let i = 0; i < ls.length; i++)
445
+ for (let j = i + 1; j < ls.length; j++)
446
+ add([-ls[i], -ls[j]], -1);
447
+ return f;
448
+ };
372
449
  const finOf = (e) => {
450
+ const f = finOf0(e);
451
+ if (f)
452
+ use.fins.push(f);
453
+ return f;
454
+ };
455
+ const finOf0 = (e) => {
373
456
  if ((e.op === 'get' && (ordMaps.has(e.map) || fnMaps.has(e.map))) || (e.op === 'var' && ordScalars.has(e.name)))
374
457
  return undefined;
375
- const ex = exactOf(e), fin = (id, cap) => (ex ? { id, cap: ex.b, exact: ex.h } : { id, cap });
458
+ const ex = exactOf(e);
376
459
  if (e.op === 'var' && !parts.has(e.name)) {
377
460
  const id = `s:${e.name}`;
378
- let f = fins.get(id);
379
- if (!f)
380
- fins.set(id, (f = fin(id, caps.get(id) ?? 1)));
381
- return f;
461
+ return fins.get(id) ?? newFin(id, caps.get(id) ?? 1, ex, {}, textOfE(e));
382
462
  }
383
463
  if (e.op === 'get' && !e.args && !fits(e.map, e.key)) {
384
464
  const id = `c:${e.map}#${textOfE(e.key)}`;
385
- let f = fins.get(id);
386
- if (!f) {
387
- fins.set(id, (f = fin(id, caps.get(`c:${e.map}`) ?? 1)));
388
- odd.push({ id, map: e.map, key: e.key });
389
- }
390
- return f;
465
+ return fins.get(id) ?? newFin(id, caps.get(`c:${e.map}`) ?? 1, ex, { map: e.map, key: e.key }, textOfE(e));
391
466
  }
392
467
  if (e.op === 'get') {
393
468
  const t = tupleOf(e.key), id = `c:${e.map}(${t.parts.join(',')})`;
394
- let f = fins.get(id);
395
- if (!f) {
396
- fins.set(id, (f = fin(id, caps.get(`c:${e.map}`) ?? 1)));
397
- if (!cellsOf.has(e.map))
398
- cellsOf.set(e.map, []);
399
- cellsOf.get(e.map).push({ id, parts: t.parts });
400
- }
401
- return f;
469
+ return fins.get(id) ?? newFin(id, caps.get(`c:${e.map}`) ?? 1, ex, { map: e.map, parts: t.parts }, textOfE(e));
402
470
  }
403
471
  return undefined;
404
472
  };
405
- const keyEqs = [];
406
- const intervals = [];
473
+ // (each bound a hypothesis puts on a term, M[t] <= b: the exact finite variable's one value under that hypothesis)
474
+ const boundBy = new Map(), exactFins = new Map();
407
475
  // An ordered term: a part, an ordered scalar, an ordered cell (a tuple's, or one of its own at a key of the wrong
408
476
  // sort), a constant; `le a b` is a ≤ b.
409
- const ordCells = new Map(), ordOdd = [];
477
+ const ordInfo = new Map();
410
478
  const ordOf = (e) => {
411
479
  if (e.op === 'const') {
412
480
  const id = `k:${e.value}`;
413
- ords.add(id);
481
+ touch(id);
414
482
  return id;
415
483
  }
416
484
  const pn = partName(e);
417
485
  if (pn !== undefined && parts.has(pn)) {
418
- ords.add(`p:${pn}`);
486
+ touch(`p:${pn}`);
419
487
  return `p:${pn}`;
420
488
  }
421
489
  if (e.op === 'var') {
422
490
  if (ordScalars.has(e.name)) {
423
- ords.add(`s:${e.name}`);
491
+ touch(`s:${e.name}`);
424
492
  return `s:${e.name}`;
425
493
  }
426
494
  return undefined;
@@ -428,22 +496,15 @@ function decide0(goal, patterns, opts) {
428
496
  // (a function read at a key of the wrong sort, idn(64·m + n): a term of the order too, its value the read-back's)
429
497
  if (e.op === 'get' && fnMaps.has(e.map)) {
430
498
  const id = `c:${e.map}#${textOfE(e.key)}`;
431
- ords.add(id);
499
+ touch(id);
432
500
  return id;
433
501
  }
434
502
  if (e.op === 'get' && ordMaps.has(e.map) && !e.args) {
435
503
  const t = fits(e.map, e.key);
436
504
  const id = t ? `c:${e.map}(${t.parts.join(',')})` : `c:${e.map}#${textOfE(e.key)}`;
437
- if (!ords.has(id)) {
438
- ords.add(id);
439
- if (t) {
440
- if (!ordCells.has(e.map))
441
- ordCells.set(e.map, []);
442
- ordCells.get(e.map).push({ id, parts: t.parts });
443
- }
444
- else
445
- ordOdd.push({ id, map: e.map, key: e.key });
446
- }
505
+ if (!ordInfo.has(id))
506
+ ordInfo.set(id, t ? { map: e.map, parts: t.parts } : { map: e.map, key: e.key });
507
+ touch(id);
447
508
  return id;
448
509
  }
449
510
  return undefined;
@@ -468,7 +529,7 @@ function decide0(goal, patterns, opts) {
468
529
  // t1 − t2 + d ⋈ 0 as order atoms (naturals: t1 < t2 is t1 + 1 ≤ t2), or undefined
469
530
  // (a constant side takes the offset: t + d ⋈ k:c is t ⋈ k:(c − d), nothing below 0; t1 = t2 + 1, the successor, is an atom
470
531
  // that implies t2 < t1 with no term between, one way only: a gap no term names leaves it unknown)
471
- const succs = [];
532
+ const succs = [], succAt = new Map();
472
533
  const ordAtom = (t1, t2, d, op) => {
473
534
  const num = (x) => (x.startsWith('k:') ? Number(x.slice(2)) : undefined), n1 = num(t1), n2 = num(t2);
474
535
  if (n1 !== undefined && n2 !== undefined) {
@@ -479,14 +540,14 @@ function decide0(goal, patterns, opts) {
479
540
  const c = n2 - d;
480
541
  if (c < 0)
481
542
  return Fa;
482
- ords.add(`k:${c}`);
543
+ touch(`k:${c}`);
483
544
  return ordAtom(t1, `k:${c}`, 0, op);
484
545
  }
485
546
  if (n1 !== undefined && d !== 0) {
486
547
  const c = n1 + d;
487
548
  if (c < 0)
488
549
  return op === '=' ? Fa : T;
489
- ords.add(`k:${c}`);
550
+ touch(`k:${c}`);
490
551
  return ordAtom(`k:${c}`, t2, 0, op);
491
552
  }
492
553
  const D = op === '<' ? d + 1 : d;
@@ -496,7 +557,12 @@ function decide0(goal, patterns, opts) {
496
557
  if (Math.abs(d) !== 1)
497
558
  return undefined;
498
559
  const [lo, hi] = d === -1 ? [t2, t1] : [t1, t2], s = atom(`succ ${lo} ${hi}`);
499
- succs.push({ s: s.v, lo, hi });
560
+ let si = succAt.get(s.v);
561
+ if (si === undefined) {
562
+ succAt.set(s.v, (si = succs.length));
563
+ succs.push({ s: s.v, lo, hi });
564
+ }
565
+ use.succ.push(si);
500
566
  return s;
501
567
  }
502
568
  return D === 0 ? le(t1, t2) : D === 1 ? not(le(t2, t1)) : undefined;
@@ -559,32 +625,74 @@ function decide0(goal, patterns, opts) {
559
625
  };
560
626
  const sum = (e, k, ts, d) => e.op === 'const' ? ((d.c += k * e.value), true) : e.op === 'add' ? sum(e.a, k, ts, d) && sum(e.b, k, ts, d) : e.op === 'mul' ? sum(e.a, k * e.k, ts, d)
561
627
  : e.op === 'sub' && exactSub(e) ? sum(e.a, k, ts, d) && sum(e.b, -k, ts, d) : (ts.push([e, k]), true);
562
- // (an opaque comparison that reads only key parts and constants: an instance at a key of the wrong sort, harmless; one
563
- // that reads a scalar or a cell is arithmetic the abstraction can't read: a counter, a sum, a product)
564
- const foreign = new Set(), opaques = new Map();
565
- const opaque = (c) => {
628
+ // the theory: each opaque comparison of key parts, ordered terms and composed keys (a part against 64·e + n, an
629
+ // instance at a key of the wrong sort) as linear arithmetic over the ordered terms, which a model's order is checked
630
+ // against below (each a term of the order, so its axioms hold)
631
+ const tlin = (e) => {
632
+ if (e.op === 'const')
633
+ return konst(e.value);
634
+ if (e.op === 'add') {
635
+ const a = tlin(e.a), b = tlin(e.b);
636
+ return a && b ? plus(a, b) : undefined;
637
+ }
638
+ if (e.op === 'mul') {
639
+ const a = tlin(e.a);
640
+ return a && times(a, e.k);
641
+ }
642
+ const t = ordOf(e);
643
+ return t === undefined ? undefined : t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t);
644
+ };
645
+ const opqs = new Map();
646
+ const opaque = (c, more) => {
566
647
  const a = atom(`op ${textOfE(c)}`);
567
- opaques.set(a.v, c);
568
- let keyOnly = true;
569
- const wk = (o) => { if (!keyOnly || !o || typeof o !== 'object')
570
- return; const x = o; if ((x.op === 'get' && !fnMaps.has(x.map) && !ordMaps.has(x.map)) || (x.op === 'var' && !parts.has(x.name) && !ordScalars.has(x.name))) {
571
- keyOnly = false;
572
- return;
573
- } for (const y of Object.values(o))
574
- wk(y); };
575
- wk(c);
576
- if (!keyOnly)
577
- foreign.add(a.v);
648
+ let o = opqs.get(a.v);
649
+ if (!o) {
650
+ const outer = use;
651
+ use = { ords: [], fins: [], opq: [], succ: [] };
652
+ let keyOnly = true;
653
+ const wk = (q) => { if (!keyOnly || !q || typeof q !== 'object')
654
+ return; const x = q; if ((x.op === 'get' && !fnMaps.has(x.map) && !ordMaps.has(x.map)) || (x.op === 'var' && !parts.has(x.name) && !ordScalars.has(x.name))) {
655
+ keyOnly = false;
656
+ return;
657
+ } for (const y of Object.values(q))
658
+ wk(y); };
659
+ wk(c);
660
+ opqs.set(a.v, (o = { foreign: !keyOnly, tied: !!more, ords: [] }));
661
+ more?.(a.v);
662
+ if (keyOnly && (c.op === '<' || c.op === '<=' || c.op === '=')) {
663
+ const ta = tlin(c.a), tb = tlin(c.b);
664
+ if (ta && tb) {
665
+ o.row = { x: a.v, op: c.op, d: plus(ta, times(tb, -1)) };
666
+ kept.add(a.v);
667
+ }
668
+ }
669
+ o.ords = use.ords;
670
+ outer.fins.push(...use.fins);
671
+ outer.succ.push(...use.succ);
672
+ use = outer;
673
+ }
674
+ use.opq.push(a.v);
675
+ use.ords.push(...o.ords);
578
676
  return a;
579
677
  };
678
+ // an interval of a prefix: equal prefixes give lo always and hi where X's low parts are under their bounds; lo and hi
679
+ // with every part of X and L but the top under its bound give equal prefixes (a pair of one X and one L)
680
+ const baseOf = (coefs, i) => coefs[i - 1] / coefs[i];
681
+ const pairs = new Map();
580
682
  const comparison = (c) => {
581
683
  // a key equality: two tuples of one shape
582
684
  if (c.op === '=') {
583
685
  const ta = tupleOf(c.a), tb = tupleOf(c.b);
584
686
  if (ta && tb && sameCoefs(ta.coefs, tb.coefs) && [...ta.parts, ...tb.parts].every(p => parts.has(p))) {
585
- const p = opaque(c);
586
- keyEqs.push({ p, a: ta, b: tb });
587
- return p;
687
+ // equal parts: equal keys, always; equal keys with every part but the top under its bound: equal parts
688
+ return opaque(c, pv => {
689
+ const es = ta.parts.map((x, i) => eq(x, tb.parts[i]));
690
+ add([...es.map(e => (e.k === 'v' ? -e.v : 0)).filter(Boolean), pv], -1);
691
+ const bd = ta.bounds.flatMap((b, i) => (b === undefined ? [] : [v(ltAt(ta.parts[i], b)), v(ltAt(tb.parts[i], b))]));
692
+ for (const e of es)
693
+ if (e.k === 'v')
694
+ add([-pv, ...bd.map(l => -l), e.v], -1);
695
+ });
588
696
  }
589
697
  }
590
698
  const ts = [], d = { c: 0 };
@@ -611,9 +719,24 @@ function decide0(goal, patterns, opts) {
611
719
  const lo = k0 === 0 && chainOf(neg).at(-1) === 1 && isChain(chainOf(neg)) && prefix(chainOf(neg), chainOf(pos));
612
720
  const hi = chainOf(pos).at(-1) === 1 && isChain(chainOf(pos)) && prefix(chainOf(pos), chainOf(neg)) && neg.length > 0 && k0 === 1 - neg.at(-1)[1];
613
721
  if (lo || hi) {
614
- const X = lo ? neg : pos, L = lo ? pos : neg, a = opaque(c);
615
- intervals.push({ p: a, kind: lo ? 'lo' : 'hi', X: X.map(t => t[0]), L: L.map(t => t[0]), coefs: chainOf(X) });
616
- return a;
722
+ const X = (lo ? neg : pos).map(t => t[0]), L = (lo ? pos : neg).map(t => t[0]), coefs = chainOf(lo ? neg : pos), kind = lo ? 'lo' : 'hi';
723
+ return opaque(c, pv => {
724
+ const pe = L.map((y, i) => eq(X[i], y));
725
+ const lowBounded = X.flatMap((x, i) => (i >= L.length ? [v(ltAt(x, baseOf(coefs, i)))] : []));
726
+ add([...pe.filter(e => e.k === 'v').map(e => -e.v), ...(kind === 'hi' ? lowBounded.map(l => -l) : []), pv], -1);
727
+ const key = `${X.join(',')}|${L.join(',')}`, pr = pairs.get(key) ?? { X, L, coefs };
728
+ const had = pr.lo !== undefined && pr.hi !== undefined;
729
+ pr[kind] = pv;
730
+ pairs.set(key, pr);
731
+ if (had || pr.lo === undefined || pr.hi === undefined)
732
+ return;
733
+ const bd = [...pr.X.flatMap((x, i) => (i ? [v(ltAt(x, baseOf(pr.coefs, i)))] : [])), ...pr.L.flatMap((y, i) => (i ? [v(ltAt(y, baseOf(pr.coefs, i)))] : []))];
734
+ for (const [i, y] of pr.L.entries()) {
735
+ const e = eq(pr.X[i], y);
736
+ if (e.k === 'v')
737
+ add([-pr.lo, -pr.hi, ...bd.map(l => -l), e.v], -1);
738
+ }
739
+ });
617
740
  }
618
741
  }
619
742
  // ordered: a term against another, or a constant, one of them an ordered cell or scalar
@@ -627,7 +750,7 @@ function decide0(goal, patterns, opts) {
627
750
  }
628
751
  // finite: every term finite, coefficients of one sign
629
752
  // (the terms not exact of one sign, the exact ones of any: a capped term at its cap decides it as any larger value)
630
- const cs = ts.length ? ts.map(([e]) => cases(e)) : [], loose = ts.filter((_, i) => !cs[i]?.every(y => y.n !== undefined || y.f.exact !== undefined));
753
+ const cs = ts.length ? ts.map(([e]) => cases(e)) : [], loose = ts.filter((_, i) => !cs[i]?.every(y => y.n !== undefined || y.f.exact));
631
754
  if (ts.length && (loose.every(t => t[1] > 0) || loose.every(t => t[1] < 0))) {
632
755
  if (cs.every(Boolean)) {
633
756
  const holds = (v) => (c.op === '<' ? v < 0 : c.op === '<=' ? v <= 0 : v === 0);
@@ -673,782 +796,883 @@ function decide0(goal, patterns, opts) {
673
796
  case 'flag': return opaque(c);
674
797
  }
675
798
  };
676
- const forms = hyps.map(h => (tick(), h ? lit(h) : undefined));
677
- // the theory: each opaque comparison of key parts, ordered terms and composed keys (a part against 64·e + n, an
678
- // instance at a key of the wrong sort) as linear arithmetic over the ordered terms, which a model's order is checked
679
- // against below (each a term of the order, so its axioms hold)
680
- const tlin = (e) => {
681
- if (e.op === 'const')
682
- return konst(e.value);
683
- if (e.op === 'add') {
684
- const a = tlin(e.a), b = tlin(e.b);
685
- return a && b ? plus(a, b) : undefined;
686
- }
687
- if (e.op === 'mul') {
688
- const a = tlin(e.a);
689
- return a && times(a, e.k);
799
+ // --- clauses (literals: +v / −v), each with the hypothesis it stands for, into the search at once
800
+ const solver = cdclSolver(first, kept);
801
+ const add = (lits, from) => {
802
+ tick();
803
+ // (a short clause, the order's axioms' above all, without a Set: the same literals in the same order)
804
+ if (lits.length <= 4) {
805
+ const out = [];
806
+ for (const l of lits) {
807
+ if (out.includes(-l))
808
+ return;
809
+ if (!out.includes(l))
810
+ out.push(l);
811
+ }
812
+ solver.add({ lits: out, from });
813
+ return;
690
814
  }
691
- const t = ordOf(e);
692
- return t === undefined ? undefined : t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t);
815
+ const s = new Set(lits);
816
+ for (const l of s)
817
+ if (s.has(-l))
818
+ return;
819
+ solver.add({ lits: [...s], from });
693
820
  };
694
- const theory = [...opaques].filter(([x]) => !foreign.has(x)).flatMap(([x, c]) => {
695
- if (c.op !== '<' && c.op !== '<=' && c.op !== '=')
696
- return [];
697
- const a = tlin(c.a), b = tlin(c.b);
698
- return a && b ? [{ x, op: c.op, d: plus(a, times(b, -1)) }] : [];
699
- });
700
- // (an order over many terms is a cubic number of transitivity clauses: past 64 terms they are added lazily, those a
701
- // model breaks, below; past 512, the totality's pairs alone are too many, and the goal keeps the usual path)
702
- // (`fill`: the constants between two near ones too, so that discreteness counts the room between them: k:0 < x < y < k:2
703
- // has none, which the read-back meets)
704
- if (opts.fill) {
705
- const cs = [...ords].filter(x => x.startsWith('k:')).map(x => Number(x.slice(2))).sort((a, b) => a - b);
706
- for (let i = 0; i + 1 < cs.length; i++)
707
- if (cs[i + 1] - cs[i] <= 4)
708
- for (let c = cs[i] + 1; c < cs[i + 1]; c++)
709
- ords.add(`k:${c}`);
710
- }
711
- if (ords.size > 512)
712
- return { unknown: `${ords.size} ordered terms` };
713
- const lazy = ords.size > 64;
714
- // --- clauses (literals: +v / −v), each with the hypotheses it stands for
715
- const clauses = [];
716
- const add = (lits, from) => { tick(); const s = new Set(lits); for (const l of s)
717
- if (s.has(-l))
718
- return; clauses.push({ lits: [...s], from }); };
719
821
  let fresh = 0;
720
- const tseitin = (f, from) => {
822
+ // (a Tseitin variable's definition holds in every model: an axiom; the hypothesis' own clause is the guarded one)
823
+ const tseitin = (f) => {
721
824
  if (f.k === 'v')
722
825
  return f.v;
723
826
  if (f.k === 'not')
724
- return -tseitin(f.x, from);
827
+ return -tseitin(f.x);
725
828
  if (f.k === 'c') {
726
829
  const g = ++fresh + 1e6;
727
830
  add([f.b ? g : -g], -1);
728
831
  return g;
729
832
  }
730
- const ls = f.xs.map(x => tseitin(x, from)), g = ++fresh + 1e6;
833
+ const ls = f.xs.map(x => tseitin(x)), g = ++fresh + 1e6;
731
834
  if (f.k === 'and') {
732
835
  for (const l of ls)
733
- add([-g, l], from);
734
- add([g, ...ls.map(l => -l)], from);
836
+ add([-g, l], -1);
837
+ add([g, ...ls.map(l => -l)], -1);
735
838
  }
736
839
  else {
737
- add([-g, ...ls], from);
840
+ add([-g, ...ls], -1);
738
841
  for (const l of ls)
739
- add([g, -l], from);
842
+ add([g, -l], -1);
740
843
  }
741
844
  return g;
742
845
  };
743
- const top = (f, from) => {
846
+ const top = (f, from, ng) => {
744
847
  if (f.k === 'and') {
745
848
  for (const x of f.xs)
746
- top(x, from);
849
+ top(x, from, ng);
747
850
  return;
748
851
  }
749
852
  if (f.k === 'c') {
750
853
  if (!f.b)
751
- add([], from);
854
+ add([ng], from);
752
855
  return;
753
856
  }
754
857
  if (f.k === 'or' && f.xs.every(x => x.k === 'v' || (x.k === 'not' && x.x.k === 'v'))) {
755
- add(f.xs.map(x => (x.k === 'v' ? x.v : -x.x.v)), from);
858
+ add([ng, ...f.xs.map(x => (x.k === 'v' ? x.v : -x.x.v))], from);
756
859
  return;
757
860
  }
758
- add([tseitin(f, from)], from);
861
+ add([ng, tseitin(f)], from);
759
862
  };
760
- forms.forEach((f, i) => { if (f)
761
- top(f, i); });
762
- // axioms: congruence of cells; a composed key's injectivity where its parts are under their bounds; one value per finite
763
- // variable; the order (below), whose transitivity is equality's and the bounds' too
764
863
  const v = (f) => (f.k === 'v' ? f.v : f.k === 'not' && f.x.k === 'v' ? -f.x.v : undefined);
765
- for (const { p, a, b } of keyEqs) {
766
- const pv = v(p), es = a.parts.map((x, i) => eq(x, b.parts[i]));
767
- // equal parts: equal keys, always; equal keys with every part but the top under its bound: equal parts
768
- add([...es.map(e => (e.k === 'v' ? -e.v : 0)).filter(Boolean), pv], -1);
769
- const bounded = a.bounds.flatMap((bd, i) => (bd === undefined ? [] : [v(ltAt(a.parts[i], bd)), v(ltAt(b.parts[i], bd))]));
770
- for (const e of es)
771
- if (e.k === 'v')
772
- add([-pv, ...bounded.map(l => -l), e.v], -1);
773
- }
774
- // an interval of a prefix: equal prefixes give lo always and hi where X's low parts are under their bounds; lo and hi
775
- // with every part of X and L but the top under its bound give equal prefixes (a pair of one X and one L)
776
- const baseOf = (coefs, i) => coefs[i - 1] / coefs[i];
777
- const pairs = new Map();
778
- for (const iv of intervals) {
779
- const pe = iv.L.map((y, i) => eq(iv.X[i], y)), pv = v(iv.p);
780
- const lowBounded = iv.X.flatMap((x, i) => (i >= iv.L.length ? [v(ltAt(x, baseOf(iv.coefs, i)))] : []));
781
- add([...pe.filter(e => e.k === 'v').map(e => -e.v), ...(iv.kind === 'hi' ? lowBounded.map(l => -l) : []), pv], -1);
782
- const key = `${iv.X.join(',')}|${iv.L.join(',')}`, pr = pairs.get(key) ?? { X: iv.X, L: iv.L, coefs: iv.coefs };
783
- pr[iv.kind] = pv;
784
- pairs.set(key, pr);
785
- }
786
- for (const pr of pairs.values()) {
787
- if (pr.lo === undefined || pr.hi === undefined)
788
- continue;
789
- const bounded = [...pr.X.flatMap((x, i) => (i ? [v(ltAt(x, baseOf(pr.coefs, i)))] : [])), ...pr.L.flatMap((y, i) => (i ? [v(ltAt(y, baseOf(pr.coefs, i)))] : []))];
790
- for (const [i, y] of pr.L.entries()) {
791
- const e = eq(pr.X[i], y);
792
- if (e.k === 'v')
793
- add([-pr.lo, -pr.hi, ...bounded.map(l => -l), e.v], -1);
864
+ // --- the hypotheses, each once by its text
865
+ const hyps = new Map();
866
+ const encode = (f) => {
867
+ let hp = hyps.get(f.text);
868
+ if (hp)
869
+ return hp;
870
+ const gid = hyps.size, a = ++fresh + 1e6;
871
+ use = { ords: [], fins: [], opq: [], succ: [] };
872
+ for (const [k, b] of f.bounds) {
873
+ let xs = boundBy.get(k);
874
+ if (!xs)
875
+ boundBy.set(k, (xs = []));
876
+ xs.push({ a, gid, b });
877
+ const ef = exactFins.get(k);
878
+ if (ef && ef.cap === b)
879
+ add([-a, ...Array.from({ length: b + 1 }, (_, val) => v(finAt(ef, val)))], gid);
794
880
  }
795
- }
796
- for (const [, cells] of cellsOf)
797
- for (let i = 0; i < cells.length; i++)
798
- for (let j = i + 1; j < cells.length; j++) {
799
- const a = cells[i], b = cells[j], es = a.parts.map((x, k) => v(eq(x, b.parts[k])));
800
- const fa = fins.get(a.id), fb = fins.get(b.id), cap = Math.max(fa.cap, fb.cap);
881
+ tick();
882
+ if (f.h)
883
+ top(lit(f.h), gid, -a);
884
+ hp = { a, gid, use };
885
+ hyps.set(f.text, hp);
886
+ return hp;
887
+ };
888
+ // --- the axioms over every term so far, each once: congruence of cells; one value per finite variable (above); the
889
+ // order: total, transitive (lazily past 64 terms), discrete, the constants in their order, every term at least 0, a part's
890
+ // equality its order both ways, equal tuples equal ordered cells; a function's reads at equal parts are equal
891
+ // (Ackermann); a successor has nothing between it and its predecessor
892
+ const num = (x) => (x.startsWith('k:') ? Number(x.slice(2)) : undefined);
893
+ const os = [], cellsBy = new Map(), ordCellsBy = new Map(), fnAll = [], fnSeen = new Set(), discrete = new Set();
894
+ let nFins = 0, nSuccs = 0, nFn = 0, lazy = false;
895
+ const pairsOn = (xs, from, f) => { for (let j = from; j < xs.length; j++)
896
+ for (let i = 0; i < j; i++)
897
+ f(xs[i], xs[j]); };
898
+ const close = (gst) => {
899
+ for (; nFins < finsList.length; nFins++) {
900
+ const b = finsList[nFins];
901
+ if (!b.map || !b.parts)
902
+ continue;
903
+ let cells = cellsBy.get(b.map);
904
+ if (!cells)
905
+ cellsBy.set(b.map, (cells = []));
906
+ cells.push(b);
907
+ for (const a of cells.slice(0, -1)) {
908
+ const es = a.parts.map((x, k) => v(eq(x, b.parts[k]))), cap = Math.max(a.cap, b.cap);
909
+ const pre = es.filter((e) => e !== undefined).map(e => -e);
801
910
  for (let val = 0; val <= cap; val++) {
802
- const la = val <= fa.cap ? v(finAt(fa, val)) : undefined, lb = val <= fb.cap ? v(finAt(fb, val)) : undefined;
803
- const pre = es.filter((e) => e !== undefined).map(e => -e);
911
+ const la = val <= a.cap ? v(finAt(a, val)) : undefined, lb = val <= b.cap ? v(finAt(b, val)) : undefined;
804
912
  if (la !== undefined)
805
913
  add([...pre, -la, ...(lb !== undefined ? [lb] : [])], -1);
806
914
  if (lb !== undefined)
807
915
  add([...pre, -lb, ...(la !== undefined ? [la] : [])], -1);
808
916
  }
809
917
  }
810
- // the order: total, transitive, discrete, the constants in their order, every term at least 0, a part's equality its
811
- // order both ways, equal tuples equal ordered cells
812
- {
813
- const os = [...ords], num = (x) => (x.startsWith('k:') ? Number(x.slice(2)) : undefined);
814
- for (let i = 0; i < os.length; i++)
815
- for (let j = i + 1; j < os.length; j++) {
816
- const a = os[i], b = os[j], na = num(a), nb = num(b);
817
- add([v(le(a, b)), v(le(b, a))], -1);
818
- if (na !== undefined && nb !== undefined) {
819
- add([na <= nb ? v(le(a, b)) : -v(le(a, b))], -1);
820
- add([nb <= na ? v(le(b, a)) : -v(le(b, a))], -1);
821
- }
918
+ }
919
+ const o0 = os.length, all0 = [...ords];
920
+ for (let i = o0; i < all0.length; i++)
921
+ os.push(all0[i]);
922
+ if (os.length > 64)
923
+ lazy = true;
924
+ pairsOn(os, o0, (a, b) => {
925
+ add([v(le(a, b)), v(le(b, a))], -1);
926
+ const na = num(a), nb = num(b);
927
+ if (na !== undefined && nb !== undefined) {
928
+ add([na <= nb ? v(le(a, b)) : -v(le(a, b))], -1);
929
+ add([nb <= na ? v(le(b, a)) : -v(le(b, a))], -1);
930
+ }
931
+ if (a.startsWith('p:') && b.startsWith('p:')) {
932
+ const e = v(eq(a.slice(2), b.slice(2))), x = v(le(a, b)), y = v(le(b, a));
933
+ add([-e, x], -1);
934
+ add([-e, y], -1);
935
+ add([e, -x, -y], -1);
822
936
  }
823
- for (const x of os)
937
+ });
938
+ for (const x of os.slice(o0))
824
939
  if (x !== 'k:0')
825
940
  add([v(le('k:0', x))], -1);
826
941
  // (the naturals are discrete: nothing between c and c + 1)
827
942
  for (const c of os.map(num).filter((n) => n !== undefined))
828
943
  if (ords.has(`k:${c + 1}`))
829
944
  for (const x of os)
830
- if (!x.startsWith('k:'))
945
+ if (!x.startsWith('k:') && !discrete.has(`${c}|${x}`)) {
946
+ discrete.add(`${c}|${x}`);
831
947
  add([v(le(x, `k:${c}`)), v(le(`k:${c + 1}`, x))], -1);
948
+ }
832
949
  if (!lazy)
833
- for (const a of os)
834
- for (const b of os)
835
- if (a !== b)
836
- for (const c of os)
837
- if (c !== a && c !== b)
838
- add([-v(le(a, b)), -v(le(b, c)), v(le(a, c))], -1);
839
- const ordParts = os.filter(x => x.startsWith('p:')).map(x => x.slice(2));
840
- for (let i = 0; i < ordParts.length; i++)
841
- for (let j = i + 1; j < ordParts.length; j++) {
842
- const x = ordParts[i], y = ordParts[j], e = v(eq(x, y)), a = v(le(`p:${x}`, `p:${y}`)), b = v(le(`p:${y}`, `p:${x}`));
843
- add([-e, a], -1);
844
- add([-e, b], -1);
845
- add([e, -a, -b], -1);
950
+ for (let m = o0; m < os.length; m++)
951
+ for (let x = 0; x < m; x++)
952
+ for (let y = 0; y < m; y++)
953
+ if (x !== y) {
954
+ const t = os[m], p = os[x], q = os[y];
955
+ add([-v(le(t, p)), -v(le(p, q)), v(le(t, q))], -1);
956
+ add([-v(le(p, t)), -v(le(t, q)), v(le(p, q))], -1);
957
+ add([-v(le(p, q)), -v(le(q, t)), v(le(p, t))], -1);
958
+ }
959
+ for (const fp of gst.fnParts)
960
+ if (!fnSeen.has(fp.n)) {
961
+ fnSeen.add(fp.n);
962
+ fnAll.push(fp);
846
963
  }
847
- // a function's reads at equal parts are equal (Ackermann); a successor has nothing between it and its predecessor
848
- for (let i = 0; i < fnParts.length; i++)
849
- for (let j = i + 1; j < fnParts.length; j++) {
850
- const x = fnParts[i], y = fnParts[j];
964
+ for (let j = nFn; j < fnAll.length; j++)
965
+ for (let i = 0; i < j; i++) {
966
+ const x = fnAll[i], y = fnAll[j];
851
967
  if (x.f === y.f && x.n !== y.n) {
852
968
  const a = v(eq(x.a, y.a)), b = v(eq(x.n, y.n));
853
969
  if (a !== undefined && b !== undefined)
854
970
  add([-a, b], -1);
855
971
  }
856
972
  }
857
- for (const { s, lo, hi } of succs) {
858
- add([-s, -v(le(hi, lo))], -1);
859
- for (const z of ords)
973
+ nFn = fnAll.length;
974
+ for (let k = 0; k < succs.length; k++) {
975
+ const { s, lo, hi } = succs[k];
976
+ if (k >= nSuccs)
977
+ add([-s, -v(le(hi, lo))], -1);
978
+ for (const z of k >= nSuccs ? os : os.slice(o0))
860
979
  if (z !== lo && z !== hi)
861
980
  add([-s, v(le(z, lo)), v(le(hi, z))], -1);
862
981
  }
863
- for (const [, cells] of ordCells)
864
- for (let i = 0; i < cells.length; i++)
865
- for (let j = i + 1; j < cells.length; j++) {
866
- const a = cells[i], b = cells[j], pre = a.parts.map((x, k) => v(eq(x, b.parts[k]))).filter((e) => e !== undefined).map(e => -e);
867
- add([...pre, v(le(a.id, b.id))], -1);
868
- add([...pre, v(le(b.id, a.id))], -1);
869
- }
870
- }
871
- for (const f of fins.values()) {
872
- const ls = Array.from({ length: f.cap + 1 }, (_, val) => v(finAt(f, val)));
873
- add(ls, f.exact ?? -1);
874
- for (let i = 0; i < ls.length; i++)
875
- for (let j = i + 1; j < ls.length; j++)
876
- add([-ls[i], -ls[j]], -1);
877
- }
878
- if (theory.length && !opts.fresh)
879
- for (const l of lemmaCache.values()) {
880
- const xs = l.map(([k, b]) => { const x = ids.get(k); return x === undefined ? undefined : b ? x : -x; });
881
- if (xs.every((x) => x !== undefined))
882
- add(xs, -1);
883
- }
884
- // EPR-shaped: no comparison the abstraction can't read (a counter's arithmetic, a sum, a product) in any hypothesis
885
- if (opts.exact) {
886
- const tied = new Set([...keyEqs, ...intervals].map(k => k.p.v));
887
- const loose = [...foreign].filter(i => !tied.has(i)).length;
888
- if (loose)
889
- return { unknown: `${loose} comparisons outside the EPR shape` };
890
- }
891
- // --- the search
892
- // (a finite variable at 0 first: models with the least values, which break the fewest laws at keys nothing names)
893
- const first = new Set([...fins.values()].map(f => v(finAt(f, 0))));
894
- if (opts.late?.())
895
- return { unknown: 'past the deadline' };
896
- // (lazily: the transitivity a model breaks, added and the search again, at most 4,096 a round and 16 rounds; as each
897
- // holds in every model, a refutation stays one)
898
- // (one solver, the lemmas added to it: the search goes on from what it learned)
899
- // (the order's atoms and the theory's comparisons keep the phase of the last model: a lemma then moves the next model
900
- // as little as it must, not to the search's first choices again)
901
- const kept = new Set([...ids].filter(([k]) => k.startsWith('le ')).map(([, x]) => x).concat(theory.map(t => t.x)));
902
- let solver = cdclSolver(clauses, first, kept);
903
- const lemma = (lits) => { const n0 = clauses.length; add(lits, -1); if (clauses.length > n0 && !solver.add(clauses.at(-1)))
904
- solver = cdclSolver(clauses, first, kept); };
905
- const search = () => {
906
- let o = solver.solve(opts.conflicts ?? 200_000, opts.late);
907
- for (let round = 0; lazy && o?.sat; round++) {
908
- const m = o.model, os = [...ords], at = (a, b) => a === b || m[v(le(a, b))] === true, broken = [];
909
- for (const a of os)
910
- for (const b of os)
911
- if (a !== b && at(a, b))
912
- for (const c of os)
913
- if (c !== a && c !== b && at(b, c) && !at(a, c) && broken.length < 4096)
914
- broken.push([-v(le(a, b)), -v(le(b, c)), v(le(a, c))]);
915
- if (!broken.length)
916
- break;
917
- if (round === 16 || opts.late?.())
918
- return 'the order\'s transitivity, lazily, did not settle';
919
- for (const c of broken)
920
- lemma(c);
921
- o = solver.solve(opts.conflicts ?? 200_000, opts.late);
982
+ nSuccs = succs.length;
983
+ for (const x of os.slice(o0)) {
984
+ const inf = ordInfo.get(x);
985
+ if (inf?.parts) {
986
+ let cs = ordCellsBy.get(inf.map);
987
+ if (!cs)
988
+ ordCellsBy.set(inf.map, (cs = []));
989
+ cs.push(x);
990
+ }
922
991
  }
923
- return o;
924
- };
925
- // (the model's order, its groups of equal terms in order: the read-back's and the theory's)
926
- const groupsOf = (m) => {
927
- const leq = (a, b) => a === b || m[v(le(a, b))] === true;
928
- const os = [...ords].sort((a, b) => (leq(a, b) && !leq(b, a) ? -1 : leq(b, a) && !leq(a, b) ? 1 : 0)), groups = [];
929
- for (let i = 0; i < os.length;) {
930
- let j = i;
931
- while (j < os.length && leq(os[j], os[i]) && leq(os[i], os[j]))
932
- j++;
933
- groups.push(os.slice(i, j));
934
- i = j;
992
+ for (const [, cells] of ordCellsBy) {
993
+ const from = cells.findIndex(x => os.indexOf(x) >= o0);
994
+ if (from >= 0)
995
+ pairsOn(cells, from, (a, b) => {
996
+ const pa = ordInfo.get(a).parts, pb = ordInfo.get(b).parts, pre = pa.map((x, k) => v(eq(x, pb[k]))).filter((e) => e !== undefined).map(e => -e);
997
+ add([...pre, v(le(a, b))], -1);
998
+ add([...pre, v(le(b, a))], -1);
999
+ });
935
1000
  }
936
- return groups;
937
- };
938
- // The theory's check of a model: its order (each group's terms equal, each group below the next, a successor the next
939
- // value), every ordered term a natural, each theory comparison as the model has it, solved over the integers. Sat: the
940
- // values, the read-back's; refuted: the model's literals its refutation reads, whose negation holds in every model (a
941
- // theory lemma, DPLL(T)'s), added and the search again.
942
- // (first over the theory's own terms, each pair as the model orders it, so that a lemma names them alone; then every
943
- // term, the model's order as its groups, for the values)
944
- const theoryTerms = [...new Set(theory.flatMap(t => Object.keys(t.d).filter(x => x !== '1')))];
945
- // (each comparison's literals: its own and its terms' order, among them and with the constants)
946
- const feasible = [], locals = [];
947
- const localOf = (ti, t, ks) => {
948
- if (locals[ti])
949
- return locals[ti];
950
- const xs = Object.keys(t.d).filter(x => x !== '1'), out = [t.x];
951
- for (let i2 = 0; i2 < xs.length; i2++)
952
- for (const b of [...xs.slice(i2 + 1), ...ks])
953
- for (const [p, q] of [[xs[i2], b], [b, xs[i2]]]) {
954
- const x = v(le(p, q));
955
- if (x !== undefined)
956
- out.push(x);
957
- }
958
- return (locals[ti] = out);
959
1001
  };
960
- const jointLp = new Simplex(true);
961
- // (each pair's order atoms and its four rows, a ≤ b, b < a, b ≤ a, a < b, made once: the same rows every round, which
962
- // the simplex knows by their objects)
963
- const pairs0 = new Map();
964
- const pairOf = (a, b) => {
965
- const key = `${a}|${b}`;
966
- let p = pairs0.get(key);
967
- if (!p) {
968
- const T = (t) => (t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t));
969
- p = { ab: v(le(a, b)), ba: v(le(b, a)), rows: [plus(T(a), times(T(b), -1)), plus(plus(T(b), konst(1)), times(T(a), -1)), plus(T(b), times(T(a), -1)), plus(plus(T(a), konst(1)), times(T(b), -1))] };
970
- pairs0.set(key, p);
971
- }
972
- return p;
973
- };
974
- const theoryCheck = (m) => {
975
- const T = (t) => (t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t));
976
- const theoryRows = (row) => {
977
- for (const t of theory) {
978
- const holds = m[t.x] === true;
979
- if (t.op === '=') {
980
- if (holds) {
981
- row(t.d, [t.x]);
982
- row(times(t.d, -1), [t.x]);
1002
+ const lemmasIn = new Set();
1003
+ let lastGoal = '';
1004
+ const seedLemmas = () => { for (const [key, l] of lemmaCache) {
1005
+ if (lemmasIn.has(key))
1006
+ continue;
1007
+ const xs = l.map(([k, b]) => { const x = ids.get(k); return x === undefined ? undefined : b ? x : -x; });
1008
+ if (xs.every((x) => x !== undefined)) {
1009
+ lemmasIn.add(key);
1010
+ add(xs, -1);
1011
+ }
1012
+ } };
1013
+ const decideGoal = (goal, fs, gst, opts) => {
1014
+ tick = () => { eprMeter.n++; if ((++ticks & 4095) === 0 && opts.late?.())
1015
+ throw pastEnd; };
1016
+ let ticks = 0;
1017
+ const hs = fs.map(encode), gOrds = new Set(['k:0', ...[...parts].map(x => `p:${x}`)]), gFins = new Set(), gOpq = new Set(), gSuccs = new Set();
1018
+ for (const h of hs) {
1019
+ for (const x of h.use.ords)
1020
+ gOrds.add(x);
1021
+ for (const f of h.use.fins)
1022
+ gFins.add(f);
1023
+ for (const x of h.use.opq)
1024
+ gOpq.add(x);
1025
+ for (const x of h.use.succ)
1026
+ gSuccs.add(x);
1027
+ }
1028
+ // (`fill`: the constants between two near ones too, so that discreteness counts the room between them: k:0 < x < y < k:2
1029
+ // has none, which the read-back meets)
1030
+ if (opts.fill) {
1031
+ const cs = [...gOrds].filter(x => x.startsWith('k:')).map(x => Number(x.slice(2))).sort((a, b) => a - b);
1032
+ for (let i = 0; i + 1 < cs.length; i++)
1033
+ if (cs[i + 1] - cs[i] <= 4)
1034
+ for (let c = cs[i] + 1; c < cs[i + 1]; c++) {
1035
+ ords.add(`k:${c}`);
1036
+ gOrds.add(`k:${c}`);
983
1037
  }
984
- continue;
985
- }
986
- // a − b < 0 is a − b + 1 ≤ 0; its negation b − a ≤ 0; a − b ≤ 0's negation b − a + 1 ≤ 0
987
- if (holds)
988
- row(t.op === '<' ? plus(t.d, konst(1)) : t.d, [t.x]);
989
- else
990
- row(t.op === '<' ? times(t.d, -1) : plus(times(t.d, -1), konst(1)), [-t.x]);
1038
+ }
1039
+ // (an order over many terms is a cubic number of transitivity clauses: past 64 terms they are added lazily, those a
1040
+ // model breaks, below; past 512, the totality's pairs alone are too many, and the goal keeps the usual path)
1041
+ // (a finite variable read as exact here and not there, or at another bound: this goal's sorts aren't the encoder's)
1042
+ for (const f of gFins)
1043
+ if (gst.bounded.get(f.bkey) !== (f.exact ? f.cap : undefined))
1044
+ return { unknown: other };
1045
+ if (gOrds.size > 512 || ords.size > 512) {
1046
+ over = true;
1047
+ return { unknown: `${gOrds.size} ordered terms` };
1048
+ }
1049
+ close(gst);
1050
+ const theory = [...gOpq].flatMap(x => { const o = opqs.get(x); return !o.foreign && o.row ? [o.row] : []; });
1051
+ if (theory.length && !opts.fresh)
1052
+ seedLemmas();
1053
+ // EPR-shaped: no comparison the abstraction can't read (a counter's arithmetic, a sum, a product) in any hypothesis
1054
+ if (opts.exact) {
1055
+ const loose = [...gOpq].filter(x => { const o = opqs.get(x); return o.foreign && !o.tied; }).length;
1056
+ if (loose)
1057
+ return { unknown: `${loose} comparisons outside the EPR shape` };
1058
+ }
1059
+ // --- the search, the goal's hypotheses assumed
1060
+ if (opts.late?.())
1061
+ return { unknown: 'past the deadline' };
1062
+ if (goal.name !== lastGoal)
1063
+ solver.fresh();
1064
+ lastGoal = goal.name;
1065
+ const assume = [...new Set(hs.map(h => h.a))], index = new Map();
1066
+ hs.forEach((h, i) => { if (!index.has(h.gid))
1067
+ index.set(h.gid, i); });
1068
+ const lemma = (lits) => add(lits, -1);
1069
+ const gos = [...gOrds];
1070
+ // (lazily: the transitivity a model breaks among the goal's terms, added and the search again, at most 4,096 a round
1071
+ // and 16 rounds; as each holds in every model, a refutation stays one)
1072
+ const search = () => {
1073
+ let o = solver.solve(opts.conflicts ?? 200_000, opts.late, assume);
1074
+ for (let round = 0; lazy && o?.sat; round++) {
1075
+ const m = o.model, at = (a, b) => a === b || m[v(le(a, b))] === true, broken = [];
1076
+ for (const a of gos)
1077
+ for (const b of gos)
1078
+ if (a !== b && at(a, b))
1079
+ for (const c of gos)
1080
+ if (c !== a && c !== b && at(b, c) && !at(a, c) && broken.length < 4096)
1081
+ broken.push([-v(le(a, b)), -v(le(b, c)), v(le(a, c))]);
1082
+ if (!broken.length)
1083
+ break;
1084
+ if (round === 16 || opts.late?.())
1085
+ return 'the order\'s transitivity, lazily, did not settle';
1086
+ for (const c of broken)
1087
+ lemma(c);
1088
+ o = solver.solve(opts.conflicts ?? 200_000, opts.late, assume);
991
1089
  }
1090
+ return o;
992
1091
  };
993
- const lemmaOf = (r, lits) => {
994
- if (r.kind !== 'refuted')
995
- return undefined;
996
- const used = new Set();
997
- for (const st of r.steps)
998
- if (st.kind === 'input')
999
- for (const l of lits[st.index])
1000
- used.add(l);
1001
- return used.size ? [...used].map(l => -l) : undefined;
1092
+ // (the model's order, its groups of equal terms in order: the read-back's and the theory's)
1093
+ const groupsOf = (m) => {
1094
+ const leq = (a, b) => a === b || m[v(le(a, b))] === true;
1095
+ const os2 = [...gos].sort((a, b) => (leq(a, b) && !leq(b, a) ? -1 : leq(b, a) && !leq(a, b) ? 1 : 0)), groups = [];
1096
+ for (let i = 0; i < os2.length;) {
1097
+ let j = i;
1098
+ while (j < os2.length && leq(os2[j], os2[i]) && leq(os2[i], os2[j]))
1099
+ j++;
1100
+ groups.push(os2.slice(i, j));
1101
+ i = j;
1102
+ }
1103
+ return groups;
1002
1104
  };
1003
- const pairRows = (row, a, b) => {
1004
- const p = pairOf(a, b);
1005
- if (m[p.ab] === true)
1006
- row(p.rows[0], [p.ab]);
1007
- else
1008
- row(p.rows[1], [-p.ab]);
1009
- if (m[p.ba] === true)
1010
- row(p.rows[2], [p.ba]);
1011
- else
1012
- row(p.rows[3], [-p.ba]);
1105
+ const succList = [...gSuccs].map(k => succs[k]);
1106
+ // The theory's check of a model: its order (each group's terms equal, each group below the next, a successor the next
1107
+ // value), every ordered term a natural, each theory comparison as the model has it, solved over the integers. Sat: the
1108
+ // values, the read-back's; refuted: the model's literals its refutation reads, whose negation holds in every model (a
1109
+ // theory lemma, DPLL(T)'s), added and the search again.
1110
+ // (first over the theory's own terms, each pair as the model orders it, so that a lemma names them alone; then every
1111
+ // term, the model's order as its groups, for the values)
1112
+ const theoryTerms = [...new Set(theory.flatMap(t => Object.keys(t.d).filter(x => x !== '1')))];
1113
+ // (each comparison's literals: its own and its terms' order, among them and with the constants)
1114
+ const feasible = [], locals = [];
1115
+ const localOf = (ti, t, ks) => {
1116
+ if (locals[ti])
1117
+ return locals[ti];
1118
+ const xs = Object.keys(t.d).filter(x => x !== '1'), out = [t.x];
1119
+ for (let i2 = 0; i2 < xs.length; i2++)
1120
+ for (const b of [...xs.slice(i2 + 1), ...ks])
1121
+ for (const [p, q] of [[xs[i2], b], [b, xs[i2]]]) {
1122
+ const x = v(le(p, q));
1123
+ if (x !== undefined)
1124
+ out.push(x);
1125
+ }
1126
+ return (locals[ti] = out);
1013
1127
  };
1014
- // (each comparison alone first, with its terms' order and the constants: a lemma of a few literals for each the
1015
- // model breaks, all of them in one round; one the model reads as an earlier model did, feasible then, not again)
1016
- {
1017
- const ks = [...ords].filter(t => t.startsWith('k:')), lemmas = [];
1018
- for (const [ti, t] of theory.entries()) {
1019
- const local = localOf(ti, t, ks), seen = (feasible[ti] ??= new Set()), key = local.map(l => (m[l] === true ? '1' : '0')).join('');
1020
- if (seen.has(key))
1021
- continue;
1022
- const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1023
- const xs = Object.keys(t.d).filter(x => x !== '1');
1024
- for (const x of xs)
1025
- row(times(tv(x), -1), []);
1026
- for (let i2 = 0; i2 < xs.length; i2++) {
1027
- for (let j = i2 + 1; j < xs.length; j++)
1028
- pairRows(row, xs[i2], xs[j]);
1029
- for (const k2 of ks)
1030
- pairRows(row, xs[i2], k2);
1031
- }
1032
- const holds = m[t.x] === true;
1033
- if (t.op === '=') {
1034
- if (holds) {
1035
- row(t.d, [t.x]);
1036
- row(times(t.d, -1), [t.x]);
1128
+ const jointLp = new Simplex(true);
1129
+ // (each pair's order atoms and its four rows, a ≤ b, b < a, b ≤ a, a < b, made once: the same rows every round, which
1130
+ // the simplex knows by their objects)
1131
+ const pairs0 = new Map();
1132
+ const pairOf = (a, b) => {
1133
+ const key = `${a}|${b}`;
1134
+ let p = pairs0.get(key);
1135
+ if (!p) {
1136
+ const T = (t) => (t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t));
1137
+ p = { ab: v(le(a, b)), ba: v(le(b, a)), rows: [plus(T(a), times(T(b), -1)), plus(plus(T(b), konst(1)), times(T(a), -1)), plus(T(b), times(T(a), -1)), plus(plus(T(a), konst(1)), times(T(b), -1))] };
1138
+ pairs0.set(key, p);
1139
+ }
1140
+ return p;
1141
+ };
1142
+ const theoryCheck = (m) => {
1143
+ const T = (t) => (t.startsWith('k:') ? konst(Number(t.slice(2))) : tv(t));
1144
+ const theoryRows = (row) => {
1145
+ for (const t of theory) {
1146
+ const holds = m[t.x] === true;
1147
+ if (t.op === '=') {
1148
+ if (holds) {
1149
+ row(t.d, [t.x]);
1150
+ row(times(t.d, -1), [t.x]);
1151
+ }
1152
+ continue;
1037
1153
  }
1154
+ // a − b < 0 is a − b + 1 ≤ 0; its negation b − a ≤ 0; a − b ≤ 0's negation b − a + 1 ≤ 0
1155
+ if (holds)
1156
+ row(t.op === '<' ? plus(t.d, konst(1)) : t.d, [t.x]);
1038
1157
  else
1039
- continue;
1158
+ row(t.op === '<' ? times(t.d, -1) : plus(times(t.d, -1), konst(1)), [-t.x]);
1040
1159
  }
1041
- else if (holds)
1042
- row(t.op === '<' ? plus(t.d, konst(1)) : t.d, [t.x]);
1160
+ };
1161
+ const lemmaOf = (r, lits) => {
1162
+ if (r.kind !== 'refuted')
1163
+ return undefined;
1164
+ const used = new Set();
1165
+ for (const s of r.steps)
1166
+ if (s.kind === 'input')
1167
+ for (const l of lits[s.index])
1168
+ used.add(l);
1169
+ return used.size ? [...used].map(l => -l) : undefined;
1170
+ };
1171
+ const pairRows = (row, a, b) => {
1172
+ const p = pairOf(a, b);
1173
+ if (m[p.ab] === true)
1174
+ row(p.rows[0], [p.ab]);
1043
1175
  else
1044
- row(t.op === '<' ? times(t.d, -1) : plus(times(t.d, -1), konst(1)), [-t.x]);
1045
- const l = lemmaOf(solve(rows), lits);
1046
- if (l)
1047
- lemmas.push(l);
1176
+ row(p.rows[1], [-p.ab]);
1177
+ if (m[p.ba] === true)
1178
+ row(p.rows[2], [p.ba]);
1048
1179
  else
1049
- seen.add(key);
1180
+ row(p.rows[3], [-p.ba]);
1181
+ };
1182
+ // (each comparison alone first, with its terms' order and the constants: a lemma of a few literals for each the
1183
+ // model breaks, all of them in one round; one the model reads as an earlier model did, feasible then, not again)
1184
+ {
1185
+ const ks = gos.filter(t => t.startsWith('k:')), lemmas = [];
1186
+ for (const [ti, t] of theory.entries()) {
1187
+ const local = localOf(ti, t, ks), seen = (feasible[ti] ??= new Set()), key = local.map(l => (m[l] === true ? '1' : '0')).join('');
1188
+ if (seen.has(key))
1189
+ continue;
1190
+ const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1191
+ const xs = Object.keys(t.d).filter(x => x !== '1');
1192
+ for (const x of xs)
1193
+ row(times(tv(x), -1), []);
1194
+ for (let i2 = 0; i2 < xs.length; i2++) {
1195
+ for (let j = i2 + 1; j < xs.length; j++)
1196
+ pairRows(row, xs[i2], xs[j]);
1197
+ for (const k2 of ks)
1198
+ pairRows(row, xs[i2], k2);
1199
+ }
1200
+ const holds = m[t.x] === true;
1201
+ if (t.op === '=') {
1202
+ if (holds) {
1203
+ row(t.d, [t.x]);
1204
+ row(times(t.d, -1), [t.x]);
1205
+ }
1206
+ else
1207
+ continue;
1208
+ }
1209
+ else if (holds)
1210
+ row(t.op === '<' ? plus(t.d, konst(1)) : t.d, [t.x]);
1211
+ else
1212
+ row(t.op === '<' ? times(t.d, -1) : plus(times(t.d, -1), konst(1)), [-t.x]);
1213
+ const l = lemmaOf(solve(rows), lits);
1214
+ if (l)
1215
+ lemmas.push(l);
1216
+ else
1217
+ seen.add(key);
1218
+ }
1219
+ if (lemmas.length)
1220
+ return { lemmas };
1050
1221
  }
1051
- if (lemmas.length)
1052
- return { lemmas };
1053
- }
1054
- {
1055
- const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1056
- // (the pairs of terms one comparison reads, and each with the constants)
1057
- const ks = [...ords].filter(t => t.startsWith('k:')), pairs = new Map();
1058
- for (const t of theory) {
1059
- const xs = Object.keys(t.d).filter(x => x !== '1');
1060
- for (const a of xs)
1061
- for (const b of [...xs, ...ks])
1062
- if (a !== b)
1063
- pairs.set(a < b ? `${a}|${b}` : `${b}|${a}`, a < b ? [a, b] : [b, a]);
1222
+ {
1223
+ const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1224
+ // (the pairs of terms one comparison reads, and each with the constants)
1225
+ const ks = gos.filter(t => t.startsWith('k:')), pairs2 = new Map();
1226
+ for (const t of theory) {
1227
+ const xs = Object.keys(t.d).filter(x => x !== '1');
1228
+ for (const a of xs)
1229
+ for (const b of [...xs, ...ks])
1230
+ if (a !== b)
1231
+ pairs2.set(a < b ? `${a}|${b}` : `${b}|${a}`, a < b ? [a, b] : [b, a]);
1232
+ }
1233
+ // (with few ordered terms, every pair of them: a refutation through a term no comparison reads, a chain of the
1234
+ // order, is then a lemma of the pairs it needs, not of the whole order)
1235
+ const all = gos.length <= 48 ? gos : [];
1236
+ for (let i2 = 0; i2 < all.length; i2++)
1237
+ for (let j = i2 + 1; j < all.length; j++) {
1238
+ const a = all[i2], b = all[j];
1239
+ if (!(a.startsWith('k:') && b.startsWith('k:')))
1240
+ pairs2.set(a < b ? `${a}|${b}` : `${b}|${a}`, a < b ? [a, b] : [b, a]);
1241
+ }
1242
+ for (const t of new Set([...theoryTerms, ...all.filter(x => !x.startsWith('k:'))]))
1243
+ row(times(tv(t), -1), []);
1244
+ for (const [a, b] of pairs2.values())
1245
+ pairRows(row, a, b);
1246
+ // (and the successors the model holds among them, n1 = n + 1, both ways: the ring's next node)
1247
+ const tt = new Set([...theoryTerms, ...all]);
1248
+ for (const x of succList)
1249
+ if (m[x.s] && (tt.has(x.lo) || tt.has(x.hi))) {
1250
+ row(plus(T(x.hi), times(plus(T(x.lo), konst(1)), -1)), [x.s]);
1251
+ row(plus(plus(T(x.lo), konst(1)), times(T(x.hi), -1)), [x.s]);
1252
+ for (const y of [x.lo, x.hi])
1253
+ if (!tt.has(y) && !y.startsWith('k:'))
1254
+ row(times(tv(y), -1), []);
1255
+ }
1256
+ theoryRows(row);
1257
+ // (several lemmas a round: each refutation's theory rows set aside, the rest solved again, at most eight)
1258
+ // (each by the simplex first (kernel/simplex.ts, the CDCL search's, its tableau kept from round to round): its
1259
+ // conflict's rows refuted exactly (core/solver.ts), the lemma the literals that refutation reads; no answer, the
1260
+ // first time by elimination over them all, as before; feasible, or a conflict the floats misjudge, no more lemmas)
1261
+ const lemmas = [], off = new Set(), theoryLits = new Set(theory.flatMap(t => [t.x, -t.x]));
1262
+ for (let k = 0; k < 8; k++) {
1263
+ const keep = rows.map((_, i) => i).filter(i => !off.has(i)), sub = keep.map(i => rows[i]), subLits = keep.map(i => lits[i]);
1264
+ let r = jointLp.load(sub);
1265
+ if (r.kind === 'sat')
1266
+ r = jointLp.check();
1267
+ if (r.kind === 'sat')
1268
+ break;
1269
+ const l = r.kind === 'conflict' ? lemmaOf(solve(r.rows.map(i => sub[i])), r.rows.map(i => subLits[i])) : k ? undefined : lemmaOf(solve(sub), subLits);
1270
+ if (!l)
1271
+ break;
1272
+ lemmas.push(l);
1273
+ keep.forEach(i => { if (lits[i].some(x => theoryLits.has(x) && l.includes(-x)))
1274
+ off.add(i); });
1275
+ }
1276
+ if (lemmas.length)
1277
+ return { lemmas };
1064
1278
  }
1065
- // (with few ordered terms, every pair of them: a refutation through a term no comparison reads, a chain of the
1066
- // order, is then a lemma of the pairs it needs, not of the whole order)
1067
- const all = ords.size <= 48 ? [...ords] : [];
1068
- for (let i2 = 0; i2 < all.length; i2++)
1069
- for (let j = i2 + 1; j < all.length; j++) {
1070
- const a = all[i2], b = all[j];
1071
- if (!(a.startsWith('k:') && b.startsWith('k:')))
1072
- pairs.set(a < b ? `${a}|${b}` : `${b}|${a}`, a < b ? [a, b] : [b, a]);
1279
+ const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1280
+ const groups = groupsOf(m);
1281
+ for (const t of gos)
1282
+ if (!t.startsWith('k:'))
1283
+ row(times(tv(t), -1), []);
1284
+ for (const [gi, g] of groups.entries()) {
1285
+ for (const t of g.slice(1)) {
1286
+ row(plus(T(t), times(T(g[0]), -1)), [v(le(t, g[0]))]);
1287
+ row(plus(T(g[0]), times(T(t), -1)), [v(le(g[0], t))]);
1073
1288
  }
1074
- for (const t of new Set([...theoryTerms, ...all.filter(x => !x.startsWith('k:'))]))
1075
- row(times(tv(t), -1), []);
1076
- for (const [a, b] of pairs.values())
1077
- pairRows(row, a, b);
1078
- // (and the successors the model holds among them, n1 = n + 1, both ways: the ring's next node)
1079
- const tt = new Set([...theoryTerms, ...all]);
1080
- for (const x of succs)
1081
- if (m[x.s] && (tt.has(x.lo) || tt.has(x.hi))) {
1289
+ const h = groups[gi + 1];
1290
+ if (h)
1291
+ row(plus(plus(T(g[0]), konst(1)), times(T(h[0]), -1)), [-v(le(h[0], g[0]))]);
1292
+ }
1293
+ for (const x of succList)
1294
+ if (m[x.s])
1082
1295
  row(plus(T(x.hi), times(plus(T(x.lo), konst(1)), -1)), [x.s]);
1083
- row(plus(plus(T(x.lo), konst(1)), times(T(x.hi), -1)), [x.s]);
1084
- for (const y of [x.lo, x.hi])
1085
- if (!tt.has(y) && !y.startsWith('k:'))
1086
- row(times(tv(y), -1), []);
1087
- }
1088
1296
  theoryRows(row);
1089
- // (several lemmas a round: each refutation's theory rows set aside, the rest solved again, at most eight)
1090
- // (each by the simplex first (kernel/simplex.ts, the CDCL search's, its tableau kept from round to round): its
1091
- // conflict's rows refuted exactly (core/solver.ts), the lemma the literals that refutation reads; no answer, the
1092
- // first time by elimination over them all, as before; feasible, or a conflict the floats misjudge, no more lemmas)
1093
- const lemmas = [], off = new Set(), theoryLits = new Set(theory.flatMap(t => [t.x, -t.x]));
1094
- for (let k = 0; k < 8; k++) {
1095
- const keep = rows.map((_, i) => i).filter(i => !off.has(i)), sub = keep.map(i => rows[i]), subLits = keep.map(i => lits[i]);
1096
- let r = jointLp.load(sub);
1097
- if (r.kind === 'sat')
1098
- r = jointLp.check();
1099
- if (r.kind === 'sat')
1100
- break;
1101
- const l = r.kind === 'conflict' ? lemmaOf(solve(r.rows.map(i => sub[i])), r.rows.map(i => subLits[i])) : k ? undefined : lemmaOf(solve(sub), subLits);
1102
- if (!l)
1103
- break;
1104
- lemmas.push(l);
1105
- keep.forEach(i => { if (lits[i].some(x => theoryLits.has(x) && l.includes(-x)))
1106
- off.add(i); });
1297
+ // (the simplex first, as the joint check: a conflict's rows refuted exactly; its point the values where every term is
1298
+ // a natural there and every row holds exactly, with elimination's (as before) for a read-back they break; else
1299
+ // elimination over them all)
1300
+ let q = jointLp.load(rows);
1301
+ if (q.kind === 'sat')
1302
+ q = jointLp.check();
1303
+ if (q.kind === 'conflict') {
1304
+ const l = lemmaOf(solve(q.rows.map(i => rows[i])), q.rows.map(i => lits[i]));
1305
+ if (l)
1306
+ return { lemmas: [l] };
1107
1307
  }
1108
- if (lemmas.length)
1109
- return { lemmas };
1110
- }
1111
- const rows = [], lits = [], row = (lin, ls) => { rows.push({ lin, label: '' }); lits.push(ls); };
1112
- const groups = groupsOf(m);
1113
- for (const t of ords)
1114
- if (!t.startsWith('k:'))
1115
- row(times(tv(t), -1), []);
1116
- for (const [gi, g] of groups.entries()) {
1117
- for (const t of g.slice(1)) {
1118
- row(plus(T(t), times(T(g[0]), -1)), [v(le(t, g[0]))]);
1119
- row(plus(T(g[0]), times(T(t), -1)), [v(le(g[0], t))]);
1308
+ const exact = () => {
1309
+ const r = solve(rows);
1310
+ if (r.kind === 'sat')
1311
+ return { val: new Map(gos.map(t => [t, t.startsWith('k:') ? Number(t.slice(2)) : r.witness[t] ?? 0])) };
1312
+ const l = lemmaOf(r, lits);
1313
+ return l && { lemmas: [l] };
1314
+ };
1315
+ if (q.kind === 'sat') {
1316
+ const at = (t) => { const j = jointLp.indexOf(t); return j === undefined ? 0 : jointLp.value(j); };
1317
+ const val = new Map(gos.map(t => [t, t.startsWith('k:') ? Number(t.slice(2)) : Math.round(at(t))]));
1318
+ const ok = gos.every(t => t.startsWith('k:') || (Math.abs(at(t) - val.get(t)) < 1e-6 && val.get(t) >= 0))
1319
+ && rows.every(row => Object.entries(row.lin).reduce((x, [k, c]) => x + c * (k === '1' ? 1 : val.get(k) ?? 0), 0) <= 0);
1320
+ if (ok)
1321
+ return { val, exact };
1120
1322
  }
1121
- const h = groups[gi + 1];
1122
- if (h)
1123
- row(plus(plus(T(g[0]), konst(1)), times(T(h[0]), -1)), [-v(le(h[0], g[0]))]);
1124
- }
1125
- for (const x of succs)
1126
- if (m[x.s])
1127
- row(plus(T(x.hi), times(plus(T(x.lo), konst(1)), -1)), [x.s]);
1128
- theoryRows(row);
1129
- // (the simplex first, as the joint check: a conflict's rows refuted exactly; its point the values where every term is
1130
- // a natural there and every row holds exactly, with elimination's (as before) for a read-back they break; else
1131
- // elimination over them all)
1132
- let q = jointLp.load(rows);
1133
- if (q.kind === 'sat')
1134
- q = jointLp.check();
1135
- if (q.kind === 'conflict') {
1136
- const l = lemmaOf(solve(q.rows.map(i => rows[i])), q.rows.map(i => lits[i]));
1137
- if (l)
1138
- return { lemmas: [l] };
1139
- }
1140
- const exact = () => {
1141
- const r = solve(rows);
1142
- if (r.kind === 'sat')
1143
- return { val: new Map([...ords].map(t => [t, t.startsWith('k:') ? Number(t.slice(2)) : r.witness[t] ?? 0])) };
1144
- const l = lemmaOf(r, lits);
1145
- return l && { lemmas: [l] };
1323
+ return exact();
1146
1324
  };
1147
- if (q.kind === 'sat') {
1148
- const at = (t) => { const j = jointLp.indexOf(t); return j === undefined ? 0 : jointLp.value(j); };
1149
- const val = new Map([...ords].map(t => [t, t.startsWith('k:') ? Number(t.slice(2)) : Math.round(at(t))]));
1150
- const ok = [...ords].every(t => t.startsWith('k:') || (Math.abs(at(t) - val.get(t)) < 1e-6 && val.get(t) >= 0))
1151
- && rows.every(row => Object.entries(row.lin).reduce((x, [k, c]) => x + c * (k === '1' ? 1 : val.get(k) ?? 0), 0) <= 0);
1152
- if (ok)
1153
- return { val, exact };
1154
- }
1155
- return exact();
1156
- };
1157
- const outcome = (o) => (typeof o === 'string' ? { unknown: o } : o === undefined ? { unknown: 'the conflict budget ran out, or the deadline' }
1158
- : !o.sat ? { sat: false, core: [...o.core].filter(i => i >= 0).sort((a, b) => a - b) } : { model: o.model });
1159
- // --- a model, read back: the ordered terms (the parts among them) by the model's order, each composed key the radix
1160
- // sum of its parts, each cell and scalar its value; then judged on every hypothesis
1161
- // (the read-back with the theory's values, where it checked the model; where they break a hypothesis, the order's own
1162
- // grouping, as without one)
1163
- const finish = (model, theoryVal) => {
1164
- const val = (l) => model[l] === true;
1165
- const w = {};
1166
- for (const f of fins.values()) {
1167
- let x = 0;
1168
- for (let val2 = 0; val2 <= f.cap; val2++)
1169
- if (val(v(finAt(f, val2))))
1170
- x = val2;
1171
- if (f.id.startsWith('s:'))
1172
- w[f.id.slice(2)] = x;
1173
- }
1174
- // each group of equal terms the next value, a constant's group its own; odd where there is room before the next constant
1175
- // (a key of the wrong sort, 2·64·x + y, then meets no cell 64·x' + y), and far apart past every constant (composed keys
1176
- // of parts above every bound then don't meet)
1177
- // (where the theory checked the model, its values)
1178
- const ordVal = theoryVal ?? new Map();
1179
- if (!theoryVal) {
1180
- const groups = groupsOf(model);
1181
- const constOf = (g) => { const cs = [...new Set(g.filter(x => x.startsWith('k:')).map(x => Number(x.slice(2))))]; return cs.length > 1 ? NaN : cs[0]; };
1182
- // (a successor the model holds, n1 = n + 1, makes its two groups consecutive values: such a chain is one block, its
1183
- // first group's value the next free one, or its constant's less the steps to it)
1184
- const groupOf = new Map();
1185
- groups.forEach((g, i) => g.forEach(t => groupOf.set(t, i)));
1186
- const tight = new Set(succs.filter(x => val(x.s)).map(x => `${groupOf.get(x.lo)}>${groupOf.get(x.hi)}`));
1187
- const tied = (i) => tight.has(`${i}>${i + 1}`);
1188
- let prev = -1, far = 0;
1189
- for (const [gi, g] of groups.entries()) {
1190
- const c = constOf(g);
1191
- if (Number.isNaN(c))
1192
- return { unknown: 'the model\'s order equates two constants' };
1193
- let next = Infinity;
1194
- for (const h of groups.slice(gi + 1)) {
1195
- const d = constOf(h);
1196
- if (d !== undefined) {
1197
- next = d;
1198
- break;
1199
- }
1200
- }
1201
- let x = c ?? (next === Infinity && prev > 0 ? (1 << 24) * ++far + 997 * far + prev + 13 : prev + 1);
1202
- if (c === undefined && next !== Infinity && x % 2 === 0 && x + 1 < next)
1203
- x++;
1204
- if (c === undefined && gi > 0 && tied(gi - 1))
1205
- x = prev + 1;
1206
- else if (c === undefined) {
1207
- let k = gi;
1208
- while (tied(k) && constOf(groups[k + 1]) === undefined)
1209
- k++;
1210
- const d = tied(k) ? constOf(groups[k + 1]) : undefined;
1211
- if (d !== undefined)
1212
- x = d - (k + 1 - gi);
1213
- }
1214
- if (x <= prev || x >= next || (gi > 0 && tied(gi - 1) && x !== prev + 1))
1215
- return { unknown: noRoom };
1216
- for (const t of g)
1217
- ordVal.set(t, x);
1218
- prev = x;
1325
+ const outcome = (o) => (typeof o === 'string' ? { unknown: o } : o === undefined ? { unknown: 'the conflict budget ran out, or the deadline' }
1326
+ : !o.sat ? { sat: false, core: [...new Set([...o.core].flatMap(g => (index.has(g) ? [index.get(g)] : [])))].sort((a, b) => a - b) } : { model: o.model });
1327
+ // the goal's own terms, for the read-back: its finite variables, cells (of its maps' patterns, and at keys of the
1328
+ // wrong sort), ordered cells and functions' parts
1329
+ const gFinsL = finsList.filter(f => gFins.has(f)), cellsOf = new Map(), odd = [];
1330
+ for (const f of gFinsL)
1331
+ if (f.parts) {
1332
+ if (!cellsOf.has(f.map))
1333
+ cellsOf.set(f.map, []);
1334
+ cellsOf.get(f.map).push({ id: f.id, parts: f.parts });
1219
1335
  }
1220
- }
1221
- for (const [t, x] of ordVal)
1222
- if (t.startsWith('p:') || t.startsWith('s:'))
1223
- w[t.slice(2)] = x;
1224
- const maps = new Map();
1225
- const cellVal = new Map();
1226
- for (const f of fins.values())
1227
- if (f.id.startsWith('c:')) {
1336
+ else if (f.key)
1337
+ odd.push({ id: f.id, map: f.map, key: f.key });
1338
+ const ordCells = new Map(), ordOdd = [];
1339
+ for (const id of gos) {
1340
+ const inf = ordInfo.get(id);
1341
+ if (!inf)
1342
+ continue;
1343
+ if (inf.parts) {
1344
+ if (!ordCells.has(inf.map))
1345
+ ordCells.set(inf.map, []);
1346
+ ordCells.get(inf.map).push({ id, parts: inf.parts });
1347
+ }
1348
+ else
1349
+ ordOdd.push({ id, map: inf.map, key: inf.key });
1350
+ }
1351
+ const reads = gst.reads, fnParts = gst.fnParts;
1352
+ // --- a model, read back: the ordered terms (the parts among them) by the model's order, each composed key the radix
1353
+ // sum of its parts, each cell and scalar its value; then judged on every hypothesis
1354
+ // (the read-back with the theory's values, where it checked the model; where they break a hypothesis, the order's own
1355
+ // grouping, as without one)
1356
+ const finish = (model, theoryVal) => {
1357
+ const val = (l) => model[l] === true;
1358
+ const w = {};
1359
+ for (const f of gFinsL) {
1228
1360
  let x = 0;
1229
1361
  for (let val2 = 0; val2 <= f.cap; val2++)
1230
1362
  if (val(v(finAt(f, val2))))
1231
1363
  x = val2;
1232
- cellVal.set(f.id, x);
1364
+ if (f.id.startsWith('s:'))
1365
+ w[f.id.slice(2)] = x;
1233
1366
  }
1234
- for (const [mp, cells] of ordCells)
1235
- for (const c of cells) {
1236
- cellVal.set(c.id, ordVal.get(c.id) ?? 0);
1237
- if (!cellsOf.has(mp))
1238
- cellsOf.set(mp, []);
1239
- cellsOf.get(mp).push(c);
1367
+ // each group of equal terms the next value, a constant's group its own; odd where there is room before the next constant
1368
+ // (a key of the wrong sort, 2·64·x + y, then meets no cell 64·x' + y), and far apart past every constant (composed keys
1369
+ // of parts above every bound then don't meet)
1370
+ // (where the theory checked the model, its values)
1371
+ const ordVal = theoryVal ?? new Map();
1372
+ if (!theoryVal) {
1373
+ const groups = groupsOf(model);
1374
+ const constOf = (g) => { const cs = [...new Set(g.filter(x => x.startsWith('k:')).map(x => Number(x.slice(2))))]; return cs.length > 1 ? NaN : cs[0]; };
1375
+ // (a successor the model holds, n1 = n + 1, makes its two groups consecutive values: such a chain is one block, its
1376
+ // first group's value the next free one, or its constant's less the steps to it)
1377
+ const groupOf = new Map();
1378
+ groups.forEach((g, i) => g.forEach(t => groupOf.set(t, i)));
1379
+ const tight = new Set(succList.filter(x => val(x.s)).map(x => `${groupOf.get(x.lo)}>${groupOf.get(x.hi)}`));
1380
+ const tied = (i) => tight.has(`${i}>${i + 1}`);
1381
+ let prev = -1, far = 0;
1382
+ for (const [gi, g] of groups.entries()) {
1383
+ const c = constOf(g);
1384
+ if (Number.isNaN(c))
1385
+ return { unknown: 'the model\'s order equates two constants' };
1386
+ let next = Infinity;
1387
+ for (const h of groups.slice(gi + 1)) {
1388
+ const d = constOf(h);
1389
+ if (d !== undefined) {
1390
+ next = d;
1391
+ break;
1392
+ }
1393
+ }
1394
+ let x = c ?? (next === Infinity && prev > 0 ? (1 << 24) * ++far + 997 * far + prev + 13 : prev + 1);
1395
+ if (c === undefined && next !== Infinity && x % 2 === 0 && x + 1 < next)
1396
+ x++;
1397
+ if (c === undefined && gi > 0 && tied(gi - 1))
1398
+ x = prev + 1;
1399
+ else if (c === undefined) {
1400
+ let k = gi;
1401
+ while (tied(k) && constOf(groups[k + 1]) === undefined)
1402
+ k++;
1403
+ const d = tied(k) ? constOf(groups[k + 1]) : undefined;
1404
+ if (d !== undefined)
1405
+ x = d - (k + 1 - gi);
1406
+ }
1407
+ if (x <= prev || x >= next || (gi > 0 && tied(gi - 1) && x !== prev + 1))
1408
+ return { unknown: noRoom };
1409
+ for (const t of g)
1410
+ ordVal.set(t, x);
1411
+ prev = x;
1412
+ }
1240
1413
  }
1241
- for (const o of ordOdd) {
1242
- cellVal.set(o.id, ordVal.get(o.id) ?? 0);
1243
- odd.push(o);
1244
- }
1245
- // every read of the goal, at its key's value under w: the abstraction's value where it has one, else 0
1246
- const keyVal = (e) => { const ts = [], d = { c: 0 }; if (!linTerms(e, 1, ts, d))
1247
- return undefined; let s = d.c; for (const [x, c] of ts) {
1248
- if (w[x] === undefined)
1249
- return undefined;
1250
- s += c * w[x];
1251
- } return s; };
1252
- // (each function's table at its parts' values)
1253
- for (const { f, n, a } of fnParts) {
1254
- if (!maps.has(f))
1255
- maps.set(f, new Map());
1256
- maps.get(f).set(w[a], w[n]);
1257
- }
1258
- // (and at a key of the wrong sort, a value of its own past every value the model gives: an injective function's
1259
- // instance there holds, and a key it is a part of meets no cell of the right sort)
1260
- let fresh2 = Math.max(0, ...Object.values(w), ...[...maps.values()].flatMap(t => [...t.values()]));
1261
- // (a key that reads such a read, idn(64·idn(64·m + n) + n): its value from the tables so far, inner reads first)
1262
- const valueAt = (e) => {
1263
- if (e.op === 'const')
1264
- return e.value;
1265
- if (e.op === 'var')
1266
- return w[e.name] ?? 0;
1267
- if (e.op === 'mul') {
1268
- const a = valueAt(e.a);
1269
- return a === undefined ? undefined : a * e.k;
1414
+ for (const [t, x] of ordVal)
1415
+ if (t.startsWith('p:') || t.startsWith('s:'))
1416
+ w[t.slice(2)] = x;
1417
+ const maps = new Map();
1418
+ const cellVal = new Map(), cells2 = new Map([...cellsOf].map(([mp, cs]) => [mp, [...cs]])), odd2 = [...odd];
1419
+ for (const f of gFinsL)
1420
+ if (f.id.startsWith('c:')) {
1421
+ let x = 0;
1422
+ for (let val2 = 0; val2 <= f.cap; val2++)
1423
+ if (val(v(finAt(f, val2))))
1424
+ x = val2;
1425
+ cellVal.set(f.id, x);
1426
+ }
1427
+ for (const [mp, cs] of ordCells)
1428
+ for (const c of cs) {
1429
+ cellVal.set(c.id, ordVal.get(c.id) ?? 0);
1430
+ if (!cells2.has(mp))
1431
+ cells2.set(mp, []);
1432
+ cells2.get(mp).push(c);
1433
+ }
1434
+ for (const o of ordOdd) {
1435
+ cellVal.set(o.id, ordVal.get(o.id) ?? 0);
1436
+ odd2.push(o);
1270
1437
  }
1271
- if (e.op === 'add') {
1272
- const a = valueAt(e.a), b = valueAt(e.b);
1273
- return a === undefined || b === undefined ? undefined : a + b;
1438
+ // every read of the goal, at its key's value under w: the abstraction's value where it has one, else 0
1439
+ const keyVal = (e) => { const ts = [], d = { c: 0 }; if (!linTerms(e, 1, ts, d))
1440
+ return undefined; let s = d.c; for (const [x, c] of ts) {
1441
+ if (w[x] === undefined)
1442
+ return undefined;
1443
+ s += c * w[x];
1444
+ } return s; };
1445
+ // (each function's table at its parts' values)
1446
+ for (const { f, n, a } of fnParts) {
1447
+ if (!maps.has(f))
1448
+ maps.set(f, new Map());
1449
+ maps.get(f).set(w[a], w[n]);
1274
1450
  }
1275
- if (e.op === 'get' && fnMaps.has(e.map)) {
1276
- const k = valueAt(e.key);
1277
- return k === undefined ? undefined : maps.get(e.map)?.get(k);
1451
+ // (and at a key of the wrong sort, a value of its own past every value the model gives: an injective function's
1452
+ // instance there holds, and a key it is a part of meets no cell of the right sort)
1453
+ let fresh2 = Math.max(0, ...Object.values(w), ...[...maps.values()].flatMap(t => [...t.values()]));
1454
+ // (a key that reads such a read, idn(64·idn(64·m + n) + n): its value from the tables so far, inner reads first)
1455
+ const valueAt = (e) => {
1456
+ if (e.op === 'const')
1457
+ return e.value;
1458
+ if (e.op === 'var')
1459
+ return w[e.name] ?? 0;
1460
+ if (e.op === 'mul') {
1461
+ const a = valueAt(e.a);
1462
+ return a === undefined ? undefined : a * e.k;
1463
+ }
1464
+ if (e.op === 'add') {
1465
+ const a = valueAt(e.a), b = valueAt(e.b);
1466
+ return a === undefined || b === undefined ? undefined : a + b;
1467
+ }
1468
+ if (e.op === 'get' && fnMaps.has(e.map)) {
1469
+ const k = valueAt(e.key);
1470
+ return k === undefined ? undefined : maps.get(e.map)?.get(k);
1471
+ }
1472
+ return undefined;
1473
+ };
1474
+ // (the reads gathered, the inner ones first: each read is gathered before the reads in its key)
1475
+ const fnOdd = (x) => {
1476
+ tick();
1477
+ if (!fnMaps.has(x.map) || partName(x) !== undefined)
1478
+ return;
1479
+ const key = keyVal(x.key) ?? valueAt(x.key), t = maps.get(x.map) ?? new Map();
1480
+ if (key === undefined || t.has(key))
1481
+ return;
1482
+ maps.set(x.map, t.set(key, ordVal.get(`c:${x.map}#${textOfE(x.key)}`) ?? ++fresh2));
1483
+ };
1484
+ [...reads].reverse().forEach(fnOdd);
1485
+ for (const [mp, cs] of cells2)
1486
+ for (const c of cs) {
1487
+ const key = c.parts.reduce((s, p, i) => s + w[p] * (patterns[mp][i] ?? 1), 0);
1488
+ if (!maps.has(mp))
1489
+ maps.set(mp, new Map());
1490
+ maps.get(mp).set(key, cellVal.get(c.id));
1491
+ }
1492
+ // (a cell at a key of the wrong sort, where its key falls, unless a cell of the right sort is there: one cell, whose
1493
+ // value the hypotheses are judged with below)
1494
+ for (const o of odd2) {
1495
+ const key = keyVal(o.key) ?? valueAt(o.key);
1496
+ if (key === undefined)
1497
+ continue;
1498
+ if (!maps.has(o.map))
1499
+ maps.set(o.map, new Map());
1500
+ if (!maps.get(o.map).has(key))
1501
+ maps.get(o.map).set(key, cellVal.get(o.id));
1278
1502
  }
1279
- return undefined;
1280
- };
1281
- // (the reads gathered, the inner ones first: each read is gathered before the reads in its key)
1282
- const fnOdd = (x) => {
1283
- tick();
1284
- if (!fnMaps.has(x.map) || partName(x) !== undefined)
1285
- return;
1286
- const key = keyVal(x.key) ?? valueAt(x.key), t = maps.get(x.map) ?? new Map();
1287
- if (key === undefined || t.has(key))
1288
- return;
1289
- maps.set(x.map, t.set(key, ordVal.get(`c:${x.map}#${textOfE(x.key)}`) ?? ++fresh2));
1290
- };
1291
- [...reads].reverse().forEach(fnOdd);
1292
- for (const [mp, cells] of cellsOf)
1293
- for (const c of cells) {
1294
- const key = c.parts.reduce((s, p, i) => s + w[p] * (patterns[mp][i] ?? 1), 0);
1295
- if (!maps.has(mp))
1296
- maps.set(mp, new Map());
1297
- maps.get(mp).set(key, cellVal.get(c.id));
1503
+ const allMaps = new Set();
1504
+ for (const x of reads)
1505
+ allMaps.add(x.map);
1506
+ const st2 = { scalars: {}, maps: Object.fromEntries([...allMaps].map(mp => [mp, maps.get(mp) ?? new Map()])) };
1507
+ const m = { name: goal.name, params: [], inputs: [], state: {}, step: {}, maps: Object.fromEntries([...allMaps].map(mp => [mp, 0])) };
1508
+ const env = new Proxy({ ...w }, { get: (t, q) => t[q] ?? 0 });
1509
+ for (const [i, f] of fs.entries()) {
1510
+ tick();
1511
+ try {
1512
+ if (f.h && !evalC(f.h, env, st2, m)) {
1513
+ return { unknown: `the abstraction's model breaks hypothesis ${i}` };
1514
+ }
1515
+ }
1516
+ catch {
1517
+ return { unknown: 'the model could not be read' };
1518
+ }
1298
1519
  }
1299
- // (a cell at a key of the wrong sort, where its key falls, unless a cell of the right sort is there: one cell, whose
1300
- // value the hypotheses are judged with below)
1301
- for (const o of odd) {
1302
- const key = keyVal(o.key) ?? valueAt(o.key);
1303
- if (key === undefined)
1304
- continue;
1305
- if (!maps.has(o.map))
1306
- maps.set(o.map, new Map());
1307
- if (!maps.get(o.map).has(key))
1308
- maps.get(o.map).set(key, cellVal.get(o.id));
1309
- }
1310
- const allMaps = new Set();
1311
- for (const x of reads)
1312
- allMaps.add(x.map);
1313
- const st = { scalars: {}, maps: Object.fromEntries([...allMaps].map(mp => [mp, maps.get(mp) ?? new Map()])) };
1314
- const m = { name: goal.name, params: [], inputs: [], state: {}, step: {}, maps: Object.fromEntries([...allMaps].map(mp => [mp, 0])) };
1315
- const env = new Proxy({ ...w }, { get: (t, q) => t[q] ?? 0 });
1316
- for (const [i, h] of goal.hyps.entries()) {
1317
- tick();
1318
- try {
1319
- if (!evalC(h, env, st, m)) {
1320
- return { unknown: `the abstraction's model breaks hypothesis ${i}${shaped[i] ? '' : ' (not EPR-shaped)'}` };
1520
+ // the kernel's witness: names, and each cell of the goal by its key's linear form
1521
+ const witness = { ...w };
1522
+ for (const x of reads) {
1523
+ tick();
1524
+ const l = linear(x.key, new Map()), kv = keyVal(x.key);
1525
+ if (l && kv !== undefined)
1526
+ witness[`${x.map}[${canon(l)}]`] = st2.maps[x.map]?.get(kv) ?? 0;
1527
+ }
1528
+ // the structure
1529
+ const values = [...new Set([...[...parts].map(x => w[x]), ...[...ordVal].filter(([t]) => !t.startsWith('k:') && !t.includes('#')).map(([, x]) => x)].filter((x) => x !== undefined))].sort((a, b) => a - b), elem = new Map(values.map((x, i) => [x, i]));
1530
+ const diagram = { elements: values.length, parts: {}, scalars: {}, cells: {}, fns: {} };
1531
+ for (const x of [...parts, ...ordScalars].sort())
1532
+ if (w[x] !== undefined)
1533
+ diagram.parts[x] = elem.get(w[x]);
1534
+ for (const f of gFinsL)
1535
+ if (f.id.startsWith('s:'))
1536
+ diagram.scalars[f.id.slice(2)] = w[f.id.slice(2)] ?? 0;
1537
+ for (const [mp, cs] of cells2) {
1538
+ const seen2 = new Set(), out = [];
1539
+ for (const c of cs) {
1540
+ const at = c.parts.map(x => elem.get(w[x])), id = at.join(','), value = cellVal.get(c.id);
1541
+ if (!seen2.has(id)) {
1542
+ seen2.add(id);
1543
+ out.push({ at, value: ordMaps.has(mp) ? elem.get(value) ?? value : value });
1544
+ }
1321
1545
  }
1546
+ diagram.cells[mp] = out.sort((a, b) => { for (let i = 0; i < a.at.length; i++)
1547
+ if (a.at[i] !== b.at[i])
1548
+ return a.at[i] - b.at[i]; return 0; });
1322
1549
  }
1323
- catch {
1324
- return { unknown: 'the model could not be read' };
1550
+ for (const { f, n, a } of fnParts) {
1551
+ const t = (diagram.fns[f] ??= []), x = elem.get(w[a]);
1552
+ if (!t.some(r => r[0] === x))
1553
+ t.push([x, elem.get(w[n])]);
1325
1554
  }
1326
- }
1327
- // the kernel's witness: names, and each cell of the goal by its key's linear form
1328
- const witness = { ...w };
1329
- for (const x of reads) {
1330
- tick();
1331
- const l = linear(x.key, new Map()), kv = keyVal(x.key);
1332
- if (l && kv !== undefined)
1333
- witness[`${x.map}[${canon(l)}]`] = st.maps[x.map]?.get(kv) ?? 0;
1334
- }
1335
- // the structure
1336
- const values = [...new Set([...[...parts].map(x => w[x]), ...[...ordVal].filter(([t]) => !t.startsWith('k:') && !t.includes('#')).map(([, x]) => x)].filter((x) => x !== undefined))].sort((a, b) => a - b), elem = new Map(values.map((x, i) => [x, i]));
1337
- const diagram = { elements: values.length, parts: {}, scalars: {}, cells: {}, fns: {} };
1338
- for (const x of [...parts, ...ordScalars].sort())
1339
- if (w[x] !== undefined)
1340
- diagram.parts[x] = elem.get(w[x]);
1341
- for (const f of fins.values())
1342
- if (f.id.startsWith('s:'))
1343
- diagram.scalars[f.id.slice(2)] = w[f.id.slice(2)] ?? 0;
1344
- for (const [mp, cells] of cellsOf) {
1345
- const seen2 = new Set(), out = [];
1346
- for (const c of cells) {
1347
- const at = c.parts.map(x => elem.get(w[x])), id = at.join(','), value = cellVal.get(c.id);
1348
- if (!seen2.has(id)) {
1349
- seen2.add(id);
1350
- out.push({ at, value: ordMaps.has(mp) ? elem.get(value) ?? value : value });
1555
+ for (const t of Object.values(diagram.fns))
1556
+ t.sort((a, b) => a[0] - b[0]);
1557
+ return { sat: true, witness, diagram };
1558
+ };
1559
+ // (the order's grouping first, as without a theory; where it breaks a hypothesis, the theory's rounds: lemmas the model
1560
+ // breaks, the search again, until the theory checks a model, its values the read-back's)
1561
+ let cur = outcome(search());
1562
+ if (!('model' in cur))
1563
+ return cur;
1564
+ let done = finish(cur.model, undefined);
1565
+ for (let round = 0; theory.length && 'unknown' in done && round < 256 && !opts.late?.(); round++) {
1566
+ let r = theoryCheck(cur.model);
1567
+ if (!r)
1568
+ break;
1569
+ if ('val' in r) {
1570
+ done = finish(cur.model, r.val);
1571
+ // (the simplex's values breaking it: elimination's)
1572
+ if ('unknown' in done && r.exact) {
1573
+ r = r.exact();
1574
+ if (r && 'val' in r)
1575
+ done = finish(cur.model, r.val);
1351
1576
  }
1577
+ if (r && !('val' in r)) {
1578
+ for (const l of r.lemmas)
1579
+ lemma(l);
1580
+ cur = outcome(search());
1581
+ if (!('model' in cur))
1582
+ return cur;
1583
+ done = finish(cur.model, undefined);
1584
+ continue;
1585
+ }
1586
+ if ('unknown' in done)
1587
+ done = finish(cur.model, undefined);
1588
+ break;
1352
1589
  }
1353
- diagram.cells[mp] = out.sort((a, b) => { for (let i = 0; i < a.at.length; i++)
1354
- if (a.at[i] !== b.at[i])
1355
- return a.at[i] - b.at[i]; return 0; });
1356
- }
1357
- for (const { f, n, a } of fnParts) {
1358
- const t = (diagram.fns[f] ??= []), x = elem.get(w[a]);
1359
- if (!t.some(r => r[0] === x))
1360
- t.push([x, elem.get(w[n])]);
1590
+ for (const l of r.lemmas) {
1591
+ lemma(l);
1592
+ const named = l.map((x) => [names[Math.abs(x)], x > 0]), key = named.map(([k, b]) => (b ? '' : '¬') + k).sort().join('|');
1593
+ if (lemmaCache.size > 20_000)
1594
+ lemmaCache.clear();
1595
+ lemmaCache.set(key, named);
1596
+ lemmasIn.add(key);
1597
+ }
1598
+ cur = outcome(search());
1599
+ if (!('model' in cur))
1600
+ return cur;
1601
+ done = finish(cur.model, undefined);
1361
1602
  }
1362
- for (const t of Object.values(diagram.fns))
1363
- t.sort((a, b) => a[0] - b[0]);
1364
- return { sat: true, witness, diagram };
1603
+ return done;
1365
1604
  };
1366
- // (the order's grouping first, as without a theory; where it breaks a hypothesis, the theory's rounds: lemmas the model
1367
- // breaks, the search again, until the theory checks a model, its values the read-back's)
1368
- let cur = outcome(search());
1369
- if (!('model' in cur))
1370
- return cur;
1371
- let done = finish(cur.model, undefined);
1372
- for (let round = 0; theory.length && 'unknown' in done && round < 256 && !opts.late?.(); round++) {
1373
- let r = theoryCheck(cur.model);
1374
- if (!r)
1605
+ // (an encoder left mid-way by the deadline, or past 512 ordered terms, is not kept)
1606
+ let over = false;
1607
+ return { decide: (goal, fs, gst, opts) => { over = true; const d = decideGoal(goal, fs, gst, opts); if (!d || !('unknown' in d) || !d.unknown.endsWith('ordered terms'))
1608
+ over = false; return d; }, size: () => (over ? Infinity : hyps.size) };
1609
+ }
1610
+ function cdclSolver(trueFirst, keepPhase) {
1611
+ const idx = new Map(), back = [0];
1612
+ let cap = 0, val = new Int8Array(0), level = new Int32Array(0), act = new Float64Array(0), phase = new Int8Array(0), at = new Int32Array(0);
1613
+ const reason = [undefined];
1614
+ const heap = [];
1615
+ const above = (a, b) => act[a] > act[b] || (act[a] === act[b] && a < b);
1616
+ const up = (i) => { const x = heap[i]; while (i > 0) {
1617
+ const pi = (i - 1) >> 1, y = heap[pi];
1618
+ if (!above(x, y))
1375
1619
  break;
1376
- if ('val' in r) {
1377
- done = finish(cur.model, r.val);
1378
- // (the simplex's values breaking it: elimination's)
1379
- if ('unknown' in done && r.exact) {
1380
- r = r.exact();
1381
- if (r && 'val' in r)
1382
- done = finish(cur.model, r.val);
1383
- }
1384
- if (r && !('val' in r)) {
1385
- for (const l of r.lemmas)
1386
- lemma(l);
1387
- cur = outcome(search());
1388
- if (!('model' in cur))
1389
- return cur;
1390
- done = finish(cur.model, undefined);
1391
- continue;
1392
- }
1393
- if ('unknown' in done)
1394
- done = finish(cur.model, undefined);
1620
+ heap[i] = y;
1621
+ at[y] = i;
1622
+ i = pi;
1623
+ } heap[i] = x; at[x] = i; };
1624
+ const down = (i) => { const x = heap[i]; for (;;) {
1625
+ let c = 2 * i + 1;
1626
+ if (c >= heap.length)
1395
1627
  break;
1628
+ if (c + 1 < heap.length && above(heap[c + 1], heap[c]))
1629
+ c++;
1630
+ if (!above(heap[c], x))
1631
+ break;
1632
+ heap[i] = heap[c];
1633
+ at[heap[i]] = i;
1634
+ i = c;
1635
+ } heap[i] = x; at[x] = i; };
1636
+ const push = (x) => { if (at[x] >= 0)
1637
+ return; heap.push(x); at[x] = heap.length - 1; up(heap.length - 1); };
1638
+ const pop = () => { const x = heap[0], y = heap.pop(); at[x] = -1; if (heap.length) {
1639
+ heap[0] = y;
1640
+ at[y] = 0;
1641
+ down(0);
1642
+ } return x; };
1643
+ const vid = (l) => {
1644
+ const a = Math.abs(l);
1645
+ let i = idx.get(a);
1646
+ if (i === undefined) {
1647
+ i = back.length;
1648
+ idx.set(a, i);
1649
+ back.push(a);
1650
+ reason.push(undefined);
1651
+ if (i >= cap) {
1652
+ const n = Math.max(1024, 2 * cap), grow = (x, mk) => { const y = mk(n); y.set(x); return y; };
1653
+ val = grow(val, k => new Int8Array(k));
1654
+ level = grow(level, k => new Int32Array(k));
1655
+ act = grow(act, k => new Float64Array(k));
1656
+ phase = grow(phase, k => new Int8Array(k));
1657
+ const at2 = new Int32Array(n).fill(-1);
1658
+ at2.set(at);
1659
+ at = at2;
1660
+ cap = n;
1661
+ }
1662
+ push(i);
1396
1663
  }
1397
- for (const l of r.lemmas) {
1398
- lemma(l);
1399
- const named = l.map((x) => [names[Math.abs(x)], x > 0]), key = named.map(([k, b]) => (b ? '' : '¬') + k).sort().join('|');
1400
- if (lemmaCache.size > 20_000)
1401
- lemmaCache.clear();
1402
- lemmaCache.set(key, named);
1403
- }
1404
- cur = outcome(search());
1405
- if (!('model' in cur))
1406
- return cur;
1407
- done = finish(cur.model, undefined);
1408
- }
1409
- return done;
1410
- }
1411
- function cdcl(input, budget, trueFirst = new Set(), late) {
1412
- return cdclSolver(input, trueFirst).solve(budget, late);
1413
- }
1414
- // The CDCL as a solver clauses can be added to between its answers (a lemma a model breaks, lazily): each added at level
1415
- // 0, the search again from there with what it learned. `add` false: a clause over a variable it doesn't have.
1416
- function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1417
- let n = 0;
1418
- for (const c of input)
1419
- for (const l of c.lits)
1420
- n = Math.max(n, Math.abs(l));
1421
- const idx = new Map(), back = [0];
1422
- const vid = (l) => { const a = Math.abs(l); let i = idx.get(a); if (i === undefined) {
1423
- i = back.length;
1424
- idx.set(a, i);
1425
- back.push(a);
1426
- } return l > 0 ? i : -i; };
1427
- const cls = input.map(c => ({ lits: c.lits.map(vid), from: new Set([c.from]) }));
1428
- const nv = back.length, val = new Int8Array(nv), level = new Int32Array(nv), reason = Array(nv), act = new Float64Array(nv);
1664
+ return l > 0 ? i : -i;
1665
+ };
1429
1666
  const watch = new Map();
1430
1667
  const wl = (l) => { let w = watch.get(l); if (!w)
1431
1668
  watch.set(l, (w = [])); return w; };
1432
1669
  const valOf = (l) => (val[Math.abs(l)] === 0 ? 0 : (val[Math.abs(l)] > 0) === (l > 0) ? 1 : -1);
1433
1670
  const trail = [], lim = [];
1434
- const phase = new Int8Array(nv);
1435
1671
  const assign = (l, r) => { val[Math.abs(l)] = l > 0 ? 1 : -1; level[Math.abs(l)] = lim.length; reason[Math.abs(l)] = r; trail.push(l); };
1436
- let qhead = 0, fixed = 'none';
1437
- const units = [];
1438
- for (const c of cls) {
1439
- if (!c.lits.length) {
1440
- fixed = { sat: false, core: c.from };
1441
- break;
1442
- }
1443
- if (c.lits.length === 1)
1444
- units.push(c);
1445
- else {
1446
- wl(-c.lits[0]).push(c);
1447
- wl(-c.lits[1]).push(c);
1448
- }
1449
- }
1450
- const coreOf = (c) => {
1451
- const out = new Set(c.from), seen = new Set(), todo = c.lits.map(Math.abs);
1672
+ let qhead = 0, fixed, seen = new Uint8Array(0);
1673
+ // (the origins of the reasons behind literals, through every level: a refutation's core)
1674
+ const coreOf = (lits, out) => {
1675
+ const seen = new Set(), todo = lits.map(Math.abs);
1452
1676
  while (todo.length) {
1453
1677
  const x = todo.pop();
1454
1678
  if (seen.has(x))
@@ -1464,20 +1688,10 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1464
1688
  }
1465
1689
  return out;
1466
1690
  };
1467
- for (const u of units) {
1468
- if (fixed !== 'none')
1469
- break;
1470
- const s = valOf(u.lits[0]);
1471
- if (s < 0) {
1472
- fixed = { sat: false, core: coreOf(u) };
1473
- break;
1474
- }
1475
- if (s === 0)
1476
- assign(u.lits[0], u);
1477
- }
1478
1691
  const propagate = () => {
1479
1692
  while (qhead < trail.length) {
1480
1693
  const l = trail[qhead++], ws = wl(l);
1694
+ eprMeter.n++;
1481
1695
  for (let i = 0; i < ws.length; i++) {
1482
1696
  const c = ws[i];
1483
1697
  if (c.lits[0] === -l) {
@@ -1508,39 +1722,6 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1508
1722
  }
1509
1723
  return undefined;
1510
1724
  };
1511
- // (the unassigned variables in a heap, the most active first, ties by the lower index: the choice a scan over them
1512
- // makes, without the scan; an assigned one is dropped where it surfaces and put back when unassigned)
1513
- const heap = [], at = new Int32Array(nv).fill(-1);
1514
- const above = (a, b) => act[a] > act[b] || (act[a] === act[b] && a < b);
1515
- const up = (i) => { const x = heap[i]; while (i > 0) {
1516
- const pi = (i - 1) >> 1, y = heap[pi];
1517
- if (!above(x, y))
1518
- break;
1519
- heap[i] = y;
1520
- at[y] = i;
1521
- i = pi;
1522
- } heap[i] = x; at[x] = i; };
1523
- const down = (i) => { const x = heap[i]; for (;;) {
1524
- let c = 2 * i + 1;
1525
- if (c >= heap.length)
1526
- break;
1527
- if (c + 1 < heap.length && above(heap[c + 1], heap[c]))
1528
- c++;
1529
- if (!above(heap[c], x))
1530
- break;
1531
- heap[i] = heap[c];
1532
- at[heap[i]] = i;
1533
- i = c;
1534
- } heap[i] = x; at[x] = i; };
1535
- const push = (x) => { if (at[x] >= 0)
1536
- return; heap.push(x); at[x] = heap.length - 1; up(heap.length - 1); };
1537
- const pop = () => { const x = heap[0], y = heap.pop(); at[x] = -1; if (heap.length) {
1538
- heap[0] = y;
1539
- at[y] = 0;
1540
- down(0);
1541
- } return x; };
1542
- for (let x = 1; x < nv; x++)
1543
- push(x);
1544
1725
  let inc = 1;
1545
1726
  const backjump = (bt) => { while (lim.length > bt) {
1546
1727
  const to = lim.pop();
@@ -1552,19 +1733,16 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1552
1733
  }
1553
1734
  } qhead = Math.min(qhead, trail.length); };
1554
1735
  const add = (c) => {
1555
- if (fixed !== 'none' && fixed?.sat === false)
1556
- return true;
1557
- if (c.lits.some(l => !idx.has(Math.abs(l))))
1558
- return false;
1736
+ if (fixed)
1737
+ return;
1559
1738
  backjump(0);
1560
- fixed = 'none';
1561
1739
  const cl = { lits: c.lits.map(vid), from: new Set([c.from]) };
1562
1740
  if (cl.lits.some(l => valOf(l) > 0))
1563
- return true;
1741
+ return;
1564
1742
  const open = cl.lits.filter(l => valOf(l) === 0);
1565
1743
  if (!open.length) {
1566
- fixed = { sat: false, core: coreOf(cl) };
1567
- return true;
1744
+ fixed = coreOf(cl.lits, new Set(cl.from));
1745
+ return;
1568
1746
  }
1569
1747
  cl.lits = [...open, ...cl.lits.filter(l => valOf(l) < 0)];
1570
1748
  if (open.length === 1)
@@ -1573,11 +1751,12 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1573
1751
  wl(-cl.lits[0]).push(cl);
1574
1752
  wl(-cl.lits[1]).push(cl);
1575
1753
  }
1576
- return true;
1577
1754
  };
1578
- const solve = (budget, late) => {
1579
- if (fixed !== 'none')
1580
- return fixed;
1755
+ const solve = (budget, late, assume) => {
1756
+ if (fixed)
1757
+ return { sat: false, core: fixed };
1758
+ backjump(0);
1759
+ const as = assume.map(vid);
1581
1760
  let conflicts = 0;
1582
1761
  for (;;) {
1583
1762
  const confl = propagate();
@@ -1585,9 +1764,11 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1585
1764
  if (++conflicts > budget || (conflicts % 256 === 0 && late?.()))
1586
1765
  return undefined;
1587
1766
  if (!lim.length)
1588
- return (fixed = { sat: false, core: coreOf(confl) });
1767
+ return { sat: false, core: (fixed = coreOf(confl.lits, new Set(confl.from))) };
1589
1768
  // first UIP
1590
- const seen = new Uint8Array(nv), learnt = [], from = new Set(confl.from);
1769
+ if (seen.length < back.length)
1770
+ seen = new Uint8Array(cap);
1771
+ const learnt = [], from = new Set(confl.from), marked = [];
1591
1772
  let p = 0, cnt = 0, c = confl, ti = trail.length - 1;
1592
1773
  do {
1593
1774
  for (const q of c.lits) {
@@ -1596,6 +1777,7 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1596
1777
  const x = Math.abs(q);
1597
1778
  if (!seen[x] && level[x] > 0) {
1598
1779
  seen[x] = 1;
1780
+ marked.push(x);
1599
1781
  act[x] = act[x] + inc;
1600
1782
  if (at[x] >= 0)
1601
1783
  up(at[x]);
@@ -1606,8 +1788,8 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1606
1788
  }
1607
1789
  else if (!seen[x] && level[x] === 0 && reason[x]) {
1608
1790
  seen[x] = 1;
1609
- for (const o of coreOf({ lits: [q], from: new Set() }))
1610
- from.add(o);
1791
+ marked.push(x);
1792
+ coreOf([q], from);
1611
1793
  }
1612
1794
  }
1613
1795
  while (!seen[Math.abs(trail[ti])])
@@ -1619,6 +1801,8 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1619
1801
  from.add(o);
1620
1802
  cnt--;
1621
1803
  } while (cnt > 0);
1804
+ for (const x of marked)
1805
+ seen[x] = 0;
1622
1806
  learnt.unshift(-p);
1623
1807
  inc *= 1.05;
1624
1808
  let bt = 0, bi = 1;
@@ -1632,17 +1816,9 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1632
1816
  learnt[1] = learnt[bi];
1633
1817
  learnt[bi] = t;
1634
1818
  }
1635
- while (lim.length > bt) {
1636
- const to = lim.pop();
1637
- while (trail.length > to) {
1638
- const x = Math.abs(trail.pop());
1639
- val[x] = 0;
1640
- reason[x] = undefined;
1641
- push(x);
1642
- }
1643
- }
1819
+ backjump(bt);
1644
1820
  qhead = trail.length;
1645
- const nc = { lits: learnt, from };
1821
+ const nc = { lits: learnt, from, learnt: true };
1646
1822
  if (learnt.length > 1) {
1647
1823
  wl(-learnt[0]).push(nc);
1648
1824
  wl(-learnt[1]).push(nc);
@@ -1650,6 +1826,16 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1650
1826
  assign(learnt[0], nc);
1651
1827
  continue;
1652
1828
  }
1829
+ // the assumptions first, in order: one already false is the refutation
1830
+ if (lim.length < as.length) {
1831
+ const l = as[lim.length], s = valOf(l);
1832
+ if (s < 0)
1833
+ return { sat: false, core: coreOf([l], new Set()) };
1834
+ lim.push(trail.length);
1835
+ if (s === 0)
1836
+ assign(l);
1837
+ continue;
1838
+ }
1653
1839
  // decide: the most active unassigned variable, false first
1654
1840
  let best = 0;
1655
1841
  while (heap.length) {
@@ -1661,7 +1847,7 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1661
1847
  }
1662
1848
  if (!best) {
1663
1849
  const model = [];
1664
- for (let x = 1; x < nv; x++) {
1850
+ for (let x = 1; x < back.length; x++) {
1665
1851
  model[back[x]] = val[x] > 0;
1666
1852
  if (keepPhase.has(back[x]))
1667
1853
  phase[x] = val[x];
@@ -1672,5 +1858,25 @@ function cdclSolver(input, trueFirst = new Set(), keepPhase = new Set()) {
1672
1858
  assign(phase[best] ? phase[best] * best : trueFirst.has(back[best]) ? best : -best);
1673
1859
  }
1674
1860
  };
1675
- return { solve, add };
1861
+ // (another goal's search from its clauses alone: the learned clauses, activities and phases of the goals before it
1862
+ // dropped, so its refutation and its model are a search of its own, as with an encoder of its own; a goal asked again
1863
+ // with more instances keeps its own)
1864
+ const fresh = () => {
1865
+ if (fixed)
1866
+ return;
1867
+ backjump(0);
1868
+ for (const [l, ws] of watch) {
1869
+ const ks = ws.filter(c => !c.learnt);
1870
+ if (ks.length !== ws.length)
1871
+ watch.set(l, ks);
1872
+ }
1873
+ act.fill(0);
1874
+ phase.fill(0);
1875
+ inc = 1;
1876
+ heap.length = 0;
1877
+ at.fill(-1);
1878
+ for (let x = 1; x < back.length; x++)
1879
+ push(x);
1880
+ };
1881
+ return { solve, add, fresh };
1676
1882
  }