gdp-wired 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,9 +16,10 @@
16
16
  // then the forms a counterexample breaks, as IC3's relative induction, then all), each asked first of the CDCL
17
17
  // search for a model alone (a refutation's core: the forms it read), a counterexample the whole set allows joined in
18
18
  // (the hull grows to hold it, a bound rises to the next of the rule's constants, then goes), one to a caller's law
19
- // ruled out by a candidate or, where none does, by a cube blocked as IC3 blocks one (its control state and the
20
- // bounds that keep the samples out, the literals its refutation's core read, its predecessors blocked first); every
21
- // goal of the cone proven, the cone is the answer
19
+ // ruled out by a candidate or by a cube blocked as IC3 blocks one (its control state, the rule's own comparisons
20
+ // true there and the bounds that keep the samples out, the literals its refutation's core read, its predecessors
21
+ // blocked first), the cube first where no sample is at its control state; every goal of the cone proven, the cone
22
+ // is the answer
22
23
  // - the kernel (where the join proves nothing, as it was): the laws with the candidates chosen so far, proven one law
23
24
  // at a time; when a goal is stuck at a step, its witness is a counterexample to induction, so the candidate that
24
25
  // rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
@@ -60,12 +61,14 @@ const joinExtras = 24, joinTries = 40, joinBits = 7, joinKeys = 128, joinAttempt
60
61
  const joinNevers = env.GDP_JOIN_NEVERS !== '0';
61
62
  const joinNeversBreaks = 1;
62
63
  const joinCore = env.GDP_JOIN_CORE !== '0';
63
- // Cubes blocked where no candidate rules a counterexample out (GDP_JOIN_CUBES=0: none): at most 48 in all, each tried 8
64
- // times, its predecessors blocked first 3 deep, each query's budget 2 s (counted, or wall time where timed).
64
+ // Cubes blocked for a counterexample to a caller's law (GDP_JOIN_CUBES=0: none), before any candidate is tried where
65
+ // no sample holds its control state, else where none rules it out: at most 48 in all, each tried 8 times, its
66
+ // predecessors blocked first 8 deep, each query's budget 2 s (counted, or wall time where timed).
65
67
  const joinCubes = env.GDP_JOIN_CUBES !== '0';
66
- const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 3, joinCubeMs = 2000;
67
- // Once a cube is in the set, the join has 0.3 of what is left of its time (the search below the rest).
68
- const joinCubeWindow = 0.3;
68
+ const joinCubeMax = 48, joinCubeTries = 8, joinCubeDepth = 8, joinCubeMs = 2000;
69
+ // GDP_JOIN_ATOMS=0: a cube's literals at a point its control values and the samples' bounds alone (else the rule's own
70
+ // comparisons true there too).
71
+ const joinAtoms = env.GDP_JOIN_ATOMS !== '0';
69
72
  // GDP_JOIN_PRIME=0: each control state no state reached a form of its own, every value read.
70
73
  const joinPrime = env.GDP_JOIN_PRIME !== '0';
71
74
  // GDP_JOIN_DOWN=0: a blocked cube kept as its refutation's core cuts it (no literal dropped); joinDownQueries, the
@@ -156,9 +159,6 @@ const keyValue = (cell, w) => {
156
159
  }
157
160
  return value;
158
161
  };
