gdp-wired 0.28.0 → 0.30.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.
@@ -21,11 +21,11 @@ import { costs, env, refuteFast, solve, work } from "../core/solver.js";
21
21
  import { checkRefutation } from "../core/check.js";
22
22
  import { atomOf, canon, canonFlip, isMonomial, leafConstraints } from "./kernel.js";
23
23
  import { cellPair, late, leafRowsOf, logged, nearOf, openAt, pairedKeys, queryHook, rowsAt, unitAtoms } from "./prove.js";
24
- import { Reader, namesOf } from "./reader.js";
24
+ import { Clausal, Reader, namesOf } from "./reader.js";
25
25
  import { Simplex } from "./simplex.js";
26
26
  // A derivation's own inputs: the rows it reads, in order, and the steps renumbered to them.
27
27
  function localize(rows, steps) {
28
- const inputs = [], at = new Map();
28
+ const inputs = [], at = new Map(), from = [];
29
29
  const out = steps.map(st => {
30
30
  if (st.kind !== 'input')
31
31
  return st;
@@ -34,10 +34,11 @@ function localize(rows, steps) {
34
34
  j = inputs.length;
35
35
  at.set(st.index, j);
36
36
  inputs.push(rows[st.index].lin);
37
+ from.push(st.index);
37
38
  }
38
39
  return { ...st, index: j };
39
40
  });
40
- return { inputs, steps: out };
41
+ return { inputs, steps: out, from };
41
42
  }
42
43
  // An atom's variable: the smaller of its canonical text and its flip's (remembered per form).
43
44
  const keyMemo = new WeakMap();
@@ -51,7 +52,7 @@ const keyOf = (lin) => {
51
52
  };
52
53
  // GDP_CDCL_LP=0: each node solved by elimination alone (no simplex); GDP_CDCL_FILL (8): the simplex's tableau begun
53
54
  // again past this many entries a row the node reads (research/step's comparisons).
54
- const lpFill = Number(env.GDP_CDCL_FILL ?? 8), useLp = env.GDP_CDCL_LP !== '0', verify = env.GDP_CDCL_VERIFY === '1';
55
+ const lpFill = Number(env.GDP_CDCL_FILL ?? 8), lpGrow = Number(env.GDP_CDCL_GROW ?? 4), lpBase = Number(env.GDP_CDCL_BASE ?? 500), lpGreedy = Number(env.GDP_CDCL_GREEDY ?? 200), useLp = env.GDP_CDCL_LP !== '0', verify = env.GDP_CDCL_VERIFY === '1';
55
56
  // Counters research/step reads (times only while `on`).
56
57
  export const cdclStats = { on: false, runs: 0, proven: 0, conflicts: 0, decisions: 0, solveMs: 0, rowsMs: 0, coreMs: 0, unfoldMs: 0, leaves: 0, resolved: 0, coreSize: 0, pathSize: 0, lpMisses: 0, resolved2: 0, unfoldWhy: '', orderMs: 0, boundMs: 0, openMisses: 0, lpMs: 0, lpUnknown: 0, fmCalls: 0, pivots: 0, lpRebuilds: 0, lpRows: 0, lpNnz: 0, lpVars: 0, lpLoad: 0, nodes: 0, boundRounds: 0 };
57
58
  // `opts.model`: only whether the goal has a model is wanted (core/bmc.ts): a refutation isn't unfolded into a tree, its
@@ -64,13 +65,25 @@ export function growCdcl(goal, root, budget, opts = {}) {
64
65
  const go = () => cdclSession(goal, root, opts).run(budget, opts.wall);
65
66
  return queryHook.on && !queryHook.depth ? logged(opts.model ? 'model' : 'cdcl', goal, go) : go();
66
67
  }
67
- // A search kept from one run to the next (core/bmc.ts's deeper goals): its atoms, their activities and phases, its learned
68
- // clauses and the simplex's tableau. Between runs the caller may add hypotheses to the goal (goal.hyps grows; none is
69
- // taken away), so every clause learned stays a consequence of the goal. A run may assume an atom (`assume`, decided
70
- // first, at level 1): where the search learns it false the run ends refuted (REFUTED), as where nothing is assumed and
71
- // the goal is refuted. Each run's own budget: nodes, `until` on the counted clock, `wall`.
68
+ // A search kept from one run to the next (core/bmc.ts's deeper goals, core/unroll.ts's sessions): its atoms, their
69
+ // activities and phases, its learned clauses and the simplex's tableau. Between runs the caller may add hypotheses to the
70
+ // goal (goal.hyps grows; none is taken away), so every clause learned stays a consequence of the goal. A run may assume
71
+ // atoms (`assume`, each decided first, at a level of its own, in order; gen/chc5-pdr's): where the search learns one false
72
+ // the run ends refuted (REFUTED), as where nothing is assumed and the goal is refuted; given a list, the refutation names
73
+ // the assumptions it needed (`assumed`, their indices, MiniSat's analyzeFinal), and with `dag` its DAG ends in the
74
+ // clause of those assumptions. Each run's own budget: nodes, `until` on the counted clock, `wall`.
75
+ // `quiet`, with `model`: names read only as decisions (a session's selectors): an atom over one of them alone brings no
76
+ // row (the simplex and the elimination never see it).
77
+ // `clausal`, with `model`: the goal read as clauses (reader.ts's Clausal) in place of the kernel's reading: unit
78
+ // propagation over them, the rows at a node the trail's atoms and their names' naturals, a decision an atom or gate of a
79
+ // clause no literal satisfies yet (the most active), a model where every clause is satisfied and the rows have an
80
+ // integer point. Where the goal reads what the clauses don't, the kernel's reading as before. `sideOf` colors gates and
81
+ // columns for interpolation (by the hypothesis that wrote them).
72
82
  export function cdclSession(goal, root, opts = {}) {
73
- let until = Infinity, budget = { nodes: 0 }, wall, assumed;
83
+ let until = Infinity, budget = { nodes: 0 }, wall, assumed = [], listed = false;
84
+ // (the first assumption not known to hold: those before it held when last looked at, and an assumption taken back
85
+ // brings it down to its own; each assumption's index by name)
86
+ let aq = 0, aqOf = new Map();
74
87
  const st = cdclStats, timing = st.on;
75
88
  const t = (f, add) => { if (!timing)
76
89
  return f(); const t0 = performance.now(); try {
@@ -80,11 +93,69 @@ export function cdclSession(goal, root, opts = {}) {
80
93
  add(performance.now() - t0);
81
94
  } };
82
95
  st.runs++;
83
- const vars = new Map(), trail = [], levels = [];
96
+ // (`tv`: the trail's variables, beside their names)
97
+ const vars = new Map(), trail = [], tv = [], levels = [];
98
+ // The clausal mode: the hypotheses as clauses (each clause a leaf of the DAG), how many literals of each input clause
99
+ // hold and how many input clauses none satisfies; the variables by activity (a heap), and those found read by
100
+ // satisfied clauses alone at a level (out of the heap until that level is taken back).
101
+ let clausal = !!(opts.clausal && opts.model), enc = clausal ? new Clausal(opts.sideOf) : undefined, fed = 0, dead = -1, unread = false, lowAt = 0;
102
+ if (enc)
103
+ for (; fed < goal.hyps.length; fed++)
104
+ if (!enc.add(goal.hyps[fed], fed)) {
105
+ clausal = false;
106
+ enc = undefined;
107
+ fed = 0;
108
+ break;
109
+ }
110
+ // (by a pair's code, 2·id + v: whether it holds, `vals[id]` 1 true, 2 false, 0 open; the clauses watching it; the input
111
+ // clauses that have it; a gate's clauses needed where it holds; each clause's pairs by code, the first two watched, and
112
+ // its gate's pair, or -1)
113
+ const heap = [], byId = [], vals = [];
114
+ // (relevance, top-down: a hypothesis' own clauses' variables at level 0, a gate's clauses' where the gate is relevant
115
+ // and holds the value that needs them; `rel` the level a variable became relevant at, or -1, `relStack` in order)
116
+ const rel = [], relStack = [];
117
+ const wl = [], ownBy = [], cls = [], oc = [];
118
+ // (each hypothesis' input clauses; those of a hypothesis retired, read no more)
119
+ const byHyp = [], retired = [];
120
+ const holds = (c) => vals[c >> 1] === 2 - (c & 1), opposed = (c) => vals[c >> 1] === 1 + (c & 1);
121
+ const heapUp = (i) => { const x = heap[i]; while (i > 0) {
122
+ const p = (i - 1) >> 1, y = heap[p];
123
+ if (y.act >= x.act)
124
+ break;
125
+ heap[i] = y;
126
+ y.hp = i;
127
+ i = p;
128
+ } heap[i] = x; x.hp = i; };
129
+ const heapDown = (i) => {
130
+ const x = heap[i], n = heap.length;
131
+ for (;;) {
132
+ let c = 2 * i + 1;
133
+ if (c >= n)
134
+ break;
135
+ if (c + 1 < n && heap[c + 1].act > heap[c].act)
136
+ c++;
137
+ if (heap[c].act <= x.act)
138
+ break;
139
+ heap[i] = heap[c];
140
+ heap[i].hp = i;
141
+ i = c;
142
+ }
143
+ heap[i] = x;
144
+ x.hp = i;
145
+ };
146
+ const heapIn = (x) => { if (!x.cond || rel[x.id] < 0 || (x.hp !== undefined && x.hp >= 0))
147
+ return; x.hp = heap.length; heap.push(x); heapUp(x.hp); };
148
+ const heapPop = () => { const top = heap[0], end = heap.pop(); top.hp = -1; if (heap.length) {
149
+ heap[0] = end;
150
+ end.hp = 0;
151
+ heapDown(0);
152
+ } };
84
153
  let sx = useLp ? new Simplex() : undefined;
154
+ if (sx && clausal)
155
+ sx.greedy = lpGreedy;
85
156
  const nodes = [], clauses = [], occ = new Map();
86
157
  // (with opts.core: each leaf's hypotheses, by node; the hypothesis each row at this node came from)
87
- const leafHyps = new Map(), wantCore = !!(opts.core && opts.model);
158
+ const leafHyps = new Map(), wantCore = !!(opts.core && opts.model), wantDag = !!(opts.dag && opts.model);
88
159
  const hypsOf = (rs) => {
89
160
  return reader.hypsOf(rs);
90
161
  };
@@ -94,7 +165,15 @@ export function cdclSession(goal, root, opts = {}) {
94
165
  const key = keyOf(lin);
95
166
  if (!vars.has(key)) {
96
167
  const flip = key !== canon(lin), stored = flip ? atomOf(lin, false).lin : lin, terms = Object.entries(stored).filter(([x0]) => x0 !== '1');
97
- vars.set(key, { name: key, lin: stored, terms, col: terms.some(([x0]) => x0.startsWith('⟦')), level: -1, at: -1, act: 0, phase: !flip });
168
+ const x = { name: key, lin: stored, terms, col: terms.some(([x0]) => x0.startsWith('⟦')), id: byId.length, level: -1, at: -1, act: 0, phase: !flip };
169
+ byId.push(x);
170
+ vals.push(0);
171
+ rel.push(-1);
172
+ if (opts.model && terms.length === 1 && (opts.quiet?.(terms[0][0]) || (clausal && terms[0][0].startsWith('τ'))))
173
+ x.quiet = true;
174
+ vars.set(key, x);
175
+ if (clausal)
176
+ heapIn(x);
98
177
  }
99
178
  return key;
100
179
  };
@@ -147,13 +226,15 @@ export function cdclSession(goal, root, opts = {}) {
147
226
  x.at = trail.length;
148
227
  stamps[x.at] = ++stampN;
149
228
  trail.push(name);
229
+ tv.push(x);
150
230
  rootNames.add(name);
151
231
  if (x.col)
152
232
  colsOn++;
153
233
  }
154
- const reader = new Reader(goal, {
234
+ const reader = new Reader(clausal ? { name: goal.name, hyps: [] } : goal, {
155
235
  get: name => vars.get(name), stamp: at => stamps[at], size: () => trail.length,
156
236
  lin: at => { const name = trail[at], x = vars.get(name); return { name, lin: x.lin, holds: x.val }; },
237
+ ...(clausal || opts.quiet ? { quiet: (at) => !!tv[at].quiet } : {}),
157
238
  });
158
239
  let last = goal.hyps.length - 1;
159
240
  const near = nearOf(goal);
@@ -161,42 +242,120 @@ export function cdclSession(goal, root, opts = {}) {
161
242
  const fixed = trail.length;
162
243
  const level = () => levels.length;
163
244
  const pathOf = () => new Map(trail.map(name => { const x = vars.get(name); return [name, { lin: x.lin, holds: x.val }]; }));
164
- const assign = (name, val, reason) => {
165
- const x = vars.get(name);
245
+ // (the kernel reading's and the clausal mode's each a function of its own, so neither's hot path reads the other's)
246
+ const assignKernel = (x, val, reason) => {
247
+ const name = x.name;
248
+ lowAt = Math.min(lowAt, trail.length);
166
249
  x.val = val;
167
250
  x.level = level();
168
251
  x.at = trail.length;
169
252
  x.phase = val;
170
253
  stamps[x.at] = ++stampN;
171
- if (reason === undefined)
172
- delete x.reason;
173
- else
174
- x.reason = reason;
254
+ x.reason = reason;
175
255
  trail.push(name);
256
+ tv.push(x);
176
257
  if (x.col)
177
258
  colsOn++;
178
259
  if (x.pair)
179
260
  pairsChanged++;
180
261
  reader.touch(name);
181
262
  };
182
- const undoTo = (l) => {
263
+ const assignClausal = (x, val, reason) => {
264
+ lowAt = Math.min(lowAt, trail.length);
265
+ x.val = val;
266
+ x.level = level();
267
+ x.at = trail.length;
268
+ x.phase = val;
269
+ stamps[x.at] = ++stampN;
270
+ x.reason = reason;
271
+ trail.push(x.name);
272
+ tv.push(x);
273
+ vals[x.id] = val ? 1 : 2;
274
+ if (rel[x.id] >= 0)
275
+ activate(x.id);
276
+ };
277
+ const assignVar = clausal ? assignClausal : assignKernel;
278
+ const assign = (name, val, reason) => assignVar(vars.get(name), val, reason);
279
+ // A variable relevant (at this level), and, where it is a gate with a value, the clauses that value needs: their
280
+ // variables relevant in turn.
281
+ const relevant = (id) => {
282
+ if (rel[id] >= 0)
283
+ return;
284
+ rel[id] = levels.length;
285
+ relStack.push(id);
286
+ heapIn(byId[id]);
287
+ if (vals[id])
288
+ activate(id);
289
+ };
290
+ const activate = (id0) => {
291
+ for (const todo = [id0]; todo.length;) {
292
+ const id = todo.pop(), own = ownBy[2 * id + (vals[id] === 1 ? 1 : 0)];
293
+ if (!own)
294
+ continue;
295
+ for (let i = 0; i < own.length; i++) {
296
+ const ci = own[i];
297
+ if (retired[ci])
298
+ continue;
299
+ const c = cls[ci];
300
+ costs.scan += 1 + (c.length >> 2);
301
+ for (let j = 0; j < c.length; j++) {
302
+ const y = c[j] >> 1;
303
+ if (rel[y] < 0) {
304
+ rel[y] = levels.length;
305
+ relStack.push(y);
306
+ heapIn(byId[y]);
307
+ if (vals[y])
308
+ todo.push(y);
309
+ }
310
+ }
311
+ }
312
+ }
313
+ };
314
+ const undoKernel = (l) => {
183
315
  const keep = levels[l] ?? trail.length;
184
316
  while (trail.length > Math.max(keep, fixed)) {
185
- const name = trail.pop(), x = vars.get(name);
186
- delete x.val;
317
+ const name = trail.pop(), x = tv.pop(), q = aqOf.size ? aqOf.get(name) : undefined;
318
+ x.val = undefined;
187
319
  x.level = -1;
188
- delete x.reason;
320
+ x.reason = undefined;
189
321
  if (x.col)
190
322
  colsOn--;
191
323
  if (x.pair)
192
324
  pairsChanged++;
193
325
  reader.touch(name);
326
+ if (q !== undefined && q < aq)
327
+ aq = q;
194
328
  }
329
+ lowAt = Math.min(lowAt, trail.length);
195
330
  levels.length = l;
196
331
  };
332
+ const undoClausal = (l) => {
333
+ const keep = levels[l] ?? trail.length, undone = [];
334
+ while (trail.length > keep) {
335
+ const name = trail.pop(), x = tv.pop(), q = aqOf.size ? aqOf.get(name) : undefined;
336
+ vals[x.id] = 0;
337
+ undone.push(x);
338
+ x.val = undefined;
339
+ x.level = -1;
340
+ x.reason = undefined;
341
+ if (q !== undefined && q < aq)
342
+ aq = q;
343
+ }
344
+ lowAt = Math.min(lowAt, trail.length);
345
+ levels.length = l;
346
+ while (relStack.length && rel[relStack.at(-1)] > l)
347
+ rel[relStack.pop()] = -1;
348
+ for (const x of undone)
349
+ heapIn(x);
350
+ };
351
+ const undoTo = clausal ? undoClausal : undoKernel;
197
352
  const addClause = (lits, node) => {
198
353
  clauses.push({ lits, node });
199
354
  const i = clauses.length - 1;
355
+ if (clausal) {
356
+ watches(i);
357
+ return i;
358
+ }
200
359
  for (const [name, pos] of lits) {
201
360
  const key = `${name}=${pos}`;
202
361
  let xs = occ.get(key);
@@ -206,12 +365,153 @@ export function cdclSession(goal, root, opts = {}) {
206
365
  }
207
366
  return i;
208
367
  };
368
+ // The clausal mode's watches: each clause's pairs by code, its first two watched, those that don't hold first, then
369
+ // those that came last on the trail (a learned clause's: its latest two).
370
+ const watches = (ci) => {
371
+ const c = Int32Array.from([...clauses[ci].lits].map(([name, pos]) => 2 * vars.get(name).id + (pos ? 1 : 0)));
372
+ cls[ci] = c;
373
+ oc[ci] = -1;
374
+ if (c.length < 2)
375
+ return;
376
+ const rank = (z) => (holds(z) ? byId[z >> 1].at : Infinity);
377
+ for (const j of [0, 1]) {
378
+ let b = j;
379
+ for (let q = j + 1; q < c.length; q++)
380
+ if (rank(c[q]) > rank(c[b]))
381
+ b = q;
382
+ const t0 = c[j];
383
+ c[j] = c[b];
384
+ c[b] = t0;
385
+ }
386
+ for (const j of [0, 1])
387
+ (wl[c[j]] ??= []).push(ci, c[1 - j]);
388
+ };
389
+ // The clausal mode's clauses of the hypotheses not yet taken (each a leaf: its hypothesis and its literals), at level 0:
390
+ // a unit's literal assigned, an empty one the goal refuted, every clause read again by propagation from the trail's
391
+ // start; the variables left out as read by satisfied clauses alone put back.
392
+ const take = () => {
393
+ if (!enc)
394
+ return;
395
+ for (; fed < goal.hyps.length; fed++)
396
+ if (!enc.add(goal.hyps[fed], fed)) {
397
+ unread = true;
398
+ break;
399
+ }
400
+ if (!enc.made.length)
401
+ return;
402
+ for (const { lits, hyp, own, out } of enc.made) {
403
+ const m = new Map();
404
+ for (const l of lits) {
405
+ const name = ensure(l.lin);
406
+ m.set(name, !(name === canon(l.lin) ? l.holds : !l.holds));
407
+ }
408
+ nodes.push({ hyp, lits: [...m].map(([name, pos]) => [vars.get(name).lin, pos]) });
409
+ // (a variable decided only where some clause reads it as more than a case's atom)
410
+ let j = 0;
411
+ for (const name of m.keys()) {
412
+ const x = vars.get(name);
413
+ if (!x.cond && !(out && j === m.size - 1)) {
414
+ x.cond = true;
415
+ heapIn(x);
416
+ }
417
+ j++;
418
+ }
419
+ const ci = addClause(m, nodes.length - 1);
420
+ clauses[ci].input = true;
421
+ (byHyp[hyp] ??= []).push(ci);
422
+ if (own && m.size) {
423
+ const [name, pos] = m.entries().next().value, z = 2 * vars.get(name).id + (pos ? 1 : 0);
424
+ oc[ci] = z;
425
+ (ownBy[z] ??= []).push(ci);
426
+ }
427
+ let open;
428
+ for (const name of m.keys())
429
+ if (vars.get(name).val === undefined)
430
+ open = name;
431
+ if (!m.size)
432
+ dead = nodes.length - 1;
433
+ else if (m.size === 1 && open !== undefined)
434
+ assign(open, !m.get(open), ci);
435
+ else if (m.size === 1 && dead < 0) {
436
+ // (a unit false at level 0, which no watch sees: resolved with the reasons below it down to the empty clause)
437
+ let c = clauses[ci];
438
+ while (c.lits.size) {
439
+ let best;
440
+ for (const name of c.lits.keys()) {
441
+ const y = vars.get(name);
442
+ if (y.val === c.lits.get(name) && (!best || y.at > best.at))
443
+ best = y;
444
+ }
445
+ if (!best || best.reason === undefined)
446
+ break;
447
+ c = resolveOn(c, best.name);
448
+ }
449
+ if (!c.lits.size)
450
+ dead = c.node;
451
+ }
452
+ // (a hypothesis' own clause: its variables relevant for good; a gate's, where the gate needs it already)
453
+ if (oc[ci] < 0 || (rel[oc[ci] >> 1] >= 0 && holds(oc[ci])))
454
+ for (const name of m.keys())
455
+ relevant(vars.get(name).id);
456
+ }
457
+ enc.made = [];
458
+ qhead = 0;
459
+ };
460
+ // The open variable a decision takes in the clausal mode: the most active relevant one. A clause is needed where it is
461
+ // a hypothesis' own (no gate's), or its gate is relevant and its literal in the clause false; every variable of a
462
+ // needed clause is relevant, so where none is open, every needed clause is satisfied (unit propagation found no
463
+ // conflict), and a model of the needed clauses is a model of the goal.
464
+ const needed = (ci) => !retired[ci] && (oc[ci] < 0 || (rel[oc[ci] >> 1] >= 0 && holds(oc[ci])));
465
+ const satisfied = (ci) => { const c = cls[ci]; costs.scan += 1 + (c.length >> 2); for (let j = 0; j < c.length; j++)
466
+ if (opposed(c[j]))
467
+ return true; return false; };
468
+ const pickOpen = () => {
469
+ while (heap.length) {
470
+ const x = heap[0];
471
+ if (x.val !== undefined || rel[x.id] < 0) {
472
+ heapPop();
473
+ continue;
474
+ }
475
+ return x;
476
+ }
477
+ // (never: GDP_CDCL_VERIFY=1 checks it where a model is about to be answered)
478
+ if (verify)
479
+ for (let ci = 0; ci < clauses.length; ci++)
480
+ if (clauses[ci].input && needed(ci) && !satisfied(ci))
481
+ throw new Error('clausal: a needed clause unsatisfied with no open variable');
482
+ return undefined;
483
+ };
484
+ // A point of the rows the simplex is at, where it is integral and meets them all (a model then).
485
+ const pointOf = (lp, rows) => {
486
+ const w = {};
487
+ for (const r of rows)
488
+ for (const n of namesOf(r.lin))
489
+ if (!(n in w)) {
490
+ const j = lp.indexOf(n);
491
+ if (j === undefined)
492
+ return undefined;
493
+ const x = lp.value(j), y = Math.round(x);
494
+ if (Math.abs(x - y) > 1e-9)
495
+ return undefined;
496
+ w[n] = y;
497
+ }
498
+ for (const r of rows) {
499
+ let x = r.lin['1'] ?? 0;
500
+ for (const n of namesOf(r.lin))
501
+ x += r.lin[n] * w[n];
502
+ if (x > 0)
503
+ return undefined;
504
+ }
505
+ return w;
506
+ };
209
507
  let qhead = 0;
210
508
  // Unit propagation: a clause whose literals all hold is a conflict (its index); all but one, the last is flipped.
211
- const propagate = () => {
509
+ const propagateKernel = () => {
212
510
  while (qhead < trail.length) {
213
- const name = trail[qhead++], x = vars.get(name);
214
- for (const ci of occ.get(`${name}=${x.val}`) ?? []) {
511
+ const name = trail[qhead++], x = vars.get(name), os = occ.get(`${name}=${x.val}`);
512
+ if (!os)
513
+ continue;
514
+ for (const ci of os) {
215
515
  const c = clauses[ci];
216
516
  let open, nOpen = 0, dead = false;
217
517
  for (const [w, p] of c.lits) {
@@ -236,6 +536,64 @@ export function cdclSession(goal, root, opts = {}) {
236
536
  }
237
537
  return undefined;
238
538
  };
539
+ // The clausal mode's, over the watches: a pair that now holds moves its watch to a pair that doesn't, else the clause
540
+ // is unit, its other watched pair's variable flipped, or, that pair holding too, a conflict.
541
+ const propagateClausal = () => {
542
+ // (each watch a clause and a blocker, a pair of it that, where it doesn't hold, satisfies the clause untouched)
543
+ while (qhead < trail.length) {
544
+ const x = tv[qhead++], code = 2 * x.id + (x.val ? 1 : 0), ws = wl[code];
545
+ if (!ws)
546
+ continue;
547
+ let n = 0;
548
+ for (let i = 0; i < ws.length;) {
549
+ if (opposed(ws[i + 1])) {
550
+ i += 2;
551
+ continue;
552
+ }
553
+ const ci = ws[i], c = cls[ci];
554
+ n++;
555
+ if (retired[ci]) {
556
+ ws[i] = ws[ws.length - 2];
557
+ ws[i + 1] = ws[ws.length - 1];
558
+ ws.length -= 2;
559
+ continue;
560
+ }
561
+ if (c[0] === code) {
562
+ c[0] = c[1];
563
+ c[1] = code;
564
+ }
565
+ const o = c[0];
566
+ if (opposed(o)) {
567
+ ws[i + 1] = o;
568
+ i += 2;
569
+ continue;
570
+ }
571
+ let j = 2;
572
+ while (j < c.length && holds(c[j]))
573
+ j++;
574
+ if (j < c.length) {
575
+ const z = c[j];
576
+ c[j] = code;
577
+ c[1] = z;
578
+ (wl[z] ??= []).push(ci, o);
579
+ ws[i] = ws[ws.length - 2];
580
+ ws[i + 1] = ws[ws.length - 1];
581
+ ws.length -= 2;
582
+ continue;
583
+ }
584
+ if (!vals[o >> 1]) {
585
+ assignVar(byId[o >> 1], !(o & 1), ci);
586
+ i += 2;
587
+ continue;
588
+ }
589
+ costs.scan += n;
590
+ return ci;
591
+ }
592
+ costs.scan += n;
593
+ }
594
+ return undefined;
595
+ };
596
+ const propagate = clausal ? propagateClausal : propagateKernel;
239
597
  const bump = (lits) => {
240
598
  for (const name of lits.keys()) {
241
599
  const x = vars.get(name);
@@ -245,6 +603,8 @@ export function cdclSession(goal, root, opts = {}) {
245
603
  y.act *= 1e-100;
246
604
  inc *= 1e-100;
247
605
  }
606
+ if (clausal && x.hp !== undefined && x.hp >= 0)
607
+ heapUp(x.hp);
248
608
  }
249
609
  inc /= 0.95;
250
610
  };
@@ -263,8 +623,8 @@ export function cdclSession(goal, root, opts = {}) {
263
623
  };
264
624
  // A leaf: the decisions of a reason (the root's are every leaf's, below which the tree starts: not literals of its
265
625
  // clause) and a derivation over the rows it reads.
266
- const leafNode = (w, inputs, steps, extra, hyps) => {
267
- nodes.push({ inputs, steps });
626
+ const leafNode = (w, inputs, steps, extra, hyps, src) => {
627
+ nodes.push(src ? { inputs, steps, src } : { inputs, steps });
268
628
  if (hyps)
269
629
  leafHyps.set(nodes.length - 1, hyps);
270
630
  st.leaves++;
@@ -274,6 +634,8 @@ export function cdclSession(goal, root, opts = {}) {
274
634
  lits.set(name, vars.get(name).val);
275
635
  if (extra)
276
636
  lits.set(extra[0], extra[1]);
637
+ if (src)
638
+ nodes.at(-1).lits = [...lits].map(([name, val]) => [vars.get(name).lin, val]);
277
639
  st.coreSize += lits.size;
278
640
  return { lits, node: nodes.length - 1 };
279
641
  };
@@ -286,7 +648,7 @@ export function cdclSession(goal, root, opts = {}) {
286
648
  w.add(name);
287
649
  st.pathSize += trail.length - fixed;
288
650
  const local = localize(rows, steps);
289
- return leafNode(w, local.inputs, local.steps, undefined, wantCore ? hypsOf(steps.flatMap(s => (s.kind === 'input' ? [rows[s.index]] : []))) : undefined);
651
+ return leafNode(w, local.inputs, local.steps, undefined, wantCore ? hypsOf(steps.flatMap(s => (s.kind === 'input' ? [rows[s.index]] : []))) : undefined, wantDag ? local.from.map(i => reader.srcOf(rows[i]) ?? -1) : undefined);
290
652
  }, ms => { st.coreMs += ms; });
291
653
  // Bound propagation's reasons, made when conflict analysis reads them: the atom's bounds (single-variable rows at the
292
654
  // trail then) and its other side refute each other, a leaf at the bounds' reasons with that side decided.
@@ -298,10 +660,82 @@ export function cdclSession(goal, root, opts = {}) {
298
660
  const s = solve(local);
299
661
  if (s.kind !== 'refuted')
300
662
  throw new Error('a bound propagation its bounds do not refute');
301
- const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val], b.hyps);
663
+ const loc = localize(local, s.steps), made = leafNode(b.w, loc.inputs, loc.steps, [b.name, !b.val], b.hyps, b.src && loc.from.map(i => b.src[i] ?? -1));
302
664
  c.lits = made.lits;
303
665
  c.node = made.node;
304
666
  }, ms => { st.coreMs += ms; });
667
+ // The clausal mode's conflict analysis: the same resolutions, in one pass down the trail (the clause kept as it is
668
+ // resolved, its literals at its latest level counted, each step the latest of them on the trail).
669
+ const analyzeClausal = (c) => {
670
+ const lits = new Map(c.lits);
671
+ let node = c.node, { top, here } = levelsOf(c), p = trail.length - 1;
672
+ if (top < level()) {
673
+ undoTo(top);
674
+ qhead = trail.length;
675
+ p = trail.length - 1;
676
+ }
677
+ while (lits.size && !(top > 0 && here === 1)) {
678
+ while (p >= 0 && !(lits.has(trail[p]) && vars.get(trail[p]).level === top))
679
+ p--;
680
+ const name = trail[p], x = vars.get(name);
681
+ if (top > 0 && x.reason === undefined)
682
+ break;
683
+ const r = clauses[x.reason];
684
+ if (r.node < 0)
685
+ materialize(x.reason);
686
+ nodes.push({ res: lits.get(name) ? [node, r.node] : [r.node, node], on: x.lin });
687
+ st.resolved++;
688
+ node = nodes.length - 1;
689
+ lits.delete(name);
690
+ here--;
691
+ for (const [w, q] of r.lits)
692
+ if (w !== name && !lits.has(w)) {
693
+ lits.set(w, q);
694
+ if (vars.get(w).level === top)
695
+ here++;
696
+ }
697
+ }
698
+ return { lits, node };
699
+ };
700
+ // (a decision at the simplex's last point, without a node: `free` of them after a node whose rows it met)
701
+ const decideFree = () => {
702
+ const x = pickOpen();
703
+ if (!x)
704
+ return false;
705
+ free--;
706
+ if (!x.quiet && sx)
707
+ phaseAtPoint(x, sx);
708
+ levels.push(trail.length);
709
+ st.decisions++;
710
+ assignVar(x, x.phase);
711
+ return true;
712
+ };
713
+ const levelsOf = (c) => {
714
+ let top = -1, here = 0, latest, at = -1;
715
+ for (const name of c.lits.keys()) {
716
+ const x = vars.get(name);
717
+ if (x.level > top) {
718
+ top = x.level;
719
+ here = 1;
720
+ latest = name;
721
+ at = x.at;
722
+ }
723
+ else if (x.level === top) {
724
+ here++;
725
+ if (x.at > at) {
726
+ latest = name;
727
+ at = x.at;
728
+ }
729
+ }
730
+ }
731
+ let below = 0;
732
+ for (const name of c.lits.keys()) {
733
+ const l = vars.get(name).level;
734
+ if (name !== latest && l > below)
735
+ below = l;
736
+ }
737
+ return { top, here, latest, below };
738
+ };
305
739
  const luby = (i) => { let n = 1; while ((1 << n) - 1 < i + 1)
306
740
  n++; return (1 << n) - 1 === i + 1 ? 1 << (n - 1) : luby(i + 1 - (1 << (n - 1))); };
307
741
  // With a model wanted: each open atom's phase (no term column's) set to its value at the simplex's point, which meets
@@ -334,7 +768,8 @@ export function cdclSession(goal, root, opts = {}) {
334
768
  }
335
769
  x.phase = v <= 1e-7 * Math.max(1, Math.abs(v));
336
770
  };
337
- let restartAt = 32, nRestart = 0, sinceRestart = 0;
771
+ let restartAt = 32, nRestart = 0, sinceRestart = 0, free = 0;
772
+ const batch = Number(env.GDP_CDCL_BATCH ?? 16);
338
773
  const stuck = (kind, why, extra = {}) => ({ stuck: kind, path: pathOf(), why, ...extra });
339
774
  const run = (b, w, assume) => {
340
775
  budget = b;
@@ -344,38 +779,117 @@ export function cdclSession(goal, root, opts = {}) {
344
779
  restartAt = 32;
345
780
  nRestart = 0;
346
781
  sinceRestart = 0;
347
- undoTo(0);
348
- qhead = Math.min(qhead, trail.length); // (a run before this one may have left decisions)
349
- if (assume) {
350
- const name = ensure(assume);
351
- assumed = [name, name === canon(assume)];
352
- }
353
- else
354
- assumed = undefined;
782
+ listed = Array.isArray(assume);
783
+ assumed = (assume === undefined ? [] : Array.isArray(assume) ? assume : [assume]).map(lin => { const name = ensure(lin); return [name, name === canon(lin)]; });
784
+ // (a run before this one may have left decisions: given a list, the levels whose decisions are its first
785
+ // assumptions in order stay, each assumption before them holding below them already, so the rows they read stand;
786
+ // none where the clausal mode has hypotheses to take)
787
+ let keep = 0;
788
+ if (listed && !(enc && fed < goal.hyps.length))
789
+ for (let l = 0, q = 0; l < levels.length; l++) {
790
+ const d = trail[levels[l]];
791
+ for (let y = q < assumed.length ? vars.get(assumed[q][0]) : undefined; y && y.val === assumed[q][1] && y.at < levels[l]; y = ++q < assumed.length ? vars.get(assumed[q][0]) : undefined)
792
+ ;
793
+ if (q >= assumed.length || assumed[q][0] !== d || vars.get(d).val !== assumed[q][1])
794
+ break;
795
+ q++;
796
+ keep = l + 1;
797
+ }
798
+ aq = 0;
799
+ aqOf = new Map(assumed.map(([name], q) => [name, q]));
800
+ undoTo(keep);
801
+ qhead = Math.min(qhead, trail.length);
802
+ take();
803
+ if (unread)
804
+ return { stuck: 'unknown', path: new Map(), why: 'a hypothesis the clauses do not read' };
805
+ if (dead >= 0)
806
+ return { stuck: 'unknown', path: new Map(), why: REFUTED, ...(listed ? { assumed: [] } : {}), ...(wantDag ? { dag: { nodes, top: dead, clausal } } : {}) };
355
807
  return queryHook.on && !queryHook.depth ? logged(opts.model ? 'model' : 'cdcl', goal, search) : search();
356
808
  };
809
+ // The assumptions a falsified one rests on: the decisions its reasons reach, each reason materialized where it is a
810
+ // bound's (every decision on the trail is an assumption here: the search decides nothing else until they all hold).
811
+ const final = (q0) => {
812
+ const at = aqOf, out = new Set([q0]), seen = new Set(), todo = [assumed[q0][0]];
813
+ while (todo.length) {
814
+ const name = todo.pop(), x = vars.get(name);
815
+ if (seen.has(name) || x.level <= 0)
816
+ continue;
817
+ seen.add(name);
818
+ if (x.reason === undefined) {
819
+ const q = at.get(name);
820
+ if (q !== undefined)
821
+ out.add(q);
822
+ continue;
823
+ }
824
+ if (clauses[x.reason].node < 0)
825
+ materialize(x.reason);
826
+ for (const w of clauses[x.reason].lits.keys())
827
+ if (w !== name)
828
+ todo.push(w);
829
+ }
830
+ return [...out].sort((a, b) => a - b);
831
+ };
832
+ // With `dag`: the falsified assumption's reason resolved with the reasons of every literal in it that is no
833
+ // assumption, latest first, down to a clause of assumptions alone (the DAG's last node).
834
+ const finalDag = (q0) => {
835
+ const x0 = vars.get(assumed[q0][0]);
836
+ if (clauses[x0.reason].node < 0)
837
+ materialize(x0.reason);
838
+ let c = clauses[x0.reason];
839
+ for (;;) {
840
+ let best;
841
+ for (const name of c.lits.keys()) {
842
+ if (aqOf.has(name))
843
+ continue;
844
+ const y = vars.get(name);
845
+ if (!best || y.at > best.at)
846
+ best = y;
847
+ }
848
+ if (!best)
849
+ return c.node;
850
+ c = resolveOn(c, best.name);
851
+ }
852
+ };
357
853
  const search = () => {
358
854
  for (;;) {
359
855
  if (++budget.nodes > 200_000 || late(until) || (wall !== undefined && performance.now() > wall))
360
856
  return stuck('unknown', budget.nodes > 200_000 ? 'nodes' : 'time');
361
857
  let conflict;
362
858
  const ci = propagate();
859
+ let open = -1, wrong = -1;
860
+ if (ci === undefined)
861
+ for (; aq < assumed.length; aq++) {
862
+ const val = vars.get(assumed[aq][0]).val;
863
+ if (val === !assumed[aq][1]) {
864
+ wrong = aq;
865
+ break;
866
+ }
867
+ if (val === undefined) {
868
+ open = aq;
869
+ break;
870
+ }
871
+ }
363
872
  if (ci !== undefined)
364
873
  conflict = clauses[ci];
365
- else if (assumed && vars.get(assumed[0]).val === !assumed[1])
366
- return { stuck: 'unknown', path: new Map(), why: REFUTED };
367
- else if (assumed && vars.get(assumed[0]).val === undefined) {
874
+ else if (wrong >= 0)
875
+ return { stuck: 'unknown', path: new Map(), why: REFUTED, ...(listed ? { assumed: final(wrong) } : {}), ...(wantDag ? { dag: { nodes, top: finalDag(wrong), clausal } } : {}) };
876
+ else if (open >= 0) {
368
877
  levels.push(trail.length);
369
- assign(assumed[0], assumed[1]);
878
+ assign(assumed[open][0], assumed[open][1]);
370
879
  continue;
371
880
  }
372
881
  else {
882
+ // (the clausal mode: after a node whose rows the simplex met, up to `batch` decisions more before the next node,
883
+ // each its own level, an atom's value the point's: they keep that point, so the rows meet it but where unit
884
+ // propagation brought an atom it doesn't meet, which the next node finds)
885
+ if (free > 0 && decideFree())
886
+ continue;
373
887
  reader.begin();
374
888
  st.nodes++;
375
889
  // The rows, kept from the node before (reader.ts's sync); the forms that came and went: the single-variable
376
890
  // ones' bounds now (for bound propagation, `bx`), the simplex's when it next runs (`toAssert`, `toRetract`: a
377
891
  // form in and out between its runs never reaches it).
378
- const rowsR = t(() => (reader.sync(), reader.live), ms => { st.rowsMs += ms; });
892
+ const rowsR = t(() => (reader.sync(lowAt), lowAt = trail.length, reader.live), ms => { st.rowsMs += ms; });
379
893
  const full = rowsR;
380
894
  const single = (id) => reader.form(full[reader.slotOf(id)].lin).names.length === 1;
381
895
  for (const id of reader.left) {
@@ -392,7 +906,7 @@ export function cdclSession(goal, root, opts = {}) {
392
906
  if (sx && !toRetract.delete(id))
393
907
  toAssert.add(id);
394
908
  }
395
- if (verify) {
909
+ if (verify && !clausal) {
396
910
  const mine = new Set(rowsR.map(r => canon(r.lin))), theirs = new Set(leafConstraints(goal, pathOf()).map(r => canon(r.lin)));
397
911
  if (mine.size !== theirs.size || [...mine].some(x => !theirs.has(x)))
398
912
  throw new Error(`reader.ts's rows differ from kernel.ts's at a node of ${goal.name}`);
@@ -416,6 +930,10 @@ export function cdclSession(goal, root, opts = {}) {
416
930
  // The candidates, in growPlain's order: the units, the conclusion's open atoms, the hypotheses' near it, the
417
931
  // rest, pairs of cells.
418
932
  const cands = t(() => {
933
+ if (clausal) {
934
+ const x = pickOpen();
935
+ return x ? [x] : [];
936
+ }
419
937
  // (each list's forms' variables kept with the list, the same array while it stands)
420
938
  const g = ++candGen, keep = [];
421
939
  const take = (lins) => {
@@ -497,7 +1015,7 @@ export function cdclSession(goal, root, opts = {}) {
497
1015
  for (const n of rowsR[i].w)
498
1016
  w.add(n);
499
1017
  clauses.push({ lits: new Map([[name, !val]]), node: -1 });
500
- pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val, ...(wantCore ? { hyps: hypsOf(used.map(i => rowsR[i])) } : {}) });
1018
+ pending.set(clauses.length - 1, { w, used: used.map(i => full[i].lin), name, val, ...(wantCore ? { hyps: hypsOf(used.map(i => rowsR[i])) } : {}), ...(wantDag ? { src: used.map(i => reader.srcOf(rowsR[i]) ?? -1) } : {}) });
501
1019
  assign(name, val, clauses.length - 1);
502
1020
  forced++;
503
1021
  break;
@@ -520,9 +1038,11 @@ export function cdclSession(goal, root, opts = {}) {
520
1038
  if (sx) {
521
1039
  const t0 = timing ? performance.now() : 0;
522
1040
  // (a tableau that has gathered many more forms than a node reads is begun again: every pivot updates them all)
523
- const over = sx.size > 4 * full.length + 500 || sx.nnz > lpFill * full.length;
1041
+ const over = sx.size > (clausal ? lpGrow : 4) * full.length + (clausal ? lpBase : 500) || sx.nnz > lpFill * full.length;
524
1042
  if (over) {
525
1043
  sx = new Simplex();
1044
+ if (clausal)
1045
+ sx.greedy = lpGreedy;
526
1046
  st.lpRebuilds++;
527
1047
  }
528
1048
  // (a tableau begun has the rows asserted in kernel.ts's order, which its variables', so Bland's rule, follow)
@@ -564,6 +1084,14 @@ export function cdclSession(goal, root, opts = {}) {
564
1084
  lpSat = lp.kind === 'sat';
565
1085
  if (steps || (open && lp.kind === 'sat'))
566
1086
  return;
1087
+ // (the clausal mode, every clause satisfied: the simplex's point, where it is integral, is a model)
1088
+ if (clausal && !open && lpSat) {
1089
+ const w = pointOf(sx, rowsR);
1090
+ if (w) {
1091
+ verdict = { kind: 'sat', witness: w };
1092
+ return;
1093
+ }
1094
+ }
567
1095
  }
568
1096
  st.fmCalls++;
569
1097
  const rows = plain();
@@ -608,7 +1136,7 @@ export function cdclSession(goal, root, opts = {}) {
608
1136
  }
609
1137
  }
610
1138
  // Nothing open by this reading: the kernel's own reading of the trail (prove.ts's) has the last word.
611
- if (!pick) {
1139
+ if (!pick && !clausal) {
612
1140
  const p = pathOf(), more = openAt(goal, p, rowsAt(goal, p)).find(lin => Object.keys(lin).some(key => key !== '1') && !decidedLin(lin));
613
1141
  if (more) {
614
1142
  st.openMisses++;
@@ -620,16 +1148,25 @@ export function cdclSession(goal, root, opts = {}) {
620
1148
  levels.push(trail.length);
621
1149
  st.decisions++;
622
1150
  assign(pick, vars.get(pick).phase);
1151
+ if (clausal && lpSat)
1152
+ free = batch;
623
1153
  continue;
624
1154
  }
625
1155
  }
626
1156
  // Conflict analysis.
627
1157
  st.conflicts++;
628
1158
  sinceRestart++;
1159
+ free = 0;
1160
+ // (a clause's latest level, how many of its literals are at it, the latest of those on the trail, and the latest
1161
+ // level of the rest: one pass)
629
1162
  let c = conflict;
1163
+ if (clausal)
1164
+ c = analyzeClausal(c);
630
1165
  for (;;) {
631
1166
  if (!c.lits.size) {
632
1167
  if (opts.model) {
1168
+ if (wantDag)
1169
+ return { stuck: 'unknown', path: new Map(), why: REFUTED, dag: { nodes, top: c.node, clausal } };
633
1170
  if (!wantCore)
634
1171
  return { stuck: 'unknown', path: new Map(), why: REFUTED };
635
1172
  // the hypotheses the leaves below the empty clause read (a clause never made into a node, a bound's not yet
@@ -660,34 +1197,30 @@ export function cdclSession(goal, root, opts = {}) {
660
1197
  st.proven++;
661
1198
  return { tree, nodes: budget.nodes };
662
1199
  }
663
- const top = Math.max(...[...c.lits.keys()].map(name => vars.get(name).level));
1200
+ const { top, here, latest } = levelsOf(c);
664
1201
  if (top < level()) {
665
1202
  undoTo(top);
666
1203
  qhead = trail.length;
667
1204
  }
668
- const here = [...c.lits.keys()].filter(name => vars.get(name).level === top);
669
1205
  if (top === 0) {
670
- c = resolveOn(c, here.reduce((a, b) => (vars.get(a).at > vars.get(b).at ? a : b)));
1206
+ c = resolveOn(c, latest);
671
1207
  continue;
672
1208
  }
673
- if (here.length === 1)
1209
+ if (here === 1)
674
1210
  break;
675
- const latest = here.reduce((a, b) => (vars.get(a).at > vars.get(b).at ? a : b));
676
1211
  if (vars.get(latest).reason === undefined)
677
1212
  break;
678
1213
  c = resolveOn(c, latest);
679
1214
  }
680
- const top = Math.max(...[...c.lits.keys()].map(name => vars.get(name).level));
681
- const here = [...c.lits.keys()].filter(name => vars.get(name).level === top);
1215
+ const { top, here, latest: uip, below } = levelsOf(c);
682
1216
  bump(c.lits);
683
1217
  const learned = addClause(c.lits, c.node);
684
- if (here.length !== 1) {
1218
+ if (here !== 1) {
685
1219
  undoTo(Math.max(0, top - 1));
686
1220
  qhead = Math.min(qhead, trail.length);
687
1221
  continue;
688
1222
  }
689
- const uip = here[0];
690
- undoTo(Math.max(0, ...[...c.lits.keys()].filter(name => name !== uip).map(name => vars.get(name).level)));
1223
+ undoTo(below);
691
1224
  qhead = trail.length;
692
1225
  assign(uip, !c.lits.get(uip), learned);
693
1226
  if (sinceRestart >= restartAt) {
@@ -698,7 +1231,13 @@ export function cdclSession(goal, root, opts = {}) {
698
1231
  }
699
1232
  }
700
1233
  };
701
- return { run };
1234
+ // A hypothesis read no more (clausal mode): its clauses out of propagation and of what a decision reads. Sound where
1235
+ // nothing else reads its gates (the caller's `sideOf` gives it gates of its own) and nothing later asks it to hold:
1236
+ // the clauses learned from it stay consequences of the goal with its gates' definitions, which any model of the rest
1237
+ // extends to (a gate its formula's value).
1238
+ const retire = (hyp) => { for (const ci of byHyp[hyp] ?? [])
1239
+ retired[ci] = true; };
1240
+ return { run, retire };
702
1241
  }
703
1242
  // The DAG as a kernel tree below `root`, walked depth first with a reader of its own (the tree's path is a stack, as
704
1243
  // the search's trail is): each leaf's derivation found again among the rows at its tree path, in kernel.ts's order (the
@@ -728,6 +1267,8 @@ function unfold(goal, nodes, top, root, maxLeaves, until) {
728
1267
  pop();
729
1268
  return no && { split: n.on, yes, no };
730
1269
  }
1270
+ if ('hyp' in n)
1271
+ return undefined; // (the clausal mode's: never unfolded, a model alone wanted there)
731
1272
  if (++leaves > maxLeaves || late(until)) {
732
1273
  cdclStats.unfoldWhy = leaves > maxLeaves ? 'leaves' : 'time';
733
1274
  return undefined;