159
- // The linear comparisons a machine's conditions make over the state alone (its assumption, its step's conditions and the
160
- // laws), as coefficients over the atoms given (an integer atom's two parts with opposite coefficients): the directions
161
- // a bound of the join may take beside the atoms' own.
162
162
  function comparisons(m, laws, atoms, coords) {
163
163
  const lin = (e, k, out) => {
164
164
  if (e.op === 'const') {
@@ -232,13 +232,15 @@ function comparisons(m, laws, atoms, coords) {
232
232
  if (neg)
233
233
  l.delete(neg[0]);
234
234
  }
235
+ const k0 = l.get('1') ?? 0;
235
236
  l.delete('1');
236
- if ([...l.values()].some(v => v !== 0) || coef.length < 2)
237
+ if ([...l.values()].some(v => v !== 0) || !coef.length)
237
238
  return;
238
239
  const g = coef.reduce((acc, [, cc]) => gcd(acc, cc), 0), t = coef.map(([i, cc]) => [i, cc / g]);
239
- if (t[0][1] < 0)
240
- t.forEach(p => { p[1] = -p[1]; });
241
- found.set(JSON.stringify(t), t);
240
+ const d = Math.floor((c.op === '<' ? -k0 - 1 : -k0) / g), u = t.map(([i, cc]) => [i, -cc]);
241
+ for (const r of [{ coef: t, d }, { coef: u, d: -d - 1 }, ...(c.op === '=' ? [{ coef: u, d: -d }, { coef: t, d: d - 1 }] : [])])
242
+ if (Number.isSafeInteger(r.d))
243
+ found.set(JSON.stringify(r), r);
242
244
  };
243
245
  if (m.assume)
244
246
  visitC(m.assume);
@@ -944,7 +946,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
944
946
  const pool0 = pool.slice(), ctis0 = ctis.length;
945
947
  if (joinOn && !mapNames.length && NS)
946
948
  try {
947
- const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * joinShare);
949
+ const jT0 = performance.now(), jUntil = Math.min(until, now() + (until - now()) * (opts.join ?? joinShare));
948
950
  // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
949
951
  // values reached a part of its own.
950
952
  const jChoice = modes.find(mo => mo.choice && !atoms[mo.atom].cell), bits = modes.filter(mo => mo.bool && !atoms[mo.atom].cell && !atoms[mo.atom].param);
@@ -963,14 +965,15 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
963
965
  for (const [c1, c2] of [[1, 1], [1, -1], [-1, 1], [-1, -1]])
964
966
  out.push([[i, c1], [j, c2]]);
965
967
  const known = new Set(out.map(t => JSON.stringify(t)));
966
- for (const t of comparisons(m, laws, atoms, cs))
967
- for (const u of [t, t.map(([i, c]) => [i, -c])]) {
968
- const k2 = JSON.stringify(u);
969
- if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
970
- known.add(k2);
971
- out.push(u);
968
+ for (const { coef } of comparisons(m, laws, atoms, cs))
969
+ if (coef.length > 1)
970
+ for (const u of coef[0][1] > 0 ? [coef, coef.map(([i, c]) => [i, -c])] : []) {
971
+ const k2 = JSON.stringify(u);
972
+ if (!known.has(k2) && out.length < 2 * cs.length + 4 * joinPairs * joinPairs + 64) {
973
+ known.add(k2);
974
+ out.push(u);
975
+ }
972
976
  }
973
- }
974
977
  return out;
975
978
  };
976
979
  const dirs = directions(coords);
@@ -1230,10 +1233,17 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1230
1233
  return { scalars: sc, maps: {} };
1231
1234
  };
1232
1235
  const vecOf = (st) => valuesOf(pointOf({}, st).scalar);
1233
- // The cube of a point the samples leave out: its control literals, then the direction that leaves out the most
1234
- // samples still in, its bound as weak as leaves them out, until none is in (undefined: none leaves out the rest).
1236
+ // The cube of a point the samples leave out: its control literals and the rule's own comparisons true there (where
1237
+ // no sample is, a location the runs never reached, a cube of its control values alone isn't blocked: its
1238
+ // predecessors take it back to the samples; the comparisons are what a predecessor's guards say, as Spacer's
1239
+ // projections read them), then the direction that leaves out the most samples still in, its bound as weak as
1240
+ // leaves them out, until none is in (undefined: none leaves out the rest).
1241
+ const ruleLits = joinAtoms ? comparisons(m, laws, atoms, lc).map(lin => ({ lin })) : [];
1235
1242
  const cubeOf = (v) => {
1236
1243
  const lits = ctrl.map(i => ({ at: { atom: i, value: v[i] } }));
1244
+ for (const l of ruleLits)
1245
+ if (litHolds(l, v))
1246
+ lits.push(l);
1237
1247
  let alive = S.filter(s2 => inCube(lits, s2));
1238
1248
  while (alive.length) {
1239
1249
  let best = -1, bestN = 0;
@@ -1308,7 +1318,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1308
1318
  // Is the cube's negation inductive relative to these laws (the caller's and the kinds' beside)? Its literals after
1309
1319
  // the step are hypotheses of their own, so the refutation's core names those it read.
1310
1320
  const queryWith = (c, frame) => {
1311
- const f = formOf(c), ls = [...given, ...frame, lawFor(f)], mm = forLaws(ls).m;
1321
+ const f = formOf(c), own = lawFor(f), names2 = new Set([own.name]), ls = [...given, ...frame.filter(l => !names2.has(l.name) && !!names2.add(l.name)), own], mm = forLaws(ls).m;
1312
1322
  const g = obligations(mm, ls, {}, ls.length - 1)[1], last = g.hyps.at(-1);
1313
1323
  const inner = last.op === 'not' && last.x.op === 'not' && last.x.x.op === 'and' && last.x.x.xs.length === c.length ? last.x.x.xs : undefined;
1314
1324
  const tails = inner ?? [last], hyps = [...g.hyps.slice(0, -1), ...tails], base = hyps.length - tails.length;
@@ -1321,13 +1331,13 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1321
1331
  return { ok: false, ...witnessStep(out.witness) };
1322
1332
  return undefined;
1323
1333
  };
1324
- // A counterexample to a caller's law no candidate rules out: its cube (its control state and the bounds that keep
1334
+ // A counterexample to a caller's law: its cube (its control state, the rule's comparisons and the bounds that keep
1325
1335
  // the samples out), blocked relative to the set (the set assumed before the step, and the cube's own negation, as
1326
1336
  // IC3's relative induction), its literals after the step those the refutation read (its core), the samples and the
1327
1337
  // start kept out. A predecessor the set allows into the cube: its own cube blocked first (a few deep), else the
1328
1338
  // cube made smaller to leave the predecessor's successor out. Each cube blocked is a form of the set (a
1329
1339
  // disjunction: never all its literals), which the join keeps or drops as any other.
1330
- let cubed = 0, cubeWhy = '', cubeUntil = Infinity;
1340
+ let cubed = 0, cubeWhy = '';
1331
1341
  // IC3's generalization of a cube blocked (Bradley's down, literal dropping as Een, Mishchenko and Brayton's): the
1332
1342
  // literals taken out a part at a time (half of them, then quarters, ..., then one by one), a part kept out where the
1333
1343
  // cube without it still leaves the start and the samples out and is still blocked relative to the same laws (the
@@ -1418,12 +1428,6 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1418
1428
  why = 'time';
1419
1429
  break;
1420
1430
  }
1421
- // (once a cube is in the set, the join has a part of what is left, the search below the rest: the cubes are
1422
- // for counterexamples no candidate rules out, which the search below rules out its own way)
1423
- if (now() > cubeUntil) {
1424
- why = 'cubes';
1425
- break;
1426
- }
1427
1431
  rounds++;
1428
1432
  set = [...formsNow(), ...extras].filter(f => !blocked.has(textOf(f)));
1429
1433
  const byText = new Map(set.map(f => [textOf(f), f]));
@@ -1522,9 +1526,22 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1522
1526
  }
1523
1527
  if (outside || breaks(params, post)) {
1524
1528
  // the caller's law broken from a state the set allows: a candidate false there and at every state reached, the
1525
- // one false at the most such states (then the smallest), or one made from it (fromCti)
1529
+ // one false at the most such states (then the smallest), or one made from it (fromCti); else its cube blocked,
1530
+ // as IC3 blocks one. Where no sample holds its control state (the samples say nothing of it) the cube comes first.
1526
1531
  negs.push(pre);
1527
1532
  ctis.push(pre);
1533
+ const pv = valuesOf(pre.scalar), alone = !S.some(s2 => ctrl.every(i => s2[i] === pv[i]));
1534
+ const cube = () => {
1535
+ if (outside || !joinCubes || !initVec || cubed >= joinCubeMax)
1536
+ return false;
1537
+ const made = blockCube(pv, joinCubeDepth, set), fresh = made.filter((f, i) => !set.some(g2 => textOf(g2) === textOf(f)) && made.findIndex(g2 => textOf(g2) === textOf(f)) === i);
1538
+ opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1539
+ cubed += fresh.length;
1540
+ extras.push(...fresh);
1541
+ return fresh.length > 0;
1542
+ };
1543
+ if (alone && cube())
1544
+ continue;
1528
1545
  const pick = (fs) => { let bestF, score = -Infinity; for (const f of fs) {
1529
1546
  if (f.cells || f.cong || extras.includes(f) || blocked.has(textOf(f)) || holdsAt(f, pre) || !reached.every(p2 => holdsAt(f, p2)))
1530
1547
  continue;
@@ -1542,17 +1559,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1542
1559
  if (next)
1543
1560
  tried++;
1544
1561
  opts.progress?.('join', { round: rounds, set: set.length, ms: qms, target: next ? textOf(next).slice(0, 60) : 'none' });
1545
- if (!next && !outside && joinCubes && initVec && cubed < joinCubeMax && now() < jUntil) {
1546
- const made = blockCube(valuesOf(pre.scalar), joinCubeDepth, set);
1547
- opts.progress?.('join', { round: rounds, set: set.length, cubes: made.map(f => textOf(f).slice(0, 100)).join('; ') || `none: ${cubeWhy}` });
1548
- if (made.length) {
1549
- if (!cubed)
1550
- cubeUntil = now() + (jUntil - now()) * joinCubeWindow;
1551
- cubed += made.length;
1552
- extras.push(...made);
1553
- continue;
1554
- }
1555
- }
1562
+ if (!next && !alone && cube())
1563
+ continue;
1556
1564
  if (!next) {
1557
1565
  why = 'target';
1558
1566
  break;
@@ -2,7 +2,6 @@
2
2
  // - interpret / compileJs: the runtime, as an interpreter and as generated JavaScript
3
3
  // - prove: each law by induction (holds at the start, one step preserves it), with every case decided by solver.ts
4
4
  // - search: real counterexample traces from the start, by bounded enumeration of short request sequences
5
- // - strengthen (invariant.ts): candidate invariants dropped until the rest are inductive (Houdini)
6
5
  // Arithmetic is linear: +, −, × by a constant, min, max, if. Maps are naturals indexed by naturals, every cell starting
7
6
  // at the same value; a law about a map holds for every key x, and is proven at one arbitrary x (with the law assumed at
8
7
  // every other key the step reads).
@@ -362,9 +362,10 @@ function search(l, opts) {
362
362
  // 1. Random runs: the states they reach, each with its stem; a lasso on the way is tried at once.
363
363
  const visits = [], bounds = [1, 2, 4, 8, 16, 64];
364
364
  try {
365
- // (a fifth of the time, at most 1.5 s, unless only lassos are asked for; at most 4,000 states kept, then only a
366
- // run's last)
367
- while (now() < (opts.lassos ? until : Math.min(t0 + (until - t0) * 0.2, t0 + 1500))) {
365
+ // (a fifth of the time, at most 1.5 s, a run too, unless only lassos are asked for; at most 4,000 states kept, then
366
+ // only a run's last)
367
+ const runsUntil = opts.lassos ? until : Math.min(t0 + (until - t0) * 0.2, t0 + 1500);
368
+ while (now() < runsUntil) {
368
369
  const bound = bounds[stats.runs++ % bounds.length], ps = drawParams(bound);
369
370
  if (!ps)
370
371
  continue;
@@ -372,7 +373,7 @@ function search(l, opts) {
372
373
  const stem = [], seen = new Map(), trail = [], run = { n: 0 };
373
374
  if (visits.length < 4000)
374
375
  visits.push({ params: ps, trail: stem, at: 0, st, run });
375
- for (let n = 0; n < 3000 && now() < until; n++) {
376
+ for (let n = 0; n < 3000 && now() < runsUntil; n++) {
376
377
  const key = keyOf(st), back = seen.get(key);
377
378
  if (back !== undefined) {
378
379
  const cycle = trail.slice(back).map((s, j) => ({ st: s, input: stem[back + j] }));
@@ -417,9 +418,9 @@ function search(l, opts) {
417
418
  if (v.run && (ends.get(v.run)?.at ?? -1) < v.at)
418
419
  ends.set(v.run, v);
419
420
  const runs = [...ends.values()].sort((a, b) => b.at - a.at).slice(0, 20).map(v => ({ params: v.params, inputs: stemOf(v) }));
420
- // A set's closure (`budget`: when it stops), then, where no stem is known, a bounded run (core/bmc.ts: the kernel's
421
- // k-step goal's model, the set's complement as the law it breaks), then the kernel's check of each stem; `late`
422
- // where the closure ran out of time.
421
+ // A set's closure (`budget`: when it stops), then, where no stem is known, the accelerated runs' search deeper and a
422
+ // bounded run (core/bmc.ts: the kernel's k-step goal's model, the set's complement as the law it breaks), then the
423
+ // kernel's check of each stem; `late` where the closure ran out of time.
423
424
  const attempt = (a, goal, stems, cut, budget) => {
424
425
  // (a model of the CDCL search whose products don't multiply out goes on to the plain search, which multiplies rows)
425
426
  const was = realModels.on;
@@ -434,6 +435,15 @@ function search(l, opts) {
434
435
  if (!('tree' in out))
435
436
  return out.stuck === 'unknown' && out.why !== undefined ? 'late' : undefined;
436
437
  stats.accelClosed++;
438
+ // (the accelerated runs' search again, deeper: fun9's stem of 30 turns)
439
+ if (!stems.length && now() < until)
440
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(until, now() + 1000), deepen: true })) {
441
+ const c = cut(t);
442
+ if (c) {
443
+ stems.push(c);
444
+ break;
445
+ }
446
+ }
437
447
  if (!stems.length && now() < until) {
438
448
  const left = Math.min(until - now(), 2000);
439
449
  const run = findBoundedRun(m, [{ name: 'outside the set', holds: { op: 'not', x: a.set } }], { ms: left, depth: 24, ...(opts.counted ? {} : { wall: performance.now() + left }) });
@@ -458,6 +468,7 @@ function search(l, opts) {
458
468
  // (sets with a small goal that the accelerated runs' search, run to its end, doesn't reach: after the rest, their
459
469
  // closures and bounded runs, in the time the search has left)
460
470
  const later = [];
471
+ let deepened = 0;
461
472
  const again = [];
462
473
  for (const a of accelerated(l, { now, until: accelUntil, runs, io: { start, turn } })) {
463
474
  stats.accel++;
@@ -502,6 +513,15 @@ function search(l, opts) {
502
513
  if (++n >= 4)
503
514
  break;
504
515
  }
516
+ // (a set that search, run to its end, doesn't reach: again deeper, at most 500 ms, for the first four)
517
+ if (!stems.length && report.exhausted && deepened++ < 4)
518
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(longUntil, now() + 500), deepen: true })) {
519
+ const c = cut(t);
520
+ if (c) {
521
+ stems.push(c);
522
+ break;
523
+ }
524
+ }
505
525
  }
506
526
  // (a set the accelerated runs' search, run to its end, doesn't reach is left: the time goes to sets a run
507
527
  // reaches; a small one is tried after them)
@@ -66,6 +66,27 @@ export declare const canon: (l: Lin) => string;
66
66
  export declare const work: {
67
67
  n: number;
68
68
  };
69
+ export declare const costs: {
70
+ solves: number;
71
+ solveRows: number;
72
+ fm: number;
73
+ fpivots: number;
74
+ fcells: number;
75
+ cdclNodes: number;
76
+ cdclRows: number;
77
+ scan: number;
78
+ pivots: number;
79
+ pivotRows: number;
80
+ plainNodes: number;
81
+ plainRows: number;
82
+ values: number;
83
+ copies: number;
84
+ edges: number;
85
+ unitRows: number;
86
+ unfoldRows: number;
87
+ goalNodes: number;
88
+ translateRows: number;
89
+ };
69
90
  export declare function solve(constraints: Constraint[], maxRows?: number, integral?: boolean): Verdict;
70
91
  export declare const ratioRow: (T: Float64Array[], basis: number[], enter: number, cols: number, eps: number) => [number, number];
71
92
  export declare function pivot(T: Float64Array[], z: Float64Array | undefined, basis: number[], leave: number, enter: number, cols: number): void;
@@ -100,8 +100,13 @@ export const canon = (l) => JSON.stringify(Object.keys(l).sort().map(x => [x, l[
100
100
  // five times as many before merging them, it gives up with `unknown`.
101
101
  // The rows the solver has read and made, which a counted search reads as its clock (kernel/prove.ts's `counted`).
102
102
  export const work = { n: 0 };
103
+ // What the searches did, by kind, beside work.n (research/query reads them: the cost of each query's parts).
104
+ export const costs = { solves: 0, solveRows: 0, fm: 0, fpivots: 0, fcells: 0, cdclNodes: 0, cdclRows: 0, scan: 0, pivots: 0, pivotRows: 0, plainNodes: 0, plainRows: 0,
105
+ values: 0, copies: 0, edges: 0, unitRows: 0, unfoldRows: 0, goalNodes: 0, translateRows: 0 };
103
106
  export function solve(constraints, maxRows = 20_000, integral = true) {
104
107
  work.n += constraints.length;
108
+ costs.solves++;
109
+ costs.solveRows += constraints.length;
105
110
  const steps = [];
106
111
  const lins = [], stricts = [];
107
112
  const push = (step, lin, strict = false) => (steps.push(step), lins.push(lin), stricts.push(strict), lins.length - 1);
@@ -226,6 +231,7 @@ export function solve(constraints, maxRows = 20_000, integral = true) {
226
231
  if (choice.pos.length * choice.neg.length > 5 * maxRows)
227
232
  return { kind: 'unknown' };
228
233
  work.n += choice.pos.length * choice.neg.length;
234
+ costs.fm += choice.pos.length * choice.neg.length;
229
235
  exact &&= choice.isExact;
230
236
  eliminated.push({ x: choice.x, rows: [...choice.pos, ...choice.neg] });
231
237
  const next = rows.filter(r => (lins[r][choice.x] ?? 0) === 0);
@@ -417,6 +423,8 @@ export function refuteFast(constraints, maxRows = 2_000, integral = true) {
417
423
  const eps = 1e-9;
418
424
  for (let iter = 0; iter < 50 * (R + m); iter++) {
419
425
  work.n += 1 + ((R * cols) >> 8);
426
+ costs.fpivots++;
427
+ costs.fcells += (R * cols) >> 8;
420
428
  // Bland's rule: the first column with a negative reduced cost enters (no cycling on degenerate systems).
421
429
  let enter = -1;
422
430
  for (let j = 0; j < cols; j++)
@@ -10,11 +10,11 @@
10
10
  // keys over Ω the node's path doesn't yet compare) is grown again on the node's goal at its path (`regrown`); a split the
11
11
  // node's path already decides is followed, not made again.
12
12
  import { walk } from "./machine.js";
13
- import { add, env, refuteFast, scale, solve } from "./solver.js";
13
+ import { add, costs, env, refuteFast, scale, solve } from "./solver.js";
14
14
  import { checkRefutation } from "./check.js";
15
- import { canon, canonFlip, columnTerm, factorsOf, isCell, isMonomial, leafConstraintsReusing, linear, substE, truth, withProducts } from "../kernel/kernel.js";
16
- import { cellProducts, clock, grow, parseKey } from "../kernel/prove.js";
17
- import { times } from "../kernel/reader.js";
15
+ import { canon, canonFlip, columnTerm, factorsOf, isCell, isMonomial, leafConstraints, leafConstraintsReusing, linear, substE, truth, withProducts } from "../kernel/kernel.js";
16
+ import { cellProducts, clock, grow, leafRowsOf, parseKey } from "../kernel/prove.js";
17
+ import { Reader, times } from "../kernel/reader.js";
18
18
  const omega = 'O$';
19
19
  const debugOn = () => !!env.GDP_CYCLIC_DEBUG;
20
20
  // A cell's key, from its name (`M[key]`, the key's canonical text, whose names may be cells themselves).
@@ -89,6 +89,45 @@ const known = (lin, wp) => {
89
89
  const b = wp.get(canonFlip(lin));
90
90
  return b ? !b.holds : undefined;
91
91
  };
92
+ const trailed = new WeakMap();
93
+ function rowsAt(g, wp) {
94
+ // (a path with an atom about a term column, a cut's, read by kernel.ts: the reader's columns aren't kept for those)
95
+ for (const a of wp.values())
96
+ for (const key in a.lin)
97
+ if (key.startsWith('⟦'))
98
+ return leafConstraintsReusing(g, wp);
99
+ let t = trailed.get(g);
100
+ if (!t) {
101
+ const stack = [], on = new Map(), stamps = [];
102
+ t = { stack, on, stamps, n: 0, reader: new Reader(g, { get: name => on.get(name), stamp: at => stamps[at], size: () => stack.length, lin: at => stack[at] }) };
103
+ trailed.set(g, t);
104
+ }
105
+ const s = t, ps = [...wp];
106
+ let k = 0;
107
+ while (k < s.stack.length && k < ps.length && s.stack[k].name === ps[k][0] && s.stack[k].holds === ps[k][1].holds)
108
+ k++;
109
+ while (s.stack.length > k) {
110
+ const name = s.stack.pop().name;
111
+ s.on.delete(name);
112
+ s.reader.touch(name);
113
+ }
114
+ for (const [name, a] of ps.slice(k)) {
115
+ s.on.set(name, { val: a.holds, at: s.stack.length });
116
+ s.stamps[s.stack.length] = ++s.n;
117
+ s.stack.push({ name, lin: a.lin, holds: a.holds });
118
+ s.reader.touch(name);
119
+ }
120
+ s.reader.begin();
121
+ const rows = s.reader.leafRows();
122
+ if (env.GDP_CDCL_VERIFY === '1') {
123
+ const kr = leafConstraints(g, wp);
124
+ if (kr.length !== rows.length || kr.some((r, j) => canon(r.lin) !== canon(rows[j].lin))) {
125
+ const j = kr.findIndex((r, j2) => canon(r.lin) !== canon(rows[j2]?.lin ?? {}));
126
+ throw new Error(`reader.ts's rows differ from kernel.ts's at a translated leaf of ${g.name}: ${kr.length} vs ${rows.length}, at ${j}: ${JSON.stringify(kr[j])} vs ${JSON.stringify(rows[j]?.lin)}; path ${JSON.stringify([...wp].map(([key, a]) => [key, a.holds]))}`);
127
+ }
128
+ }
129
+ return rows;
130
+ }
92
131
  // The node's goal grown at a path (cell products on, as every cyclic goal is), within the deadline.
93
132
  function regrow(whole, wp, until) {
94
133
  const was = cellProducts.on;
@@ -132,18 +171,29 @@ export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp
132
171
  const no = yes && translate(part, whole, tree.no, ren0, st, until, new Map(pp).set(id, { lin: tree.split, holds: false }), new Map(wp).set(wid, { lin: wl, holds: false }), swaps);
133
172
  return yes && no ? { split: wl, yes, no } : undefined;
134
173
  }
135
- const rp = leafConstraintsReusing(part, pp), rw = leafConstraintsReusing(whole, wp), at = new Map();
174
+ // (past its budget, no translation: each leaf reads the two goals' rows whole, counted, so a large tree's stops there)
175
+ if (clock() > until)
176
+ return undefined;
177
+ // (the usual leaf's rows as its search kept them, where it did: kernel/prove.ts's leafRowsOf; else read again)
178
+ const kept = !tree.products && !tree.squares ? leafRowsOf.get(tree) : undefined;
179
+ const rp = kept ? undefined : leafConstraintsReusing(part, pp), rw = rowsAt(whole, wp), at = new Map();
180
+ const np = kept ? kept.n : rp.length, linP = (i) => (kept ? kept.at.get(i).lin : rp[i].lin);
181
+ const pairP = (i) => { if (kept) {
182
+ const s = kept.at.get(i)?.src;
183
+ return Array.isArray(s) ? s : undefined;
184
+ } const s = rp[i].src; return s && 'pair' in s ? s.pair : undefined; };
185
+ costs.translateRows += (rp?.length ?? 0) + rw.length;
136
186
  rw.forEach((r, i) => { const key = canon(r.lin); if (!at.has(key))
137
187
  at.set(key, i); });
138
188
  // Two cells the usual path proves equal (a row of the leaf's from their pair) are cells over time here, at keys
139
189
  // (t − 1) + a·Ω and (t − 1) + b·Ω: the path has a = b, and the keys' difference (a − b)·Ω is split (each other side
140
190
  // refuted by (a − b)·Ω = 0, the product of a − b <= 0 or b − a <= 0 with Ω >= 0), the leaf then read again.
141
- const usedRows = [...tree.leaf.flatMap(x => (x.kind === 'input' ? [x.index] : [])), ...(tree.products ?? []).flat()].filter(i => i < rp.length);
191
+ const usedRows = [...tree.leaf.flatMap(x => (x.kind === 'input' ? [x.index] : [])), ...(tree.products ?? []).flat()].filter(i => i < np);
142
192
  for (const i of usedRows) {
143
- const src = rp[i].src;
144
- if (!src || !('pair' in src))
193
+ const pair = pairP(i);
194
+ if (!pair)
145
195
  continue;
146
- const a = ren({ [src.pair[0]]: 1 }, wp), b = ren({ [src.pair[1]]: 1 }, wp), [ca] = Object.keys(a ?? {}), [cb] = Object.keys(b ?? {});
196
+ const a = ren({ [pair[0]]: 1 }, wp), b = ren({ [pair[1]]: 1 }, wp), [ca] = Object.keys(a ?? {}), [cb] = Object.keys(b ?? {});
147
197
  if (!ca || !cb || !isCell(ca) || !isCell(cb))
148
198
  continue;
149
199
  const d = add(keyOf(ca), scale(keyOf(cb), -1)), q0 = {};
@@ -167,8 +217,8 @@ export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp
167
217
  }
168
218
  }
169
219
  st.leaves++;
170
- const map = (i) => { if (i >= rp.length)
171
- return i - rp.length + rw.length; const l = ren(rp[i].lin, wp); return l && at.get(canon(l)); };
220
+ const map = (i) => { if (i >= np)
221
+ return i - np + rw.length; const l = ren(linP(i), wp); return l && at.get(canon(l)); };
172
222
  const leaf = [], products = [], squares = (tree.squares ?? []).map(s => ren(s, wp));
173
223
  let ok = squares.every(Boolean);
174
224
  for (const s of ok ? tree.leaf : []) {
@@ -194,8 +244,8 @@ export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp
194
244
  if (ok && checkRefutation(withProducts(rw, products, squares), leaf))
195
245
  return { leaf, ...(tree.products ? { products } : {}), ...(tree.squares ? { squares: squares } : {}) };
196
246
  if (debugOn()) {
197
- const missing = tree.leaf.flatMap(s => (s.kind === 'input' && s.index < rp.length && map(s.index) === undefined ? [s.index] : []));
198
- console.error(`[leaf] ${whole.name}: ${ok ? 'rows found, refutation refused' : `${missing.length} rows missing`}${missing.slice(0, 3).map(i => `; ${JSON.stringify(rp[i].lin)} as ${JSON.stringify(ren(rp[i].lin, wp) ?? 'no form')}${rp[i].src ? ` (${JSON.stringify(rp[i].src)})` : ''}`).join('')}`);
247
+ const missing = tree.leaf.flatMap(s => (s.kind === 'input' && s.index < np && map(s.index) === undefined ? [s.index] : []));
248
+ console.error(`[leaf] ${whole.name}: ${ok ? 'rows found, refutation refused' : `${missing.length} rows missing`}${missing.slice(0, 3).map(i => `; ${JSON.stringify(linP(i))} as ${JSON.stringify(ren(linP(i), wp) ?? 'no form')}`).join('')}`);
199
249
  }
200
250
  return close(whole, wp, st, until);
201
251
  }
@@ -229,7 +279,7 @@ export function readsFirst(whole, reads, ren, inner, st, until, wp = new Map(),
229
279
  // A path where l >= 1 (two cells' keys apart by l = q·Ω) while q <= 0 is a row: refuted by q·Ω <= 0, the product of
230
280
  // that row and Ω >= 0.
231
281
  function apart(whole, wp, l, q, st, until) {
232
- const rows = leafConstraintsReusing(whole, wp), find = (x) => { const c = canon(x); return rows.findIndex(r => canon(r.lin) === c); };
282
+ const rows = rowsAt(whole, wp), find = (x) => { const c = canon(x); return rows.findIndex(r => canon(r.lin) === c); };
233
283
  const iq = find(q), io = find({ [omega]: -1 }), ia = find(add({ 1: 1 }, scale(l, -1)));
234
284
  if (iq >= 0 && io >= 0 && ia >= 0) {
235
285
  const leaf = [{ kind: 'input', index: ia }, { kind: 'input', index: rows.length }, { kind: 'combine', a: 0, b: 1, ma: 1, mb: 1 }], products = [[iq, io]];
@@ -285,7 +335,7 @@ export function decide(whole, conds, inner, st, until, wp = new Map()) {
285
335
  }
286
336
  // A leaf of `g` at the path: a hypothesis false there (its row 1 <= 0), or with `solveIt` the rows refuted by the solver.
287
337
  function leafAt(g, wp, solveIt, st) {
288
- const rows = leafConstraintsReusing(g, wp), absurd = rows.findIndex(r => Object.keys(r.lin).every(key => key === '1') && (r.lin['1'] ?? 0) > 0);
338
+ const rows = rowsAt(g, wp), absurd = rows.findIndex(r => Object.keys(r.lin).every(key => key === '1') && (r.lin['1'] ?? 0) > 0);
289
339
  if (absurd >= 0) {
290
340
  st.leaves++;
291
341
  return { leaf: [{ kind: 'input', index: absurd }] };
@@ -318,7 +368,7 @@ const open = (c, wp) => atomsOf(c, wp)?.find(l => known(l, wp) === undefined);
318
368
  // Two reads of one function at keys the path doesn't yet prove equal or apart, keys linear (keys through a choice's
319
369
  // column after the others: such a column is often one the path decides later).
320
370
  function cellAtom(g, wp) {
321
- const rows = leafConstraintsReusing(g, wp), names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
371
+ const rows = rowsAt(g, wp), names = [...new Set(rows.flatMap(r => Object.keys(r.lin)))].filter(isCell);
322
372
  let later;
323
373
  for (const [i, p] of names.entries())
324
374
  for (const q of names.slice(i + 1)) {
@@ -351,7 +401,7 @@ const choiceOf = (e, wp) => {
351
401
  return Object.keys(d).some(key => key !== '1') && known(d, wp) === undefined ? d : undefined;
352
402
  };
353
403
  function choiceAtom(g, wp) {
354
- const rows = leafConstraintsReusing(g, wp);
404
+ const rows = rowsAt(g, wp);
355
405
  for (const name of new Set(rows.flatMap(r => Object.keys(r.lin)))) {
356
406
  const e = name.startsWith('⟦') ? columnTerm(name) : undefined;
357
407
  const l = e && e.op === 'if' ? choiceOf(e, wp) : undefined;
@@ -387,7 +437,7 @@ function conclCells(g, wp) {
387
437
  // Two cells over time at keys u + a·Ω and u + b·Ω: a = b decided first, then the keys' difference, its other side
388
438
  // refuted by the product (`apart`).
389
439
  function omegaPair(g, wp) {
390
- const rows = leafConstraintsReusing(g, wp), names = [...new Set([...rows.flatMap(r => Object.keys(r.lin)), ...conclCells(g, wp)])].filter(isCell);
440
+ const rows = rowsAt(g, wp), names = [...new Set([...rows.flatMap(r => Object.keys(r.lin)), ...conclCells(g, wp)])].filter(isCell);
391
441
  for (const [i, p] of names.entries())
392
442
  for (const q of names.slice(i + 1)) {
393
443
  if (p.slice(0, p.indexOf('[')) !== q.slice(0, q.indexOf('[')))
@@ -545,7 +595,7 @@ export function carry(g, nFacts, nUses, st, until) {
545
595
  const y = side(yes), n = y && side(no);
546
596
  return y && n ? { split: next, yes: y, no: n } : undefined;
547
597
  };
548
- const quick = (wp) => { const rows = leafConstraintsReusing(g, wp), v = refuteFast(rows); if (v?.kind !== 'refuted')
598
+ const quick = (wp) => { const rows = rowsAt(g, wp), v = refuteFast(rows); if (v?.kind !== 'refuted')
549
599
  return undefined; st.leaves++; return { leaf: v.steps }; };
550
600
  return node(new Map(), false);
551
601
  }